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.
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/bin/interscale-mcp.mjs +3 -0
- package/bin/interscale.mjs +3 -0
- package/lib/file-hash-worker.mjs +2 -0
- package/lib/interscale-mcp.mjs +114 -0
- package/lib/interscale.mjs +665 -0
- package/lib/launcher.mjs +27 -0
- package/package.json +30 -4
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __interscaleRequire } from "node:module"; const require = __interscaleRequire(import.meta.url);
|
|
3
|
+
var xS=Object.create;var Fo=Object.defineProperty;var RS=Object.getOwnPropertyDescriptor;var OS=Object.getOwnPropertyNames;var IS=Object.getPrototypeOf,NS=Object.prototype.hasOwnProperty;var a=(t,e)=>Fo(t,"name",{value:e,configurable:!0}),W=(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 v=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var M=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},K=(t,e)=>{for(var r in e)Fo(t,r,{get:e[r],enumerable:!0})},AS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of OS(e))!NS.call(t,i)&&i!==r&&Fo(t,i,{get:()=>e[i],enumerable:!(n=RS(e,i))||n.enumerable});return t};var nr=(t,e,r)=>(r=t!=null?xS(IS(t)):{},AS(e||!t||!t.__esModule?Fo(r,"default",{value:t,enumerable:!0}):r,t));function qo(t){let e=[],r={},n=[];for(let i=0;i<t.length;i+=1){let s=t[i];if(s==="--"){n=t.slice(i+1);break}if(!s.startsWith("--")){e.push(s);continue}let o=s.indexOf("=");if(o>2){r[s.slice(2,o)]=s.slice(o+1);continue}let c=s.slice(2),l=t[i+1];l!==void 0&&!l.startsWith("--")?(r[c]=l,i+=1):r[c]=!0}return{positional:e,options:r,passthrough:n}}function A(t,e=!1){if(t===void 0)return e;if(t===!0||t==="true"||t==="1"||t==="yes")return!0;if(t===!1||t==="false"||t==="0"||t==="no")return!1;throw new Error(`Invalid boolean value: ${t}`)}var zo=v(()=>{a(qo,"parseArgs");a(A,"booleanOption")});var ir=M((PU,Nf)=>{"use strict";var Of=["nodebuffer","arraybuffer","fragments"],If=typeof Blob<"u";If&&Of.push("blob");Nf.exports={BINARY_TYPES:Of,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:If,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:a(()=>{},"NOOP")}});var ds=M(($U,Wo)=>{"use strict";var{EMPTY_BUFFER:LS}=ir(),ql=Buffer[Symbol.species];function CS(t,e){if(t.length===0)return LS;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 ql(r.buffer,r.byteOffset,n):r}a(CS,"concat");function Af(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}a(Af,"_mask");function Lf(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}a(Lf,"_unmask");function PS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}a(PS,"toArrayBuffer");function zl(t){if(zl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ql(t):ArrayBuffer.isView(t)?e=new ql(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),zl.readOnly=!1),e}a(zl,"toBuffer");Wo.exports={concat:CS,mask:Af,toArrayBuffer:PS,toBuffer:zl,unmask:Lf};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=W("bufferutil");Wo.exports.mask=function(e,r,n,i,s){s<48?Af(e,r,n,i,s):t.mask(e,r,n,i,s)},Wo.exports.unmask=function(e,r){e.length<32?Lf(e,r):t.unmask(e,r)}}catch{}});var Df=M((jU,Pf)=>{"use strict";var Cf=Symbol("kDone"),Wl=Symbol("kRun"),Hl=class{static{a(this,"Limiter")}constructor(e){this[Cf]=()=>{this.pending--,this[Wl]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Wl]()}[Wl](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Cf])}}};Pf.exports=Hl});var hi=M((BU,Mf)=>{"use strict";var us=W("zlib"),$f=ds(),DS=Df(),{kStatusCode:Uf}=ir(),$S=Buffer[Symbol.species],US=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),sr=Symbol("total-length"),di=Symbol("callback"),jr=Symbol("buffers"),ui=Symbol("error"),Ho,Gl=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,!Ho){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new DS(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[di];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){Ho.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){Ho.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"?us.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=us.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Go]=this,this._inflate[sr]=0,this._inflate[jr]=[],this._inflate.on("error",MS),this._inflate.on("data",jf)}this._inflate[di]=n,this._inflate.write(e),r&&this._inflate.write(US),this._inflate.flush(()=>{let s=this._inflate[ui];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=$f.concat(this._inflate[jr],this._inflate[sr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[sr]=0,this._inflate[jr]=[],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"?us.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=us.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[sr]=0,this._deflate[jr]=[],this._deflate.on("data",jS)}this._deflate[di]=n,this._deflate.write(e),this._deflate.flush(us.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=$f.concat(this._deflate[jr],this._deflate[sr]);r&&(s=new $S(s.buffer,s.byteOffset,s.length-4)),this._deflate[di]=null,this._deflate[sr]=0,this._deflate[jr]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};Mf.exports=Gl;function jS(t){this[jr].push(t),this[sr]+=t.length}a(jS,"deflateOnData");function jf(t){if(this[sr]+=t.length,this[Go]._maxPayload<1||this[sr]<=this[Go]._maxPayload){this[jr].push(t);return}this[ui]=new RangeError("Max payload size exceeded"),this[ui].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ui][Uf]=1009,this.removeListener("data",jf),this.reset()}a(jf,"inflateOnData");function MS(t){if(this[Go]._inflate=null,this[ui]){this[di](this[ui]);return}t[Uf]=1007,this[di](t)}a(MS,"inflateOnError")});var pi=M((qU,Jo)=>{"use strict";var{isUtf8:Bf}=W("buffer"),{hasBlob:BS}=ir(),FS=[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 qS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}a(qS,"isValidStatusCode");function Jl(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(Jl,"_isValidUTF8");function zS(t){return BS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}a(zS,"isBlob");Jo.exports={isBlob:zS,isValidStatusCode:qS,isValidUTF8:Jl,tokenChars:FS};if(Bf)Jo.exports.isValidUTF8=function(t){return t.length<24?Jl(t):Bf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=W("utf-8-validate");Jo.exports.isValidUTF8=function(e){return e.length<32?Jl(e):t(e)}}catch{}});var Zl=M((WU,Jf)=>{"use strict";var{Writable:WS}=W("stream"),Ff=hi(),{BINARY_TYPES:HS,EMPTY_BUFFER:qf,kStatusCode:GS,kWebSocket:JS}=ir(),{concat:Vl,toArrayBuffer:VS,unmask:YS}=ds(),{isValidStatusCode:XS,isValidUTF8:zf}=pi(),Vo=Buffer[Symbol.species],Ye=0,Wf=1,Hf=2,Gf=3,Yl=4,Xl=5,Yo=6,Kl=class extends WS{static{a(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||HS[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[JS]=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=Ye}_write(e,r,n){if(this._opcode===8&&this._state==Ye)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 Vo(n.buffer,n.byteOffset+e,n.length-e),new Vo(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 Vo(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 Ye:this.getInfo(e);break;case Wf:this.getPayloadLength16(e);break;case Hf:this.getPayloadLength64(e);break;case Gf:this.getMask();break;case Yl:this.getData(e);break;case Xl:case Yo: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[Ff.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=Wf:this._payloadLength===127?this._state=Hf: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=Gf:this._state=Yl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yl}getData(e){let r=qf;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&&YS(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Xl,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[Ff.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===Ye&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Ye;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=Vl(n,r):this._binaryType==="arraybuffer"?i=VS(Vl(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Ye):(this._state=Yo,setImmediate(()=>{this.emit("message",i,!0),this._state=Ye,this.startLoop(e)}))}else{let i=Vl(n,r);if(!this._skipUTF8Validation&&!zf(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Xl||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Ye):(this._state=Yo,setImmediate(()=>{this.emit("message",i,!1),this._state=Ye,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,qf),this.end();else{let n=e.readUInt16BE(0);if(!XS(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Vo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zf(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=Ye;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye):(this._state=Yo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye,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[GS]=i,o}};Jf.exports=Kl});var td=M((JU,Xf)=>{"use strict";var{Duplex:GU}=W("stream"),{randomFillSync:KS}=W("crypto"),{types:{isUint8Array:ZS}}=W("util"),Vf=hi(),{EMPTY_BUFFER:QS,kWebSocket:eT,NOOP:tT}=ir(),{isBlob:fi,isValidStatusCode:rT}=pi(),{mask:Yf,toBuffer:un}=ds(),Xe=Symbol("kByteLength"),nT=Buffer.alloc(4),Xo=8*1024,hn,mi=Xo,dt=0,iT=1,sT=2,Ql=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=dt,this.onerror=tT,this[eT]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||nT,r.generateMask?r.generateMask(n):(mi===Xo&&(hn===void 0&&(hn=Buffer.alloc(Xo)),KS(hn,0,Xo),mi=0),n[0]=hn[mi++],n[1]=hn[mi++],n[2]=hn[mi++],n[3]=hn[mi++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let c;typeof e=="string"?(!r.mask||o)&&r[Xe]!==void 0?c=r[Xe]:(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?(Yf(e,n,d,s,c),[d]):(Yf(e,n,e,0,c),[d,e])):[d,e]}close(e,r,n,i){let s;if(e===void 0)s=QS;else{if(typeof e!="number"||!rT(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(ZS(r))s.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Xe]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==dt?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):fi(e)?(i=e.size,s=!1):(e=un(e),i=e.length,s=un.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Xe]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};fi(e)?this._state!==dt?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==dt?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):fi(e)?(i=e.size,s=!1):(e=un(e),i=e.length,s=un.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Xe]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};fi(e)?this._state!==dt?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==dt?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[Vf.extensionName],s=r.binary?2:1,o=r.compress,c,l;typeof e=="string"?(c=Buffer.byteLength(e),l=!1):fi(e)?(c=e.size,l=!1):(e=un(e),c=e.length,l=un.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={[Xe]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};fi(e)?this._state!==dt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==dt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Xe],this._state=sT,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ed,this,c,i);return}this._bufferedBytes-=n[Xe];let o=un(s);r?this.dispatch(o,r,n,i):(this._state=dt,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(oT,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[Vf.extensionName];this._bufferedBytes+=n[Xe],this._state=iT,s.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ed(this,l,i);return}this._bufferedBytes-=n[Xe],this._state=dt,n.readOnly=!1,this.sendFrame(t.frame(c,n),i),this.dequeue()})}dequeue(){for(;this._state===dt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Xe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Xe],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)}};Xf.exports=Ql;function ed(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(ed,"callCallbacks");function oT(t,e,r){ed(t,e,r),t.onerror(e)}a(oT,"onError")});var sm=M((YU,im)=>{"use strict";var{kForOnEventAttribute:hs,kListener:rd}=ir(),Kf=Symbol("kCode"),Zf=Symbol("kData"),Qf=Symbol("kError"),em=Symbol("kMessage"),tm=Symbol("kReason"),_i=Symbol("kTarget"),rm=Symbol("kType"),nm=Symbol("kWasClean"),or=class{static{a(this,"Event")}constructor(e){this[_i]=null,this[rm]=e}get target(){return this[_i]}get type(){return this[rm]}};Object.defineProperty(or.prototype,"target",{enumerable:!0});Object.defineProperty(or.prototype,"type",{enumerable:!0});var pn=class extends or{static{a(this,"CloseEvent")}constructor(e,r={}){super(e),this[Kf]=r.code===void 0?0:r.code,this[tm]=r.reason===void 0?"":r.reason,this[nm]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Kf]}get reason(){return this[tm]}get wasClean(){return this[nm]}};Object.defineProperty(pn.prototype,"code",{enumerable:!0});Object.defineProperty(pn.prototype,"reason",{enumerable:!0});Object.defineProperty(pn.prototype,"wasClean",{enumerable:!0});var gi=class extends or{static{a(this,"ErrorEvent")}constructor(e,r={}){super(e),this[Qf]=r.error===void 0?null:r.error,this[em]=r.message===void 0?"":r.message}get error(){return this[Qf]}get message(){return this[em]}};Object.defineProperty(gi.prototype,"error",{enumerable:!0});Object.defineProperty(gi.prototype,"message",{enumerable:!0});var ps=class extends or{static{a(this,"MessageEvent")}constructor(e,r={}){super(e),this[Zf]=r.data===void 0?null:r.data}get data(){return this[Zf]}};Object.defineProperty(ps.prototype,"data",{enumerable:!0});var aT={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[hs]&&i[rd]===e&&!i[hs])return;let n;if(t==="message")n=a(function(s,o){let c=new ps("message",{data:o?s:s.toString()});c[_i]=this,Ko(e,this,c)},"onMessage");else if(t==="close")n=a(function(s,o){let c=new pn("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[_i]=this,Ko(e,this,c)},"onClose");else if(t==="error")n=a(function(s){let o=new gi("error",{error:s,message:s.message});o[_i]=this,Ko(e,this,o)},"onError");else if(t==="open")n=a(function(){let s=new or("open");s[_i]=this,Ko(e,this,s)},"onOpen");else return;n[hs]=!!r[hs],n[rd]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[rd]===e&&!r[hs]){this.removeListener(t,r);break}}};im.exports={CloseEvent:pn,ErrorEvent:gi,Event:or,EventTarget:aT,MessageEvent:ps};function Ko(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}a(Ko,"callListener")});var Zo=M((KU,om)=>{"use strict";var{tokenChars:fs}=pi();function kt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}a(kt,"push");function cT(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&&fs[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 f=t.slice(l,u);d===44?(kt(e,f,r),r=Object.create(null)):o=f,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(u===-1&&fs[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),kt(r,t.slice(l,u),!0),d===44&&(kt(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(fs[d]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:n||(n=!0),i=!1}else if(s)if(fs[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&&fs[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 f=t.slice(l,u);n&&(f=f.replace(/\\/g,""),n=!1),kt(r,c,f),d===44&&(kt(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 p=t.slice(l,u);return o===void 0?kt(e,p,r):(c===void 0?kt(r,p,!0):n?kt(r,c,p.replace(/\\/g,"")):kt(r,c,p),kt(e,o,r)),e}a(cT,"parse");function lT(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(lT,"format");om.exports={format:lT,parse:cT}});var ra=M((t2,wm)=>{"use strict";var dT=W("events"),uT=W("https"),hT=W("http"),lm=W("net"),pT=W("tls"),{randomBytes:fT,createHash:mT}=W("crypto"),{Duplex:QU,Readable:e2}=W("stream"),{URL:nd}=W("url"),Mr=hi(),_T=Zl(),gT=td(),{isBlob:wT}=pi(),{BINARY_TYPES:am,CLOSE_TIMEOUT:yT,EMPTY_BUFFER:Qo,GUID:bT,kForOnEventAttribute:id,kListener:vT,kStatusCode:ET,kWebSocket:le,NOOP:dm}=ir(),{EventTarget:{addEventListener:ST,removeEventListener:TT}}=sm(),{format:kT,parse:xT}=Zo(),{toBuffer:RT}=ds(),um=Symbol("kAborted"),sd=[8,13],ar=["CONNECTING","OPEN","CLOSING","CLOSED"],OT=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Y=class t extends dT{static{a(this,"WebSocket")}constructor(e,r,n){super(),this._binaryType=am[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qo,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]),hm(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){am.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 _T({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 gT(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[le]=this,s[le]=this,e[le]=this,i.on("conclude",AT),i.on("drain",LT),i.on("error",CT),i.on("message",PT),i.on("ping",DT),i.on("pong",$T),s.onerror=UT,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",mm),e.on("data",ta),e.on("end",_m),e.on("error",gm),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[Mr.extensionName]&&this._extensions[Mr.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){Ue(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())}),fm(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){od(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Qo,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){od(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Qo,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){od(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Mr.extensionName]||(i.compress=!1),this._sender.send(e||Qo,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ue(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Y,"CONNECTING",{enumerable:!0,value:ar.indexOf("CONNECTING")});Object.defineProperty(Y.prototype,"CONNECTING",{enumerable:!0,value:ar.indexOf("CONNECTING")});Object.defineProperty(Y,"OPEN",{enumerable:!0,value:ar.indexOf("OPEN")});Object.defineProperty(Y.prototype,"OPEN",{enumerable:!0,value:ar.indexOf("OPEN")});Object.defineProperty(Y,"CLOSING",{enumerable:!0,value:ar.indexOf("CLOSING")});Object.defineProperty(Y.prototype,"CLOSING",{enumerable:!0,value:ar.indexOf("CLOSING")});Object.defineProperty(Y,"CLOSED",{enumerable:!0,value:ar.indexOf("CLOSED")});Object.defineProperty(Y.prototype,"CLOSED",{enumerable:!0,value:ar.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Y.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Y.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[id])return e[vT];return null},set(e){for(let r of this.listeners(t))if(r[id]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[id]:!0})}})});Y.prototype.addEventListener=ST;Y.prototype.removeEventListener=TT;wm.exports=Y;function hm(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:yT,protocolVersion:sd[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,!sd.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${sd.join(", ")})`);let s;if(e instanceof nd)s=e;else try{s=new nd(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 _;ea(t,_);return}let d=o?443:80,u=fT(16).toString("base64"),h=o?uT.request:hT.request,p=new Set,f;if(i.createConnection=i.createConnection||(o?NT:IT),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&&(f=new Mr({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=kT({[Mr.extensionName]:f.offer()})),r.length){for(let _ of r){if(typeof _!="string"||!OT.test(_)||p.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.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[w,g]of Object.entries(_))n.headers[w.toLowerCase()]=g}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",()=>{Ue(t,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[um]||(m=t._req=null,ea(t,_))}),m.on("response",_=>{let w=_.headers.location,g=_.statusCode;if(w&&i.followRedirects&&g>=300&&g<400){if(++t._redirects>i.maxRedirects){Ue(t,m,"Maximum redirects exceeded");return}m.abort();let y;try{y=new nd(w,e)}catch{let S=new SyntaxError(`Invalid URL: ${w}`);ea(t,S);return}hm(t,y,r,n)}else t.emit("unexpected-response",m,_)||Ue(t,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,w,g)=>{if(t.emit("upgrade",_),t.readyState!==Y.CONNECTING)return;m=t._req=null;let y=_.headers.upgrade;if(y===void 0||y.toLowerCase()!=="websocket"){Ue(t,w,"Invalid Upgrade header");return}let E=mT("sha1").update(u+bT).digest("base64");if(_.headers["sec-websocket-accept"]!==E){Ue(t,w,"Invalid Sec-WebSocket-Accept header");return}let S=_.headers["sec-websocket-protocol"],k;if(S!==void 0?p.size?p.has(S)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":p.size&&(k="Server sent no subprotocol"),k){Ue(t,w,k);return}S&&(t._protocol=S);let $=_.headers["sec-websocket-extensions"];if($!==void 0){if(!f){Ue(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let q;try{q=xT($)}catch{Ue(t,w,"Invalid Sec-WebSocket-Extensions header");return}let V=Object.keys(q);if(V.length!==1||V[0]!==Mr.extensionName){Ue(t,w,"Server indicated an extension that was not requested");return}try{f.accept(q[Mr.extensionName])}catch{Ue(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Mr.extensionName]=f}t.setSocket(w,g,{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(hm,"initAsClient");function ea(t,e){t._readyState=Y.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}a(ea,"emitErrorAndClose");function IT(t){return t.path=t.socketPath,lm.connect(t)}a(IT,"netConnect");function NT(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=lm.isIP(t.host)?"":t.host),pT.connect(t)}a(NT,"tlsConnect");function Ue(t,e,r){t._readyState=Y.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Ue),e.setHeader?(e[um]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ea,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}a(Ue,"abortHandshake");function od(t,e,r){if(e){let n=wT(e)?e.size:RT(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${ar[t.readyState]})`);process.nextTick(r,n)}}a(od,"sendAfterClose");function AT(t,e){let r=this[le];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[le]!==void 0&&(r._socket.removeListener("data",ta),process.nextTick(pm,r._socket),t===1005?r.close():r.close(t,e))}a(AT,"receiverOnConclude");function LT(){let t=this[le];t.isPaused||t._socket.resume()}a(LT,"receiverOnDrain");function CT(t){let e=this[le];e._socket[le]!==void 0&&(e._socket.removeListener("data",ta),process.nextTick(pm,e._socket),e.close(t[ET])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}a(CT,"receiverOnError");function cm(){this[le].emitClose()}a(cm,"receiverOnFinish");function PT(t,e){this[le].emit("message",t,e)}a(PT,"receiverOnMessage");function DT(t){let e=this[le];e._autoPong&&e.pong(t,!this._isServer,dm),e.emit("ping",t)}a(DT,"receiverOnPing");function $T(t){this[le].emit("pong",t)}a($T,"receiverOnPong");function pm(t){t.resume()}a(pm,"resume");function UT(t){let e=this[le];e.readyState!==Y.CLOSED&&(e.readyState===Y.OPEN&&(e._readyState=Y.CLOSING,fm(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}a(UT,"senderOnError");function fm(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}a(fm,"setCloseTimer");function mm(){let t=this[le];if(this.removeListener("close",mm),this.removeListener("data",ta),this.removeListener("end",_m),t._readyState=Y.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[le]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",cm),t._receiver.on("finish",cm))}a(mm,"socketOnClose");function ta(t){this[le]._receiver.write(t)||this.pause()}a(ta,"socketOnData");function _m(){let t=this[le];t._readyState=Y.CLOSING,t._receiver.end(),this.end()}a(_m,"socketOnEnd");function gm(){let t=this[le];this.removeListener("error",gm),this.on("error",dm),t&&(t._readyState=Y.CLOSING,this.destroy())}a(gm,"socketOnError")});var Em=M((i2,vm)=>{"use strict";var n2=ra(),{Duplex:jT}=W("stream");function ym(t){t.emit("close")}a(ym,"emitClose");function MT(){!this.destroyed&&this._writableState.finished&&this.destroy()}a(MT,"duplexOnEnd");function bm(t){this.removeListener("error",bm),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}a(bm,"duplexOnError");function BT(t,e){let r=!0,n=new jT({...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(ym,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(ym,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",MT),n.on("error",bm),n}a(BT,"createWebSocketStream");vm.exports=BT});var ad=M((o2,Sm)=>{"use strict";var{tokenChars:FT}=pi();function qT(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&&FT[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(qT,"parse");Sm.exports={parse:qT}});var Nm=M((l2,Im)=>{"use strict";var zT=W("events"),na=W("http"),{Duplex:c2}=W("stream"),{createHash:WT}=W("crypto"),Tm=Zo(),fn=hi(),HT=ad(),GT=ra(),{CLOSE_TIMEOUT:JT,GUID:VT,kWebSocket:YT}=ir(),XT=/^[+/0-9A-Za-z]{22}==$/,km=0,xm=1,Om=2,cd=class extends zT{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:JT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:GT,...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=na.createServer((n,i)=>{let s=na.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=KT(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=km}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===Om){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ms,this);return}if(e&&this.once("close",e),this._state!==xm)if(this._state=xm,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(ms,this):process.nextTick(ms,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ms(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",Rm);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){mn(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){mn(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!XT.test(s)){mn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){mn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){_s(r,400);return}let l=e.headers["sec-websocket-protocol"],d=new Set;if(l!==void 0)try{d=HT.parse(l)}catch{mn(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 p=new fn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=Tm.parse(u);f[fn.extensionName]&&(p.accept(f[fn.extensionName]),h[fn.extensionName]=p)}catch{mn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={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(p,(f,m,_,w)=>{if(!f)return _s(r,m||401,_,w);this.completeUpgrade(h,s,d,e,r,n,i)});return}if(!this.options.verifyClient(p))return _s(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[YT])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>km)return _s(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${WT("sha1").update(r+VT).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[fn.extensionName]){let h=e[fn.extensionName].params,p=Tm.format({[fn.extensionName]:[h]});d.push(`Sec-WebSocket-Extensions: ${p}`),u._extensions=e}this.emit("headers",d,i),s.write(d.concat(`\r
|
|
4
|
+
`).join(`\r
|
|
5
|
+
`)),s.removeListener("error",Rm),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(ms,this)})),c(u,i)}};Im.exports=cd;function KT(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(KT,"addListeners");function ms(t){t._state=Om,t.emit("close")}a(ms,"emitClose");function Rm(){this.destroy()}a(Rm,"socketOnError");function _s(t,e,r,n){r=r||na.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} ${na.STATUS_CODES[e]}\r
|
|
6
|
+
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
7
|
+
`)+`\r
|
|
8
|
+
\r
|
|
9
|
+
`+r)}a(_s,"abortHandshake");function mn(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,mn),t.emit("wsClientError",o,r,e)}else _s(r,n,i,s)}a(mn,"abortHandshakeOrEmitwsClientError")});var ZT,QT,ek,tk,rk,nk,ut,ik,ia=v(()=>{ZT=nr(Em(),1),QT=nr(Zo(),1),ek=nr(hi(),1),tk=nr(Zl(),1),rk=nr(td(),1),nk=nr(ad(),1),ut=nr(ra(),1),ik=nr(Nm(),1)});import{readFileSync as sk}from"node:fs";var we,wi,Am,Lm,ok,p2,gs,sa,f2,Cm,Pm,m2,ws,Dm,me=v(()=>{we=JSON.parse(sk(new URL("../package.json",import.meta.url),"utf8")).version,wi="interscale/v1",Am="https://interscale.app",Lm=47821,ok=1024*1024,p2=48*1024,gs=32,sa=64*1024*1024,f2=4*1024*1024,Cm="claude",Pm="jobs.env.v1",m2=576*60*60,ws=new Set(["succeeded","failed","cancelled","rejected","expired","needs_review"]),Dm={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 oa(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 G,N,ye=v(()=>{a(oa,"publicErrorDetails");G=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}},N=class extends G{static{a(this,"ApiError")}constructor(e,r,n,i={}){super(r,n,i),this.name="ApiError",this.status=e}}});import{setTimeout as ak}from"node:timers/promises";async function ne(t,e,r={}){let n=new URL(e,uk(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 f=0;;f+=1){let m,_;try{m=await fetch(n,{method:o,headers:i,body:s,signal:h}),_=await dk(m,d)}catch(g){if(g.code==="response_too_large"&&c)throw g;if(f<l&&!h.aborted&&g.code!=="response_too_large"){try{await $m(f,null,h,r)}catch(y){throw p(y)}continue}throw p(g)}let w={};if(_)try{w=JSON.parse(_)}catch{if(m.ok)throw new G("invalid_server_response",`Le serveur a r\xE9pondu avec un contenu invalide (${m.status}).`)}if(!m.ok){if(f<l&&[429,502,503,504].includes(m.status)&&w?.error?.retryable!==!1&&w?.error?.terminal!==!0){try{await $m(f,m,h,r)}catch(y){throw p(y)}continue}let g=new G(w?.error?.code||`http_${m.status}`,w?.error?.message||`HTTP ${m.status}`);throw g.status=m.status,Object.assign(g,oa(w?.error)),g}return w}function p(f){let m=lk(f);return new G(c?"network_error":"outcome_unknown",`R\xE9ponse incompl\xE8te de ${n.origin}: ${f.message}${m?` (${m})`:""}`,{cause:f})}a(p,"requestFailure")}function lk(t){let e=t?.cause?.code||t?.cause?.errors?.find(n=>n?.code)?.code;if(!e)return"";let r=ck.find(([n])=>n.test(e))?.[1];return r?`${e}: ${r}`:e}async function dk(t,e){if(!t.body)return"";let r=a(()=>new G("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")}async function $m(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 ak(Math.min(2**31-1,Math.max(o,Number.isFinite(s)?s:0)),void 0,{signal:r})}function uk(t){return t.endsWith("/")?t:`${t}/`}function Ke(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(/\/$/,"")}var ck,cr=v(()=>{me();ye();a(ne,"apiRequest");ck=[[/^(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"]];a(lk,"networkCause");a(dk,"readControlResponse");a($m,"retryDelay");a(uk,"ensureTrailingSlash");a(Ke,"normalizeServerUrl")});import{homedir as ld,platform as Um}from"node:os";import{join as Pe}from"node:path";function x(t=process.env,e=Um()){return t.INTERSCALE_HOME?t.INTERSCALE_HOME:e==="darwin"?Pe(ld(),"Library","Application Support","Interscale"):e==="win32"?Pe(t.LOCALAPPDATA||Pe(ld(),"AppData","Local"),"Interscale"):Pe(t.XDG_STATE_HOME||Pe(ld(),".local","state"),"interscale")}function ys(t=process.env){return t.INTERSCALE_TRANSFER_DB||Pe(x(t),"controller-transfers.sqlite3")}function jm(t=process.env){return t.INTERSCALE_DOWNLOAD_DB||Pe(x(t),"controller-downloads.sqlite3")}function L(t=process.env){return t.INTERSCALE_AGENT_CONFIG||Pe(x(t),"agent.json")}function Mm(t=process.env){return t.INTERSCALE_AGENT_DB||Pe(x(t),"agent.sqlite3")}function xt(t=process.env){return t.INTERSCALE_AGENT_LOG||Pe(x(t),"logs","agent.log")}function aa(t=process.env){return t.INTERSCALE_AGENT_PID||Pe(x(t),"agent.pid")}function yi(t=process.env){return t.INTERSCALE_TRAY_PID||Pe(x(t),"tray.pid")}function bs(t=process.env){return t.INTERSCALE_SERVER_DATA?t.INTERSCALE_SERVER_DATA:Um()==="linux"&&process.getuid?.()===0?"/var/lib/interscale":Pe(x(t),"server")}function je(t=process.env){return t.INTERSCALE_SERVER_CONFIG||Pe(bs(t),"server.json")}var Z=v(()=>{a(x,"userDataDirectory");a(ys,"controllerTransferDatabasePath");a(jm,"controllerDownloadDatabasePath");a(L,"agentConfigPath");a(Mm,"agentDatabasePath");a(xt,"agentLogPath");a(aa,"agentPidPath");a(yi,"trayPidPath");a(bs,"serverDataDirectory");a(je,"serverConfigPath")});import{chmodSync as zm,mkdirSync as hk,renameSync as Wm,writeFileSync as Hm,openSync as Bm,closeSync as Fm,fsyncSync as qm,rmSync as pk}from"node:fs";import{randomUUID as fk}from"node:crypto";import{dirname as Gm}from"node:path";function xe(t){hk(t,{recursive:!0,mode:448});try{zm(t,448)}catch{}}function Rt(t,e,r=384){xe(Gm(t));let n=`${t}.${process.pid}.tmp`;Hm(n,`${JSON.stringify(e,null,2)}
|
|
10
|
+
`,{mode:r}),Wm(n,t);try{zm(t,r)}catch{}}function se(t,e){let r=Gm(t);xe(r);let n=`${t}.${fk()}.tmp`;try{let i=Bm(n,"wx",384);try{Hm(i,`${JSON.stringify(e,null,2)}
|
|
11
|
+
`),qm(i)}finally{Fm(i)}Wm(n,t);let s;try{s=Bm(r,"r"),qm(s)}catch(o){if(!["EINVAL","ENOTSUP"].includes(o.code)&&process.platform!=="win32")throw o}finally{s!==void 0&&Fm(s)}}finally{pk(n,{force:!0})}}var Re=v(()=>{a(xe,"ensurePrivateDirectory");a(Rt,"writeJsonAtomic");a(se,"writeJsonDurableAtomic")});import{constants as Jm,closeSync as mk,fstatSync as _k,openSync as gk,readFileSync as wk}from"node:fs";import{join as yk}from"node:path";function Me(t=x()){return yk(t,"machine-agent.json")}function ca(t,e,r=x()){if(typeof t!="string"||!t||typeof e!="string"||Buffer.from(e,"base64url").length!==gs)throw new Error("Invalid machine credential");se(Me(r),{schema:"interscale.machine-credential/v1",node_id:t,token:e})}function Ze(t,e){let r=gk(t,Jm.O_RDONLY|(Jm.O_NOFOLLOW||0));try{let n=_k(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(wk(r,"utf8"));if(i.schema!=="interscale.machine-credential/v1"||i.node_id!==e||typeof i.token!="string"||Buffer.from(i.token,"base64url").length!==gs)throw new Error("Machine credential does not match the enrolled node");return i.token}finally{mk(r)}}var bi=v(()=>{me();Z();Re();a(Me,"machineCredentialPath");a(ca,"saveMachineCredential");a(Ze,"readMachineCredential")});import{existsSync as dd,readFileSync as Km,rmSync as bk,writeFileSync as Zm}from"node:fs";import{platform as vi}from"node:os";import{join as _n}from"node:path";import{execFileSync as Qm,spawnSync as ud}from"node:child_process";function la(t,e,r,n=process.env){if(typeof r!="string"||r.length===0)throw new Error("Secret must not be empty");return n.INTERSCALE_TEST_SECRET_DIR?Vm(t,e,r,n.INTERSCALE_TEST_SECRET_DIR):vi()==="darwin"?Sk(t,e,r):vi()==="win32"?kk(t,e,r,n):Vm(t,e,r,_n(x(n),"secrets"))}function vs(t,e,r=process.env){if(t==="agent"&&r.INTERSCALE_MACHINE_CREDENTIAL)return Ze(r.INTERSCALE_MACHINE_CREDENTIAL,e);let n=r[`INTERSCALE_${t.toUpperCase()}_TOKEN`];return n||(r.INTERSCALE_TEST_SECRET_DIR?Ym(t,e,r.INTERSCALE_TEST_SECRET_DIR):vi()==="darwin"?Tk(t,e):vi()==="win32"?xk(t,e,r):Ym(t,e,_n(x(r),"secrets")))}function da(t,e,r=process.env){if(r.INTERSCALE_TEST_SECRET_DIR)return Xm(t,e,r.INTERSCALE_TEST_SECRET_DIR);if(vi()==="darwin")return ud("/usr/bin/security",["delete-generic-password","-a",e,"-s",`${hd}.${t}`],{stdio:"ignore"}).status===0;let n=vi()==="win32"?_n(x(r),"secrets"):_n(x(r),"secrets");return Xm(t,e,n)}function Sk(t,e,r){Qm("/usr/bin/security",["add-generic-password","-U","-a",e,"-s",`${hd}.${t}`,"-w",r],{stdio:["ignore","ignore","pipe"]})}function Tk(t,e){try{return Qm("/usr/bin/security",["find-generic-password","-a",e,"-s",`${hd}.${t}`,"-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Secret ${t}/${e} not found in macOS Keychain`)}}function kk(t,e,r,n){let i=_n(x(n),"secrets");xe(i);let s=ud("powershell.exe",["-NoProfile","-NonInteractive","-Command",vk],{input:r,encoding:"utf8",windowsHide:!0});if(s.status!==0)throw new Error(`Windows DPAPI encryption failed: ${s.stderr}`);Zm(Es(i,t,e),s.stdout.trim(),{mode:384})}function xk(t,e,r){let n=Es(_n(x(r),"secrets"),t,e);if(!dd(n))throw new Error(`Secret ${t}/${e} not found`);let i=ud("powershell.exe",["-NoProfile","-NonInteractive","-Command",Ek],{input:Km(n,"utf8"),encoding:"utf8",windowsHide:!0});if(i.status!==0)throw new Error(`Windows DPAPI decryption failed: ${i.stderr}`);return i.stdout}function Vm(t,e,r,n){xe(n),Zm(Es(n,t,e),r,{mode:384})}function Ym(t,e,r){let n=Es(r,t,e);if(!dd(n))throw new Error(`Secret ${t}/${e} not found at ${n}`);return Km(n,"utf8")}function Xm(t,e,r){let n=Es(r,t,e);return dd(n)?(bk(n),!0):!1}function Es(t,e,r){let n=`${e}-${r}`.replace(/[^a-zA-Z0-9_.-]/g,"_");return _n(t,`${n}.secret`)}var hd,e_,vk,Ek,pd=v(()=>{Re();Z();bi();hd="com.interscale",e_="Add-Type -AssemblyName System.Security",vk=[e_,"$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(";"),Ek=[e_,"$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(";");a(la,"setSecret");a(vs,"getSecret");a(da,"deleteSecret");a(Sk,"setMacSecret");a(Tk,"getMacSecret");a(kk,"setWindowsSecret");a(xk,"getWindowsSecret");a(Vm,"setFileSecret");a(Ym,"getFileSecret");a(Xm,"deleteFileSecret");a(Es,"secretPath")});function ua(t){if(typeof t!="string"||t.length>2048||/[\u0000-\u0020\u007f]/.test(t))throw fd();let e;try{e=new URL(t)}catch{throw fd()}let r=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&r)||e.username||e.password||e.search||e.hash||!["/","/join","/join/"].includes(e.pathname))throw fd();return e.origin}function fd(){return Object.assign(new Error("Use a valid HTTPS InterScale installation link."),{code:"invalid_join_link"})}var md=v(()=>{a(ua,"normalizeJoinServer");a(fd,"invalid")});import{existsSync as Rk,readFileSync as Ok}from"node:fs";import{join as _d}from"node:path";function gn(t=process.env){let e=_d(x(t),"connection.json");if(!Rk(e))return null;let r=JSON.parse(Ok(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:Ke(r.server_url),token:vs("controller",r.token_id,t)}}function ha(t,e=process.env){if(!/^ctok_[A-Za-z0-9-]{1,200}$/.test(t?.token_id)||typeof t.token!="string"||t.token.length<32)throw new Error("Invalid activation response");let r=x(e),n={version:1,server_url:Ke(t.server_url),token_id:t.token_id,release_public_key:t.release_public_key||null,...t.user?{user:t.user}:{}};return xe(r),la("controller",t.token_id,t.token,e),Rt(_d(r,"connection.json"),n),n}function t_(t=process.env){let e;try{e=gn(t)}catch(r){if(r.code!=="signed_out")throw r}e&&da("controller",e.token_id,t),xe(x(t)),Rt(_d(x(t),"connection.json"),{version:1,signed_out:!0})}async function gd({serverUrl:t,email:e,password:r,name:n},i=process.env){let s=ua(t),o=new URL(s);if(o.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("Activation requires HTTPS");let c=await ne(s,"/v1/auth/login",{method:"POST",json:{...e?{email:e}:{},password:r,name:n}}),l=e?c:await ne(s,"/v1/auth/activate",{method:"POST",json:{activation_token:c.activation_token}});return{...ha({...l,server_url:s},i),token:l.token}}var pa=v(()=>{Z();pd();Re();cr();md();a(gn,"loadConnection");a(ha,"saveConnection");a(t_,"clearConnection");a(gd,"activateConnection")});import{existsSync as Ik,readFileSync as Nk}from"node:fs";import{dirname as Ak,join as Lk,resolve as r_}from"node:path";import{fileURLToPath as Ck}from"node:url";function $k(t=process.env){return r_(t.INTERSCALE_FLEET_PROFILE||Lk(Dk,Pk))}function be(t=process.env){let e=gn(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=$k(t);if(!Ik(r))throw new Error("Sign in first: interscale login (or open the Interscale app on this computer)");let n;try{n=JSON.parse(Nk(r,"utf8"))}catch{throw new Error(`Profil priv\xE9 Interscale illisible: ${r}`)}return wd(n)}function wd(t){if(!t||t.version!==1)throw new Error("Version du profil priv\xE9 Interscale invalide");return{version:1,server_url:Ke(t.server_url),fleet_key:Uk(t.fleet_key)}}function Uk(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}var Pk,Dk,fa=v(()=>{cr();pa();Pk="interscale-fleet.private.json",Dk=r_(Ak(Ck(import.meta.url)),"..");a($k,"fleetProfilePath");a(be,"loadFleetProfile");a(wd,"validateFleetProfile");a(Uk,"validateFleetKey")});import{isIP as n_}from"node:net";function Ss(t,{loopback:e=!0,linkLocal:r=!0}={}){let n=String(t||"").toLowerCase().split("%")[0];n.startsWith("::ffff:")&&n_(n.slice(7))===4&&(n=n.slice(7));let i=n_(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 yd=v(()=>{a(Ss,"isPrivateNetworkAddress")});import{networkInterfaces as o_,platform as bd}from"node:os";import{execFileSync as a_}from"node:child_process";import{readlinkSync as jk}from"node:fs";function Bk({refresh:t=!1}={}){if(!t&&vd&&Date.now()-s_<Mk)return vd;let e;try{e=Fk()}catch{e=new Map}return vd=e,s_=Date.now(),e}function Fk(){return bd()==="darwin"?qk():bd()==="linux"?zk():bd()==="win32"?Wk():new Map}function qk(){let t=new Map,e=a_("/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],c_(r)),r=null)}return t}function zk(){let t=new Map;for(let e of Object.keys(o_())){if(/^(thunderbolt|tb)\d*$/i.test(e)){t.set(e,Ts);continue}let r="";try{r=jk(`/sys/class/net/${e}`)}catch{r=""}/thunderbolt/i.test(r)?t.set(e,Ts):/^(wl|wlan|wifi)/i.test(e)?t.set(e,Td):/^(en|eth|br|bond)/i.test(e)&&t.set(e,Sd)}return t}function Wk(){let t=new Map,e=a_("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,c_(`${n.Name} ${n.InterfaceDescription||""}`));return t}function c_(t){return Hk.test(t)?_a:/thunderbolt/i.test(t)?Ts:/wi-?fi|airport|wireless|wlan|802\.11/i.test(t)?Td:/ethernet|\blan\b|gigabit|bridge/i.test(t)?Sd:Ei}function Si({classes:t=Bk()}={}){let e=[];for(let[r,n]of Object.entries(o_()))for(let i of n||[])i.internal||e.push({name:r,kind:t.get(r)||(Gk.test(r)?_a:Ei),family:Kk(i.family),address:i.address,netmask:i.netmask,scopeid:i.scopeid});return e}function ma(t){return i_[t]??i_[Ei]}function Jk(t){return t.startsWith("169.254.")}function Vk(t){return!t.includes(":")&&Ss(t,{loopback:!1,linkLocal:!1})}function Yk(t){return Ss(t,{loopback:!1})}function Xk(t){return t.kind===_a?!1:t.family===4?Vk(t.address)?!0:Jk(t.address)&&t.kind===Ts:Yk(t.address)}function l_(t=Si()){let e=t.filter(Xk);e.sort((n,i)=>ma(n.kind)-ma(i.kind));let r=e.map(n=>n.address);return r.push("127.0.0.1"),[...new Set(r)]}function Kk(t){return t===4||t===6?t:String(t).toLowerCase()==="ipv6"?6:4}function Ed(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 Zk(t,e){let r=Ed(t.address),n=Ed(t.netmask||""),i=Ed(e);return r===null||n===null||i===null?!1:(r&n)>>>0===(i&n)>>>0}function Qk(t,e,r){return r!==t.family?!1:r===4?Zk(t,e):e.toLowerCase().startsWith("fe80:")&&t.address.toLowerCase().startsWith("fe80:")}function ex(t){try{return new URL(t).hostname.replace(/^\[/,"").replace(/\]$/,"")}catch{return null}}function tx(t){return t?/^\d{1,3}(\.\d{1,3}){3}$/.test(t)?4:t.includes(":")?6:null:null}function Ti(t,e=Si()){let r=[],n=new Set;for(let i of t||[]){let s=ex(i);if(!s)continue;let o=tx(s),c=o?e.filter(d=>Qk(d,s,o)):[],l=c.length>0?c.map(d=>({url:i,localAddress:d.address,interface:d.name,kind:d.kind,rank:ma(d.kind)})):[{url:i,localAddress:null,interface:null,kind:Ei,rank:ma(Ei)+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 Ts,Sd,Td,Ei,_a,i_,Mk,vd,s_,Hk,Gk,ks=v(()=>{yd();Ts="thunderbolt",Sd="ethernet",Td="wifi",Ei="other",_a="virtual",i_={[Ts]:0,[Sd]:1,[Td]:2,[Ei]:3,[_a]:4},Mk=60*1e3,vd=null,s_=0;a(Bk,"interfaceClasses");a(Fk,"detectInterfaceClasses");a(qk,"detectDarwin");a(zk,"detectLinux");a(Wk,"detectWindows");Hk=/vEthernet|Hyper-V|\bWSL\b|Docker|VMware|VirtualBox|VBox|TAP-|\bTAP\b|Npcap|Parsec|Bluetooth|Default Switch/i,Gk=/^(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(c_,"kindFromPortName");a(Si,"localLinks");a(ma,"kindRank");a(Jk,"isLinkLocalIpv4");a(Vk,"isPrivateIpv4");a(Yk,"isPrivateIpv6");a(Xk,"isAdvertisable");a(l_,"advertisedAddresses");a(Kk,"normalizeFamily");a(Ed,"ipv4ToInt");a(Zk,"sameIpv4Subnet");a(Qk,"reachesPeer");a(ex,"hostFromUrl");a(tx,"addressFamily");a(Ti,"planDirectCandidates")});var Rd={};K(Rd,{connectDirect:()=>g_,connectPeer:()=>y_,planTunnelCandidates:()=>__,sshProxy:()=>m_,sshProxyCommand:()=>lx,upgrade:()=>b_});import{connect as rx}from"node:net";import{isIP as d_}from"node:net";import{duplexPair as nx}from"node:stream";async function lx(t,e={}){let r=t[1];if(!r)throw new Error("Usage: interscale ssh-proxy <machine> [--debug] (SSH ProxyCommand; see interscale vscode setup)");return m_(r,{debug:e.debug===!0||e.debug==="true"||process.env.INTERSCALE_PROXY_DEBUG==="1"})}async function m_(t,{stdin:e=process.stdin,stdout:r=process.stdout,stderr:n=process.stderr,profile:i,WebSocketImpl:s=ut.default,connectTcp:o=rx,planCandidates:c=__,loadPeerRuntime:l=w_,peerTimeoutMs:d=f_,connectTimeoutMs:u,requestTimeoutMs:h,heartbeatIntervalMs:p,heartbeatTimeoutMs:f,debug:m=process.env.INTERSCALE_PROXY_DEBUG==="1"}={}){let _=a(E=>n.write(`interscale ssh-proxy: ${E}
|
|
12
|
+
`),"say"),w=Date.now(),g=m?E=>_(`+${Date.now()-w}ms ${E}`):()=>{},y=null;try{return g(`connecting to the hub for ${t}`),y=await xd.open(i||be(),s,{connectTimeoutMs:u,requestTimeoutMs:h,heartbeatIntervalMs:p,heartbeatTimeoutMs:f}),g("hub ready"),await dx(t,y,{stdin:e,stdout:r,say:_,debug:g,started:w,connectTcp:o,planCandidates:c,loadPeerRuntime:l,peerTimeoutMs:d})}catch(E){return y?.close(),_(`cannot open a tunnel to ${t}: ${kd(E)}`),1}}async function dx(t,e,{stdin:r,stdout:n,say:i,debug:s,started:o,connectTcp:c,planCandidates:l,loadPeerRuntime:d,peerTimeoutMs:u}){let h=await e.request({type:"tunnel_open",node:t,target:"ssh"},"tunnel_offer"),p=h.node_name||t,f={direct:null,peer:h.peer?null:"not offered"};s(`offer peer=${h.peer===!0} addresses=${(h.addresses||[]).length} port=${h.port??"none"}`);let m=h.peer?y_(e,h,{loadPeerRuntime:d,timeoutMs:u,debug:s}).catch(k=>(f.peer=kd(k),s(`peer failed: ${f.peer}`),null)):Promise.resolve(null),_=g_(h,{connectTcp:c,planCandidates:l,debug:s,report:a(k=>{f.direct=k},"report")}),w=await ux([_.then(k=>k&&{direct:k}),m.then(k=>k&&{peer:k})]),{direct:g,peer:y}=w||{};s(`route ${g?"direct":y?"peer":"relay"}`);let E=a((...k)=>{let $=k.filter(q=>f[q]).map(q=>`${q}: ${f[q]}`);return $.length?` (${$.join("; ")})`:""},"because"),S=a((k,$)=>$?(i(`lost the ${k} to ${p} after ${p_(Date.now()-o)}: ${kd($)}`),1):(s(`session ended normally after ${p_(Date.now()-o)}`),0),"finish");return g?(e.close(),m.then(k=>k?.close()),i(`direct ${g.remoteAddress}:${g.remotePort} to ${p}`),S("direct link",await hx(g.socket,g.leftover,r,n))):y?(_.then(k=>k?.socket.destroy()),e.close(),i(`peer ${y.route} to ${p}${E("direct")}`),S("peer link",await y.bridge(r,n))):(s("relay requested"),await e.request({type:"tunnel_relay_open",tunnel_id:h.tunnel_id},"tunnel_relay_ready"),s("relay ready"),i(`relay through the hub to ${p}${E("direct","peer")}`),S("hub relay",await e.bridge(r,n)))}function __(t){return Ti(t,Si({classes:new Map}))}function Qe(t,e){return Object.assign(new Error(t),{code:e})}function kd(t){let e=t?.message||String(t);return t?.code&&!e.includes(t.code)?`${e} (${t.code})`:e}function p_(t){if(t<1e3)return`${t}ms`;let e=Math.round(t/1e3);return e<60?`${e}s`:`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`}async function g_(t,{connectTcp:e,planCandidates:r,report:n=a(()=>{},"report"),debug:i=a(()=>{},"debug")}){if(!Number.isInteger(t.port))return n("the machine has no LAN data port"),null;let s=(t.addresses||[]).filter(d=>d_(d)&&!/^fe80:/i.test(d)).map(d=>d_(d)===6?`http://[${d}]:${t.port}`:`http://${d}:${t.port}`),o=[...new Set(r(s).map(d=>new URL(d.url).hostname.replace(/^\[|\]$/g,"")))].slice(0,sx);if(!o.length)return n("no LAN address offered"),null;let c=null,l=o.map(d=>b_(e,d,t.port,t.tunnel_id,t.token).then(u=>{if(c)throw u.socket.destroy(),new Error("lost the race");return c={...u,remoteAddress:d,remotePort:t.port},c},u=>{throw i(`direct ${d}: ${u.code||u.message}`),u}));return Promise.any(l).catch(d=>(n(o.map((u,h)=>`${u} ${d.errors[h]?.code||d.errors[h]?.message||"failed"}`).join(", ")),null))}function ux(t){return new Promise(e=>{let r=t.length,n=a(i=>{i?e(i):--r===0&&e(null)},"settle");for(let i of t)i.then(n,()=>n(null))})}async function w_(){let[{createDesktopPeerTransport:t},{bridgeTcp:e,validateOverlaySignal:r}]=await Promise.all([import("../shared/desktop-peer-runtime.mjs"),import("../shared/desktop-overlay.mjs")]);return{createDesktopPeerTransport:t,bridgeTcp:e,validateOverlaySignal:r}}async function y_(t,e,{loadPeerRuntime:r=w_,timeoutMs:n=f_,debug:i=a(()=>{},"debug")}={}){let s=await r(),o=await t.request({type:"tunnel_peer_open",tunnel_id:e.tunnel_id},"tunnel_peer_opened");i("peer opened by the hub");let c=a(u=>u.kind==="candidate"?`candidate ${u.candidate.split(" ")[7]||"?"}`:`description ${u.description_type}`,"kind"),l=await s.createDesktopPeerTransport("interscale-ssh",u=>{i(`local ${c(u)}`),t.send({type:"tunnel_peer_signal",tunnel_id:e.tunnel_id,signal:u})},{iceServers:o.ice_servers||[]}),{peer:d}=l;try{d.onStateChange?.(u=>i(`state ${u}`)),d.onIceStateChange?.(u=>i(`ice ${u}`)),d.onGatheringStateChange?.(u=>i(`gathering ${u}`))}catch{}try{let u=await new Promise((p,f)=>{let m=setTimeout(()=>f(new Error(`no peer link within ${n} ms`)),n),_=a(g=>{clearTimeout(m),f(g)},"fail");t.onPeer={signal:a(g=>{try{let y=s.validateOverlaySignal(g);i(`remote ${c(y)}`),y.kind==="description"?d.setRemoteDescription(y.sdp,y.description_type):d.addRemoteCandidate(y.candidate,y.mid)}catch(y){_(y)}},"signal"),error:a(g=>_(new Error(g||"peer failed")),"error")},t.onClosed=()=>_(t.failure||new Error("hub connection closed"));let w=d.createDataChannel("ssh");w.onOpen(()=>{clearTimeout(m),p(w)}),w.onError(()=>_(new Error("peer channel failed"))),w.onClosed(()=>_(new Error("peer channel closed")))});t.onPeer=null,t.onClosed=null;let h="connected";try{let p=d.getSelectedCandidatePair();p?.local&&p?.remote&&(h=`${p.local.type}/${p.remote.type} ${p.remote.transportType||""}`.trim())}catch{}return{route:h,close:a(()=>l.close(),"close"),bridge:a((p,f)=>new Promise(m=>{let[_,w]=nx(),g=null;s.bridgeTcp(u,_,y=>{g||=y||new Error("peer channel failed"),w.destroy()}),p.readableEnded?w.end():p.pipe(w),w.pipe(f),w.on("end",()=>w.destroy()),w.on("close",()=>{l.close(),m(g)})}),"bridge")}}catch(u){throw t.onPeer=null,t.onClosed=null,l.close(),u}}function b_(t,e,r,n,i){return new Promise((s,o)=>{let c=t({host:e,port:r}),l=setTimeout(()=>{c.destroy(),o(new Error("timeout"))},ix),d=Buffer.alloc(0);c.once("error",h=>{clearTimeout(l),o(h)}),c.once("connect",()=>{c.setNoDelay(!0),c.write(`GET /v1/tunnels/${n} HTTP/1.1\r
|
|
13
|
+
Host: ${e.includes(":")?`[${e}]`:e}:${r}\r
|
|
14
|
+
Connection: Upgrade\r
|
|
15
|
+
Upgrade: interscale-tunnel\r
|
|
16
|
+
X-Interscale-Tunnel-Token: ${i}\r
|
|
17
|
+
\r
|
|
18
|
+
`)});let u=a(h=>{d=Buffer.concat([d,h]);let p=d.indexOf(`\r
|
|
19
|
+
\r
|
|
20
|
+
`);if(p<0){d.length>8192&&(c.destroy(),o(new Error("bad response")));return}if(clearTimeout(l),c.off("data",u),!/^HTTP\/1\.1 101 /.test(d.subarray(0,p).toString("latin1")))return c.destroy(),o(new Error("refused"));s({socket:c,leftover:d.subarray(p+4)})},"onData");c.on("data",u)})}function hx(t,e,r,n){return new Promise(i=>{let s=null;e.length&&n.write(e),r.pipe(t),t.pipe(n),t.on("error",o=>{s||=o}),t.on("close",()=>i(s)),r.on("end",()=>t.end())})}var ix,f_,sx,u_,h_,ox,ax,cx,xd,Od=v(()=>{ia();fa();ks();ix=1e3,f_=6e3,sx=8,u_=128*1024,h_=1e4,ox=15e3,ax=15e3,cx=1e4;a(lx,"sshProxyCommand");a(m_,"sshProxy");a(dx,"openRoute");a(__,"planTunnelCandidates");a(Qe,"coded");a(kd,"describe");a(p_,"elapsed");a(g_,"connectDirect");a(ux,"firstRoute");a(w_,"defaultPeerRuntime");a(y_,"connectPeer");a(b_,"upgrade");a(hx,"bridgeSocket");xd=class t{static{a(this,"HubChannel")}static open(e,r,n={}){let i=new URL("/v1/controller/connect",`${e.server_url.replace(/\/$/,"")}/`);return i.protocol=i.protocol==="https:"?"wss:":"ws:",new t(new r(i,{perMessageDeflate:!1,handshakeTimeout:n.connectTimeoutMs??h_}),n).ready(e.fleet_key)}constructor(e,{connectTimeoutMs:r,requestTimeoutMs:n,heartbeatIntervalMs:i,heartbeatTimeoutMs:s}={}){this.socket=e,this.connectTimeoutMs=r??h_,this.requestTimeoutMs=n??ox,this.heartbeatIntervalMs=i??ax,this.heartbeatTimeoutMs=s??cx,this.waiters=[],this.binary=null,this.early=[],this.failure=null,this.closing=!1,this.lastInbound=Date.now(),this.heartbeatTimer=null,this.pongTimer=null,this.heartbeatId=0,e.on("message",(o,c)=>{if(this.lastInbound=Date.now(),c){this.binary?this.binary(o):this.early.length<64&&this.early.push(o);return}let l;try{l=JSON.parse(o.toString("utf8"))}catch{return}if(l.type==="pong"){this.pongTimer&&l.request_id===`heartbeat-${this.heartbeatId}`&&(clearTimeout(this.pongTimer),this.pongTimer=null,this.scheduleHeartbeat());return}if(l.type==="tunnel_peer_signal"){this.onPeer?.signal(l.signal);return}if(l.type==="tunnel_peer_error"){this.onPeer?.error(l.code);return}let d=this.waiters.find(u=>u.type===l.type||l.type==="error"||l.type==="tunnel_relay_closed"&&u.type==="tunnel_relay_ready");if(l.type==="tunnel_relay_closed"&&l.code&&l.code!=="tunnel_closed"&&(this.failure||=Qe("the hub ended the relay",l.code)),l.type==="tunnel_relay_closed"&&this.closed?.(),!d&&l.type==="error"&&this.closed)return this.fail(Qe(l.message||l.code||"relay failed",l.code));d&&(this.release(d),l.type===d.type?d.resolve(l):d.reject(Qe(l.message||l.code||"tunnel failed",l.code)))}),e.on("close",(o,c)=>{if(this.stopHeartbeat(),!this.closing&&!this.failure){let d=this.lastError?`: ${this.lastError.message}`:o?` with ${o}${c?.length?` ${c}`:""}`:"";this.failure=Qe(`hub connection closed${d}`,"tunnel_hub_closed")}let l=this.failure||Qe("hub connection closed","tunnel_hub_closed");for(let d of this.waiters.splice(0))clearTimeout(d.timer),d.reject(l);this.closed?.(),this.onClosed?.()}),e.on("error",o=>{this.lastError=o})}async ready(e){try{await new Promise((r,n)=>{let i=setTimeout(()=>n(Qe(`the hub did not accept the connection within ${this.connectTimeoutMs} ms`,"tunnel_connect_timeout")),this.connectTimeoutMs),s=a(o=>c=>{clearTimeout(i),o(c)},"settle");this.socket.once("open",s(r)),this.socket.once("error",s(o=>n(Qe(`cannot reach the hub: ${o.message}`,o.code||"tunnel_hub_unreachable")))),this.socket.once("close",s(()=>n(this.failure||Qe("hub connection closed","tunnel_hub_closed"))))}),await this.request({type:"authenticate",token:e},"authenticated")}catch(r){throw this.fail(r),r}return this.scheduleHeartbeat(),this}send(e){this.socket.readyState===1&&this.socket.send(JSON.stringify(e))}request(e,r){return new Promise((n,i)=>{if(this.failure||this.socket.readyState>1)return i(this.failure||Qe("hub connection closed","tunnel_hub_closed"));let s={type:r,resolve:n,reject:i};s.timer=setTimeout(()=>{this.release(s),i(Qe(`the hub did not answer ${e.type} within ${this.requestTimeoutMs} ms`,"tunnel_request_timeout"))},this.requestTimeoutMs),this.waiters.push(s);try{this.socket.send(JSON.stringify(e))}catch(o){this.release(s),i(o)}})}release(e){clearTimeout(e.timer);let r=this.waiters.indexOf(e);r>=0&&this.waiters.splice(r,1)}scheduleHeartbeat(){clearTimeout(this.heartbeatTimer);let e=Math.max(1,this.lastInbound+this.heartbeatIntervalMs-Date.now());this.heartbeatTimer=setTimeout(()=>this.heartbeat(),e),this.heartbeatTimer.unref?.()}heartbeat(){if(this.closing||this.failure||this.socket.readyState!==1)return;if(Date.now()-this.lastInbound<this.heartbeatIntervalMs)return this.scheduleHeartbeat();let e=Date.now();this.pongTimer=setTimeout(()=>{if(this.pongTimer=null,this.lastInbound>=e)return this.scheduleHeartbeat();this.fail(Qe(`no heartbeat reply from the hub for ${this.heartbeatTimeoutMs} ms`,"tunnel_heartbeat_timeout"))},this.heartbeatTimeoutMs);try{this.socket.send(JSON.stringify({type:"ping",request_id:`heartbeat-${++this.heartbeatId}`}))}catch(r){this.fail(r)}}stopHeartbeat(){clearTimeout(this.heartbeatTimer),clearTimeout(this.pongTimer),this.heartbeatTimer=this.pongTimer=null}fail(e){this.failure||=e,this.stopHeartbeat();try{typeof this.socket.terminate=="function"?this.socket.terminate():this.socket.close()}catch{}}bridge(e,r){return new Promise(n=>{for(let i of this.early.splice(0))r.write(i);if(this.failure||this.socket.readyState>1)return n(this.failure||Qe("hub connection closed","tunnel_hub_closed"));this.binary=i=>r.write(i),this.closed=()=>n(this.closing?null:this.failure),e.on("data",i=>{for(let s=0;s<i.length;s+=u_)this.socket.send(i.subarray(s,s+u_),{binary:!0});if(this.socket.bufferedAmount>4*1024*1024){e.pause();let s=setInterval(()=>{this.socket.bufferedAmount<1024*1024&&(clearInterval(s),e.resume())},20)}}),e.on("end",()=>this.close())})}close(){this.closing=!0,this.stopHeartbeat();try{this.socket.close()}catch{}}}});import mx from"events";import De from"fs";import{EventEmitter as Su}from"node:events";import rg from"node:stream";import{StringDecoder as _x}from"node:string_decoder";import sg from"node:path";import Ci from"node:fs";import{dirname as Ix,parse as Nx}from"path";import{EventEmitter as jx}from"events";import iu from"assert";import{Buffer as Rn}from"buffer";import*as k_ from"zlib";import Mx from"zlib";import{posix as xi}from"node:path";import{basename as pR}from"node:path";import Wa from"fs";import Lt from"fs";import C_ from"path";import{win32 as xR}from"node:path";import B_ from"path";import vg from"node:fs";import zR from"node:assert";import{randomBytes as Eg}from"node:crypto";import B from"node:fs";import oe from"node:path";import Sg from"fs";import Qa from"node:fs";import Ws from"node:path";import qe from"node:fs";import XR from"node:fs/promises";import Ja from"node:path";import{join as Pg}from"node:path";import Fe from"node:fs";import Ug from"node:path";function $R(t,e,r){let n=e,i=e?e.next:t.head,s=new Nu(r,n,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function UR(t,e){t.tail=new Nu(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function jR(t,e){t.head=new Nu(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var px,fx,v_,gx,wx,yx,lr,dr,Br,ga,xs,wa,E_,ya,S_,ht,ki,de,Rs,Ni,ue,Oe,he,Id,ba,ve,ie,Nd,Ad,T_,Ld,Ot,Cd,va,Os,wn,Be,Is,bx,vx,Ex,Sx,ng,Tx,kx,xx,Nn,Rx,Yr,_t,Ns,z,Pd,fr,Dd,ru,nu,qs,Ea,Di,$i,$d,Ai,Xr,mt,Wr,It,Li,Ud,pr,As,jd,La,yn,Ca,xn,Tu,Ox,Va,ig,Ax,Lx,Cx,Px,Dx,$x,Ux,ku,Ks,Bx,Pt,Fx,x_,qx,Md,On,Sa,Bd,xu,og,zx,Wx,ag,Hx,Gx,cg,Jx,Vx,Yx,Xx,Kx,Zx,Qx,eR,lg,dg,tR,Pa,rR,ug,Ya,Ru,nR,In,iR,bn,Fd,sR,Hr,oR,aR,cR,Gr,lR,dR,uR,qd,hR,vn,za,fR,mR,_R,gR,P,wR,Xa,yR,su,ou,bR,et,En,ur,zd,R_,Nt,Ls,Fr,O_,J,hr,qr,Wd,Sn,te,Ta,ka,Hd,I_,N_,Cs,Gd,xa,Ri,At,Ra,Tn,Oa,Ia,A_,vR,Ps,Jd,L_,ER,Xs,zs,SR,pg,TR,kR,Ui,fg,RR,P_,Ou,Ka,Iu,OR,IR,D_,NR,mg,AR,$_,U_,j_,au,M_,Ds,Da,cu,$a,lu,du,uu,hu,Jr,Ha,pu,Vd,Ct,_g,LR,CR,PR,DR,Nu,F_,q_,Ua,$s,pt,Us,zr,kn,js,Na,ft,Yd,ja,z_,fu,mu,Ma,Ba,W_,Xd,Fa,gg,Kd,Za,Au,MR,BR,wg,yg,FR,qR,bg,WR,Tg,kg,H_,xg,Rg,Og,HR,GR,JR,G_,Ig,_u,Ga,VR,Ng,YR,Ag,Lg,ec,KR,ZR,gu,Cg,QR,e1,Zd,J_,Oi,t1,r1,n1,i1,s1,o1,V_,wu,Y_,yu,tt,bu,vu,qa,X_,K_,Fs,Z_,Q_,Qd,Vr,pe,Aa,eg,Ii,eu,tu,Eu,Hs,Gs,Js,Vs,a1,Ys,c1,l1,d1,tg,Lu,Ms,Dg,u1,h1,$g,p1,f1,m1,_1,g1,Bs,cM,w1,jg=v(()=>{px=Object.defineProperty,fx=a((t,e)=>{for(var r in e)px(t,r,{get:e[r],enumerable:!0})},"Ur"),v_=typeof process=="object"&&process?process:{stdout:null,stderr:null},gx=a(t=>!!t&&typeof t=="object"&&(t instanceof Nn||t instanceof rg||wx(t)||yx(t)),"Wr"),wx=a(t=>!!t&&typeof t=="object"&&t instanceof Su&&typeof t.pipe=="function"&&t.pipe!==rg.Writable.prototype.pipe,"Gr"),yx=a(t=>!!t&&typeof t=="object"&&t instanceof Su&&typeof t.write=="function"&&typeof t.end=="function","Zr"),lr=Symbol("EOF"),dr=Symbol("maybeEmitEnd"),Br=Symbol("emittedEnd"),ga=Symbol("emittingEnd"),xs=Symbol("emittedError"),wa=Symbol("closed"),E_=Symbol("read"),ya=Symbol("flush"),S_=Symbol("flushChunk"),ht=Symbol("encoding"),ki=Symbol("decoder"),de=Symbol("flowing"),Rs=Symbol("paused"),Ni=Symbol("resume"),ue=Symbol("buffer"),Oe=Symbol("pipes"),he=Symbol("bufferLength"),Id=Symbol("bufferPush"),ba=Symbol("bufferShift"),ve=Symbol("objectMode"),ie=Symbol("destroyed"),Nd=Symbol("error"),Ad=Symbol("emitData"),T_=Symbol("emitEnd"),Ld=Symbol("emitEnd2"),Ot=Symbol("async"),Cd=Symbol("abort"),va=Symbol("aborted"),Os=Symbol("signal"),wn=Symbol("dataListeners"),Be=Symbol("discarded"),Is=a(t=>Promise.resolve().then(t),"jt"),bx=a(t=>t(),"Yr"),vx=a(t=>t==="end"||t==="finish"||t==="prefinish","Kr"),Ex=a(t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,"Vr"),Sx=a(t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),"$r"),ng=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[Ni](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Tx=class extends ng{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)}},kx=a(t=>!!t.objectMode,"Xr"),xx=a(t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer","qr"),Nn=class extends Su{static{a(this,"A")}[de]=!1;[Rs]=!1;[Oe]=[];[ue]=[];[ve];[ht];[Ot];[ki];[lr]=!1;[Br]=!1;[ga]=!1;[wa]=!1;[xs]=null;[he]=0;[ie]=!1;[Os];[va]=!1;[wn]=0;[Be]=!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");kx(e)?(this[ve]=!0,this[ht]=null):xx(e)?(this[ht]=e.encoding,this[ve]=!1):(this[ve]=!1,this[ht]=null),this[Ot]=!!e.async,this[ki]=this[ht]?new _x(this[ht]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:a(()=>this[ue],"get")}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:a(()=>this[Oe],"get")});let{signal:r}=e;r&&(this[Os]=r,r.aborted?this[Cd]():r.addEventListener("abort",()=>this[Cd]()))}get bufferLength(){return this[he]}get encoding(){return this[ht]}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[ve]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ot]}set async(t){this[Ot]=this[Ot]||!!t}[Cd](){this[va]=!0,this.emit("abort",this[Os]?.reason),this.destroy(this[Os]?.reason)}get aborted(){return this[va]}set aborted(t){}write(t,e,r){if(this[va])return!1;if(this[lr])throw new Error("write after end");if(this[ie])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[Ot]?Is:bx;if(!this[ve]&&!Buffer.isBuffer(t)){if(Sx(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Ex(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ve]?(this[de]&&this[he]!==0&&this[ya](!0),this[de]?this.emit("data",t):this[Id](t),this[he]!==0&&this.emit("readable"),r&&n(r),this[de]):t.length?(typeof t=="string"&&!(e===this[ht]&&!this[ki]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[ht]&&(t=this[ki].write(t)),this[de]&&this[he]!==0&&this[ya](!0),this[de]?this.emit("data",t):this[Id](t),this[he]!==0&&this.emit("readable"),r&&n(r),this[de]):(this[he]!==0&&this.emit("readable"),r&&n(r),this[de])}read(t){if(this[ie])return null;if(this[Be]=!1,this[he]===0||t===0||t&&t>this[he])return this[dr](),null;this[ve]&&(t=null),this[ue].length>1&&!this[ve]&&(this[ue]=[this[ht]?this[ue].join(""):Buffer.concat(this[ue],this[he])]);let e=this[E_](t||null,this[ue][0]);return this[dr](),e}[E_](t,e){if(this[ve])this[ba]();else{let r=e;t===r.length||t===null?this[ba]():typeof r=="string"?(this[ue][0]=r.slice(t),e=r.slice(0,t),this[he]-=t):(this[ue][0]=r.subarray(t),e=r.subarray(0,t),this[he]-=t)}return this.emit("data",e),!this[ue].length&&!this[lr]&&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[lr]=!0,this.writable=!1,(this[de]||!this[Rs])&&this[dr](),this}[Ni](){this[ie]||(!this[wn]&&!this[Oe].length&&(this[Be]=!0),this[Rs]=!1,this[de]=!0,this.emit("resume"),this[ue].length?this[ya]():this[lr]?this[dr]():this.emit("drain"))}resume(){return this[Ni]()}pause(){this[de]=!1,this[Rs]=!0,this[Be]=!1}get destroyed(){return this[ie]}get flowing(){return this[de]}get paused(){return this[Rs]}[Id](t){this[ve]?this[he]+=1:this[he]+=t.length,this[ue].push(t)}[ba](){return this[ve]?this[he]-=1:this[he]-=this[ue][0].length,this[ue].shift()}[ya](t=!1){do;while(this[S_](this[ba]())&&this[ue].length);!t&&!this[ue].length&&!this[lr]&&this.emit("drain")}[S_](t){return this.emit("data",t),this[de]}pipe(t,e){if(this[ie])return t;this[Be]=!1;let r=this[Br];return e=e||{},t===v_.stdout||t===v_.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Oe].push(e.proxyErrors?new Tx(this,t,e):new ng(this,t,e)),this[Ot]?Is(()=>this[Ni]()):this[Ni]()),t}unpipe(t){let e=this[Oe].find(r=>r.dest===t);e&&(this[Oe].length===1?(this[de]&&this[wn]===0&&(this[de]=!1),this[Oe]=[]):this[Oe].splice(this[Oe].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[Be]=!1,this[wn]++,!this[Oe].length&&!this[de]&&this[Ni]();else if(t==="readable"&&this[he]!==0)super.emit("readable");else if(vx(t)&&this[Br])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[xs]){let n=e;this[Ot]?Is(()=>n.call(this,this[xs])):n.call(this,this[xs])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[wn]=this.listeners("data").length,this[wn]===0&&!this[Be]&&!this[Oe].length&&(this[de]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[wn]=0,!this[Be]&&!this[Oe].length&&(this[de]=!1)),e}get emittedEnd(){return this[Br]}[dr](){!this[ga]&&!this[Br]&&!this[ie]&&this[ue].length===0&&this[lr]&&(this[ga]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[wa]&&this.emit("close"),this[ga]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==ie&&this[ie])return!1;if(t==="data")return!this[ve]&&!r?!1:this[Ot]?(Is(()=>this[Ad](r)),!0):this[Ad](r);if(t==="end")return this[T_]();if(t==="close"){if(this[wa]=!0,!this[Br]&&!this[ie])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[xs]=r,super.emit(Nd,r);let i=!this[Os]||this.listeners("error").length?super.emit("error",r):!1;return this[dr](),i}else if(t==="resume"){let i=super.emit("resume");return this[dr](),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[dr](),n}[Ad](t){for(let r of this[Oe])r.dest.write(t)===!1&&this.pause();let e=this[Be]?!1:super.emit("data",t);return this[dr](),e}[T_](){return this[Br]?!1:(this[Br]=!0,this.readable=!1,this[Ot]?(Is(()=>this[Ld]()),!0):this[Ld]())}[Ld](){if(this[ki]){let e=this[ki].end();if(e){for(let r of this[Oe])r.dest.write(e);this[Be]||super.emit("data",e)}}for(let e of this[Oe])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[ve]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[ve]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[ve])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[ht]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ie,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[Be]=!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[lr])return e();let n,i,s=a(d=>{this.off("data",o),this.off("end",c),this.off(ie,l),e(),i(d)},"h"),o=a(d=>{this.off("error",s),this.off("end",c),this.off(ie,l),this.pause(),n({value:d,done:!!this[lr]})},"a"),c=a(()=>{this.off("error",s),this.off("data",o),this.off(ie,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(ie,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[Be]=!1;let t=!1,e=a(()=>(this.pause(),this.off(Nd,e),this.off(ie,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(Nd,e),this.once(ie,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ie])return t?this.emit("error",t):this.emit(ie),this;this[ie]=!0,this[Be]=!0,this[ue].length=0,this[he]=0;let e=this;return typeof e.close=="function"&&!this[wa]&&e.close(),t?this.emit("error",t):this.emit(ie),this}static get isStream(){return gx}},Rx=De.writev,Yr=Symbol("_autoClose"),_t=Symbol("_close"),Ns=Symbol("_ended"),z=Symbol("_fd"),Pd=Symbol("_finished"),fr=Symbol("_flags"),Dd=Symbol("_flush"),ru=Symbol("_handleChunk"),nu=Symbol("_makeBuf"),qs=Symbol("_mode"),Ea=Symbol("_needDrain"),Di=Symbol("_onerror"),$i=Symbol("_onopen"),$d=Symbol("_onread"),Ai=Symbol("_onwrite"),Xr=Symbol("_open"),mt=Symbol("_path"),Wr=Symbol("_pos"),It=Symbol("_queue"),Li=Symbol("_read"),Ud=Symbol("_readSize"),pr=Symbol("_reading"),As=Symbol("_remain"),jd=Symbol("_size"),La=Symbol("_write"),yn=Symbol("_writing"),Ca=Symbol("_defaultFlag"),xn=Symbol("_errored"),Tu=class extends Nn{static{a(this,"_t")}[xn]=!1;[z];[mt];[Ud];[pr]=!1;[jd];[As];[Yr];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[xn]=!1,this[z]=typeof e.fd=="number"?e.fd:void 0,this[mt]=t,this[Ud]=e.readSize||16*1024*1024,this[pr]=!1,this[jd]=typeof e.size=="number"?e.size:1/0,this[As]=this[jd],this[Yr]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[z]=="number"?this[Li]():this[Xr]()}get fd(){return this[z]}get path(){return this[mt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Xr](){De.open(this[mt],"r",(t,e)=>this[$i](t,e))}[$i](t,e){t?this[Di](t):(this[z]=e,this.emit("open",e),this[Li]())}[nu](){return Buffer.allocUnsafe(Math.min(this[Ud],this[As]))}[Li](){if(!this[pr]){this[pr]=!0;let t=this[nu]();if(t.length===0)return process.nextTick(()=>this[$d](null,0,t));De.read(this[z],t,0,t.length,null,(e,r,n)=>this[$d](e,r,n))}}[$d](t,e,r){this[pr]=!1,t?this[Di](t):this[ru](e,r)&&this[Li]()}[_t](){if(this[Yr]&&typeof this[z]=="number"){let t=this[z];this[z]=void 0,De.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Di](t){this[pr]=!0,this[_t](),this.emit("error",t)}[ru](t,e){let r=!1;return this[As]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[As]<=0)&&(r=!1,this[_t](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[z]=="number"&&this[Li](),!1;case"error":return this[xn]?!1:(this[xn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Ox=class extends Tu{static{a(this,"Be")}[Xr](){let t=!0;try{this[$i](null,De.openSync(this[mt],"r")),t=!1}finally{t&&this[_t]()}}[Li](){let t=!0;try{if(!this[pr]){this[pr]=!0;do{let e=this[nu](),r=e.length===0?0:De.readSync(this[z],e,0,e.length,null);if(!this[ru](r,e))break}while(!0);this[pr]=!1}t=!1}finally{t&&this[_t]()}}[_t](){if(this[Yr]&&typeof this[z]=="number"){let t=this[z];this[z]=void 0,De.closeSync(t),this.emit("close")}}},Va=class extends mx{static{a(this,"et")}readable=!1;writable=!0;[xn]=!1;[yn]=!1;[Ns]=!1;[It]=[];[Ea]=!1;[mt];[qs];[Yr];[z];[Ca];[fr];[Pd]=!1;[Wr];constructor(t,e){e=e||{},super(e),this[mt]=t,this[z]=typeof e.fd=="number"?e.fd:void 0,this[qs]=e.mode===void 0?438:e.mode,this[Wr]=typeof e.start=="number"?e.start:void 0,this[Yr]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[Wr]!==void 0?"r+":"w";this[Ca]=e.flags===void 0,this[fr]=e.flags===void 0?r:e.flags,this[z]===void 0&&this[Xr]()}emit(t,...e){if(t==="error"){if(this[xn])return!1;this[xn]=!0}return super.emit(t,...e)}get fd(){return this[z]}get path(){return this[mt]}[Di](t){this[_t](),this[yn]=!0,this.emit("error",t)}[Xr](){De.open(this[mt],this[fr],this[qs],(t,e)=>this[$i](t,e))}[$i](t,e){this[Ca]&&this[fr]==="r+"&&t&&t.code==="ENOENT"?(this[fr]="w",this[Xr]()):t?this[Di](t):(this[z]=e,this.emit("open",e),this[yn]||this[Dd]())}end(t,e){return t&&this.write(t,e),this[Ns]=!0,!this[yn]&&!this[It].length&&typeof this[z]=="number"&&this[Ai](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ns]?(this.emit("error",new Error("write() after end()")),!1):this[z]===void 0||this[yn]||this[It].length?(this[It].push(t),this[Ea]=!0,!1):(this[yn]=!0,this[La](t),!0)}[La](t){De.write(this[z],t,0,t.length,this[Wr],(e,r)=>this[Ai](e,r))}[Ai](t,e){t?this[Di](t):(this[Wr]!==void 0&&typeof e=="number"&&(this[Wr]+=e),this[It].length?this[Dd]():(this[yn]=!1,this[Ns]&&!this[Pd]?(this[Pd]=!0,this[_t](),this.emit("finish")):this[Ea]&&(this[Ea]=!1,this.emit("drain"))))}[Dd](){if(this[It].length===0)this[Ns]&&this[Ai](null,0);else if(this[It].length===1)this[La](this[It].pop());else{let t=this[It];this[It]=[],Rx(this[z],t,this[Wr],(e,r)=>this[Ai](e,r))}}[_t](){if(this[Yr]&&typeof this[z]=="number"){let t=this[z];this[z]=void 0,De.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},ig=class extends Va{static{a(this,"Wt")}[Xr](){let t;if(this[Ca]&&this[fr]==="r+")try{t=De.openSync(this[mt],this[fr],this[qs])}catch(e){if(e?.code==="ENOENT")return this[fr]="w",this[Xr]();throw e}else t=De.openSync(this[mt],this[fr],this[qs]);this[$i](null,t)}[_t](){if(this[Yr]&&typeof this[z]=="number"){let t=this[z];this[z]=void 0,De.closeSync(t),this.emit("close")}}[La](t){let e=!0;try{this[Ai](null,De.writeSync(this[z],t,0,t.length,this[Wr])),e=!1}finally{if(e)try{this[_t]()}catch{}}}},Ax=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"]]),Lx=a(t=>!!t.sync&&!!t.file,"Fs"),Cx=a(t=>!t.sync&&!!t.file,"ks"),Px=a(t=>!!t.sync&&!t.file,"vs"),Dx=a(t=>!t.sync&&!t.file,"Ms"),$x=a(t=>!!t.file,"Bs"),Ux=a(t=>Ax.get(t)||t,"tn"),ku=a((t={})=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){let i=Ux(r);e[i]=n}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},"se"),Ks=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=ku(s);if(i?.(l,o),Lx(l)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return t(l,o)}else if(Cx(l)){let d=e(l,o);return c?d.then(()=>c(),c):d}else if(Px(l)){if(typeof c=="function")throw new TypeError("callback not supported for sync tar functions");return r(l,o)}else if(Dx(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"),Bx=Mx.constants||{ZLIB_VERNUM:4736},Pt=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},Bx)),Fx=Rn.concat,x_=Object.getOwnPropertyDescriptor(Rn,"concat"),qx=a(t=>t,"nn"),Md=x_?.writable===!0||x_?.set!==void 0?t=>{Rn.concat=t?qx:Fx}:t=>{},On=Symbol("_superWrite"),Sa=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"}},Bd=Symbol("flushFlag"),xu=class extends Nn{static{a(this,"re")}#e=!1;#r=!1;#n;#c;#s;#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.#c=t.finishFlush??0,this.#s=t.fullFlushFlag??0,typeof k_[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new k_[e](t)}catch(r){throw new Sa(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 Sa(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return iu(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#s),this.write(Object.assign(Rn.alloc(0),{[Bd]: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.#c),this.#r=!0,super.end(r)}get ended(){return this.#r}[On](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Rn.from(t,e)),this.#e)return;iu(this.#t,"zlib binding closed");let n=this.#t._handle,i=n.close;n.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},Md(!0);let o;try{let l=typeof t[Bd]=="number"?t[Bd]:this.#n;o=this.#t._processChunk(t,l),Md(!1)}catch(l){Md(!1),this.#o(new Sa(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 Sa(l,this.write)));let c;if(o)if(Array.isArray(o)&&o.length>0){let l=o[0];c=this[On](Rn.from(l));for(let d=1;d<o.length;d++)c=this[On](o[d])}else c=this[On](Rn.from(o));return r&&r(),c}},og=class extends xu{static{a(this,"Pe")}#e;#r;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.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(Pt.Z_SYNC_FLUSH),iu(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)}}}},zx=class extends og{static{a(this,"ze")}#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[On](t){return this.#e?(this.#e=!1,t[9]=255,super[On](t)):super[On](t)}},Wx=class extends og{static{a(this,"Ue")}constructor(t){super(t,"Unzip")}},ag=class extends xu{static{a(this,"He")}constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},Hx=class extends ag{static{a(this,"We")}constructor(t){super(t,"BrotliCompress")}},Gx=class extends ag{static{a(this,"Ge")}constructor(t){super(t,"BrotliDecompress")}},cg=class extends xu{static{a(this,"Ze")}constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},Jx=class extends cg{static{a(this,"Ye")}constructor(t){super(t,"ZstdCompress")}},Vx=class extends cg{static{a(this,"Ke")}constructor(t){super(t,"ZstdDecompress")}},Yx=a((t,e)=>{if(Number.isSafeInteger(t))t<0?Kx(t,e):Xx(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},"Us"),Xx=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"),Kx=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]=lg(i):i===0?e[n-1]=0:(r=!0,e[n-1]=dg(i))}},"an"),Zx=a(t=>{let e=t[0],r=e===128?eR(t.subarray(1,t.length)):e===255?Qx(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"),Qx=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=lg(s):s===0?o=s:(n=!0,o=dg(s)),o!==0&&(r-=o*Math.pow(256,e-i-1))}return r},"ln"),eR=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"),lg=a(t=>(255^t)&255,"Ws"),dg=a(t=>(255^t)+1&255,"Gs"),tR={};fx(tR,{code:a(()=>Ru,"code"),isCode:a(()=>Pa,"isCode"),isName:a(()=>rR,"isName"),name:a(()=>Ya,"name"),normalFsTypes:a(()=>ug,"normalFsTypes")});Pa=a(t=>Ya.has(t),"ne"),rR=a(t=>Ru.has(t),"dn"),ug=new Set(["0","","1","2","3","4","5","6","7","D"]),Ya=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"]]),Ru=new Map(Array.from(Ya).map(t=>[t[1],t[0]])),nR=a(t=>t===void 0||t<0?void 0:t,"un"),In=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=bn(t,e+156,1),s=ug.has(i),o=s?r:void 0,c=s?n:void 0;if(this.path=o?.path??bn(t,e,100),this.mode=o?.mode??c?.mode??Hr(t,e+100,8),this.uid=o?.uid??c?.uid??Hr(t,e+108,8),this.gid=o?.gid??c?.gid??Hr(t,e+116,8),this.size=nR(o?.size??c?.size??Hr(t,e+124,12)),this.mtime=o?.mtime??c?.mtime??Fd(t,e+136,12),this.cksum=Hr(t,e+148,12),c&&this.#r(c,!0),o&&this.#r(o),Pa(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=bn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=o?.uname??c?.uname??bn(t,e+265,32),this.gname=o?.gname??c?.gname??bn(t,e+297,32),this.devmaj=o?.devmaj??c?.devmaj??Hr(t,e+329,8)??0,this.devmin=o?.devmin??c?.devmin??Hr(t,e+337,8)??0,t[e+475]!==0){let d=bn(t,e+345,155);this.path=d+"/"+this.path}else{let d=bn(t,e+345,130);d&&(this.path=d+"/"+this.path),this.atime=r?.atime??n?.atime??Fd(t,e+476,12),this.ctime=r?.ctime??n?.ctime??Fd(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=iR(this.path||"",r),i=n[0],s=n[1];this.needPax=!!n[2],this.needPax=vn(t,e,100,i)||this.needPax,this.needPax=Gr(t,e+100,8,this.mode)||this.needPax,this.needPax=Gr(t,e+108,8,this.uid)||this.needPax,this.needPax=Gr(t,e+116,8,this.gid)||this.needPax,this.needPax=Gr(t,e+124,12,this.size)||this.needPax,this.needPax=qd(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=vn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=vn(t,e+265,32,this.uname)||this.needPax,this.needPax=vn(t,e+297,32,this.gname)||this.needPax,this.needPax=Gr(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Gr(t,e+337,8,this.devmin)||this.needPax,this.needPax=vn(t,e+345,r,s)||this.needPax,t[e+475]!==0?this.needPax=vn(t,e+345,155,s)||this.needPax:(this.needPax=vn(t,e+345,130,s)||this.needPax,this.needPax=qd(t,e+476,12,this.atime)||this.needPax,this.needPax=qd(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,Gr(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Ya.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Ru.get(t));if(Pa(e)||e==="Unsupported")this.#e=e;else if(Pa(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},iR=a((t,e)=>{let r=t,n="",i,s=xi.parse(t).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=xi.dirname(r),r=xi.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=xi.join(xi.basename(n),r),n=xi.dirname(n));while(n!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},"mn"),bn=a((t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),"xt"),Fd=a((t,e,r)=>sR(Hr(t,e,r)),"Wi"),sR=a(t=>t===void 0?void 0:new Date(t*1e3),"pn"),Hr=a((t,e,r)=>Number(t[e])&128?Zx(t.subarray(e,e+r)):aR(t,e,r),"lt"),oR=a(t=>isNaN(t)?void 0:t,"En"),aR=a((t,e,r)=>oR(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),"wn"),cR={12:8589934591,8:2097151},Gr=a((t,e,r,n)=>n===void 0?!1:n>cR[r]||n<0?(Yx(n,t.subarray(e,e+r)),!0):(lR(t,e,r,n),!1),"ct"),lR=a((t,e,r,n)=>t.write(dR(n,r),e,r,"ascii"),"yn"),dR=a((t,e)=>uR(Math.floor(t).toString(8),e),"Rn"),uR=a((t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0","gn"),qd=a((t,e,r,n)=>n===void 0?!1:Gr(t,e,r,n.getTime()/1e3),"Gi"),hR=new Array(156).join("\0"),vn=a((t,e,r,n)=>n===void 0?!1:(t.write(n+hR,e,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),"Lt"),za=class hg{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 In({path:("PaxHeader/"+pR(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+`
|
|
21
|
+
`,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 hg(fR(mR(e),r),n)}},fR=a((t,e)=>e?Object.assign({},e,t):t,"On"),mR=a(t=>t.replace(/\n$/,"").split(`
|
|
22
|
+
`).reduce(_R,Object.create(null)),"Tn"),_R=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"),gR=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,P=gR!=="win32"?t=>String(t):t=>String(t).replaceAll(/\\/g,"/"),wR=class extends Nn{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=P(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?P(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=P(t.path)),t.linkpath&&(t.linkpath=P(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e))))}},Xa=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"),yR=1024*1024,su=Buffer.from([31,139]),ou=Buffer.from([40,181,47,253]),bR=Math.max(su.length,ou.length),et=Symbol("state"),En=Symbol("writeEntry"),ur=Symbol("readEntry"),zd=Symbol("nextEntry"),R_=Symbol("processEntry"),Nt=Symbol("extendedHeader"),Ls=Symbol("globalExtendedHeader"),Fr=Symbol("meta"),O_=Symbol("emitMeta"),J=Symbol("buffer"),hr=Symbol("queue"),qr=Symbol("ended"),Wd=Symbol("emittedEnd"),Sn=Symbol("emit"),te=Symbol("unzip"),Ta=Symbol("consumeChunk"),ka=Symbol("consumeChunkSub"),Hd=Symbol("consumeBody"),I_=Symbol("consumeMeta"),N_=Symbol("consumeHeader"),Cs=Symbol("consuming"),Gd=Symbol("bufferConcat"),xa=Symbol("maybeEnd"),Ri=Symbol("writing"),At=Symbol("aborted"),Ra=Symbol("onDone"),Tn=Symbol("sawValidEntry"),Oa=Symbol("sawNullBlock"),Ia=Symbol("sawEOF"),A_=Symbol("closeStream"),vR=1e3,Ps=Symbol("compressedBytesRead"),Jd=Symbol("decompressedBytesRead"),L_=Symbol("checkDecompressionRatio"),ER=a(()=>!0,"Cn"),Xs=class extends jx{static{a(this,"rt")}file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[hr]=[];[J];[ur];[En];[et]="begin";[Fr]="";[Nt];[Ls];[qr]=!1;[te];[At]=!1;[Tn];[Oa]=!1;[Ia]=!1;[Ri]=!1;[Cs]=!1;[Wd]=!1;[Ps]=0;[Jd]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Ra,()=>{(this[et]==="begin"||this[Tn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ra,t.ondone):this.on(Ra,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:vR,this.maxMetaEntrySize=t.maxMetaEntrySize||yR,this.filter=typeof t.filter=="function"?t.filter:ER;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[A_]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){Xa(this,t,e,r)}[N_](t,e){this[Tn]===void 0&&(this[Tn]=!1);let r;try{r=new In(t,e,this[Nt],this[Ls])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[Oa]?(this[Ia]=!0,this[et]==="begin"&&(this[et]="header"),this[Sn]("eof")):(this[Oa]=!0,this[Sn]("nullBlock"));else if(this[Oa]=!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[En]=new wR(r,this[Nt],this[Ls]);if(!this[Tn])if(i.remain){let s=a(()=>{i.invalid||(this[Tn]=!0)},"o");i.on("end",s)}else this[Tn]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[Sn]("ignoredEntry",i),this[et]="ignore",i.resume()):i.size>0&&(this[Fr]="",i.on("data",s=>this[Fr]+=s),this[et]="meta"):(this[Nt]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[Sn]("ignoredEntry",i),this[et]=i.remain?"ignore":"header",i.resume()):(i.remain?this[et]="body":(this[et]="header",i.end()),this[ur]?this[hr].push(i):(this[hr].push(i),this[zd]())))}}}[A_](){queueMicrotask(()=>this.emit("close"))}[R_](t){let e=!0;if(!t)this[ur]=void 0,e=!1;else if(Array.isArray(t)){let[r,...n]=t;this.emit(r,...n)}else this[ur]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[zd]()),e=!1);return e}[zd](){do;while(this[R_](this[hr].shift()));if(this[hr].length===0){let t=this[ur];!t||t.flowing||t.size===t.remain?this[Ri]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Hd](t,e){let r=this[En];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[et]="header",this[En]=void 0,r.end()),i.length}[I_](t,e){let r=this[En],n=this[Hd](t,e);return!this[En]&&r&&this[O_](r),n}[Sn](t,e,r){this[hr].length===0&&!this[ur]?this.emit(t,e,r):this[hr].push([t,e,r])}[O_](t){switch(this[Sn]("meta",this[Fr]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Nt]=za.parse(this[Fr],this[Nt],!1);break;case"GlobalExtendedHeader":this[Ls]=za.parse(this[Fr],this[Ls],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Nt]??Object.create(null);this[Nt]=e,e.path=this[Fr].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Nt]||Object.create(null);this[Nt]=e,e.linkpath=this[Fr].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[At]){if(this[te]){let e=this[te];e.write=()=>!0,e.end=()=>e,e.emit=()=>!1,e.destroy?.()}this[At]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}}[L_](t){this[Jd]+=t.length;let e=this[Jd]/this[Ps];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[At])return r?.(),!1;if((this[te]===void 0||this.brotli===void 0&&this[te]===!1)&&t){if(this[J]&&(t=Buffer.concat([this[J],t]),this[J]=void 0),t.length<bR)return this[J]=t,r?.(),!0;for(let o=0;this[te]===void 0&&o<su.length;o++)t[o]!==su[o]&&(this[te]=!1);let i=!1;if(this[te]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<ou.length;o++)if(t[o]!==ou[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[te]===!1&&s)if(t.length<512)if(this[qr])this.brotli=!0;else return this[J]=t,r?.(),!0;else try{new In(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[te]===void 0||this[te]===!1&&(this.brotli||i)){let o=this[qr];this[qr]=!1,this[te]=this[te]===void 0?new Wx({}):i?new Vx({}):new Gx({}),this[te].on("data",l=>{this[L_](l)&&this[Ta](l)}),this[te].on("error",l=>{this[At]||this.abort(l)}),this[te].on("end",()=>{this[qr]=!0,this[Ta]()}),this[Ri]=!0,this[Ps]+=t.length;let c=!!this[te][o?"end":"write"](t);return this[Ri]=!1,r?.(),c}}this[Ri]=!0,this[te]?(this[Ps]+=t.length,this[te].write(t)):this[Ta](t),this[Ri]=!1;let n=this[hr].length>0?!1:this[ur]?this[ur].flowing:!0;return!n&&this[hr].length===0&&this[ur]?.once("drain",()=>this.emit("drain")),r?.(),n}[Gd](t){t&&!this[At]&&(this[J]=this[J]?Buffer.concat([this[J],t]):t)}[xa](){if(this[qr]&&!this[Wd]&&!this[At]&&!this[Cs]){this[Wd]=!0;let t=this[En];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[Sn](Ra)}}[Ta](t){if(this[Cs]&&t)this[Gd](t);else if(!t&&!this[J])this[xa]();else if(t){if(this[Cs]=!0,this[J]){this[Gd](t);let e=this[J];this[J]=void 0,this[ka](e)}else this[ka](t);for(;this[J]&&this[J]?.length>=512&&!this[At]&&!this[Ia];){let e=this[J];this[J]=void 0,this[ka](e)}this[Cs]=!1}(!this[J]||this[qr])&&this[xa]()}[ka](t){let e=0,r=t.length;for(;e+512<=r&&!this[At]&&!this[Ia];)switch(this[et]){case"begin":case"header":this[N_](t,e),e+=512;break;case"ignore":case"body":e+=this[Hd](t,e);break;case"meta":e+=this[I_](t,e);break;default:throw new Error("invalid state: "+this[et])}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[At]||(this[te]?(t&&(this[Ps]+=t.length,this[te].write(t)),this[te].end()):(this[qr]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[xa]())),this}},zs=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"),SR=a(t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},"vn"),pg=a((t,e)=>{let r=new Map(e.map(o=>[zs(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||Nx(o).root||".",u;if(o===d)u=!1;else{let h=r.get(o);u=h!==void 0?h:s(Ix(o),d,l+1)}return r.set(o,u),u},"n");t.filter=n?(o,c)=>n(o,c)&&s(zs(o)):o=>s(zs(o))},"Qi"),TR=a(t=>{let e=new Xs(t),r=t.file,n;try{n=Ci.openSync(r,"r");let i=Ci.fstatSync(n),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),c=Ci.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=Ci.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{Ci.closeSync(n)}catch{}}},"Mn"),kR=a((t,e)=>{let r=new Xs(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("end",s),Ci.stat(i,(c,l)=>{if(c)o(c);else{let d=new Tu(i,{readSize:n,size:l.size});d.on("error",o),d.pipe(r)}})})},"Bn"),Ui=Ks(TR,kR,t=>new Xs(t),t=>new Xs(t),(t,e)=>{e?.length&&pg(t,e),t.noResume||SR(t)}),fg=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:RR,parse:P_}=xR,Ou=a(t=>{let e="",r=P_(t);for(;RR(t)||r.root;){let n=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(n.length),e+=n,r=P_(t)}return[e,t]},"ce"),Ka=["|","<",">","?",":"],Iu=Ka.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),OR=new Map(Ka.map((t,e)=>[t,Iu[e]])),IR=new Map(Iu.map((t,e)=>[t,Ka[e]])),D_=a(t=>Ka.reduce((e,r)=>e.split(r).join(OR.get(r)),t),"ts"),NR=a(t=>Iu.reduce((e,r)=>e.split(r).join(IR.get(r)),t),"Qs"),mg=a((t,e)=>e?(t=P(t).replace(/^\.(\/|$)/,""),zs(e)+"/"+t):P(t),"rr"),AR=16*1024*1024,$_=Symbol("process"),U_=Symbol("file"),j_=Symbol("directory"),au=Symbol("symlink"),M_=Symbol("hardlink"),Ds=Symbol("header"),Da=Symbol("read"),cu=Symbol("lstat"),$a=Symbol("onlstat"),lu=Symbol("onread"),du=Symbol("onreadlink"),uu=Symbol("openfile"),hu=Symbol("onopenfile"),Jr=Symbol("close"),Ha=Symbol("mode"),pu=Symbol("awaitDrain"),Vd=Symbol("ondrain"),Ct=Symbol("prefix"),_g=class extends Nn{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=ku(e);super(),this.path=P(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||AR,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=P(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?P(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]=Ou(this.path);s&&typeof o=="string"&&(this.path=o,n=s)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=NR(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=P(r.absolute||C_.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[$a](i):this[cu]()}warn(t,e,r={}){return Xa(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[cu](){Lt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[$a](e)})}[$a](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=PR(t),this.emit("stat",t),this[$_]()}[$_](){switch(this.type){case"File":return this[U_]();case"Directory":return this[j_]();case"SymbolicLink":return this[au]();default:return this.end()}}[Ha](t){return fg(t,this.type==="Directory",this.portable)}[Ct](t){return mg(t,this.prefix)}[Ds](){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 In({path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](this.linkpath):this.linkpath,mode:this[Ha](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 za({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[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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)}[j_](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Ds](),this.end()}[au](){Lt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[du](e)})}[du](t){this.linkpath=P(t),this[Ds](),this.end()}[M_](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=P(C_.relative(this.cwd,t)),this.stat.size=0,this[Ds](),this.end()}[U_](){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[M_](e);this.linkCache.set(t,this.absolute)}if(this[Ds](),this.stat.size===0)return this.end();this[uu]()}[uu](){Lt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[hu](e)})}[hu](t){if(this.fd=t,this.#e)return this[Jr]();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[Da]()}[Da](){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");Lt.read(t,e,r,n,i,(s,o)=>{if(s)return this[Jr](()=>this.emit("error",s));this[lu](o)})}[Jr](t=()=>{}){this.fd!==void 0&&Lt.close(this.fd,t)}[lu](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[Jr](()=>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[Jr](()=>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[Vd]():this[pu](()=>this[Vd]())}[pu](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)}[Vd](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Jr](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[Da]()}},LR=class extends _g{static{a(this,"ni")}sync=!0;[cu](){this[$a](Lt.lstatSync(this.absolute))}[au](){this[du](Lt.readlinkSync(this.absolute))}[uu](){this[hu](Lt.openSync(this.absolute,"r"))}[Da](){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=Lt.readSync(e,r,n,i,s);this[lu](o),t=!1}finally{if(t)try{this[Jr](()=>{})}catch{}}}[pu](t){t()}[Jr](t=()=>{}){this.fd!==void 0&&Lt.closeSync(this.fd),t()}},CR=class extends Nn{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 Xa(this,t,e,r)}constructor(t,e={}){let r=ku(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=P(t.path),this.mode=t.mode!==void 0?this[Ha](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?P(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[o,c]=Ou(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 In({path:this[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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 za({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[Ct](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Ct](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)}[Ct](t){return mg(t,this.prefix)}[Ha](t){return fg(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}},PR=a(t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported","Gn"),DR=class Pi{static{a(this,"s")}tail;head;length=0;static create(e=[]){return new Pi(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++)UR(this,e[r]);return this.length}unshift(...e){for(var r=0,n=e.length;r<n;r++)jR(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 Pi;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 Pi;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 Pi;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 Pi;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=$R(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($R,"Zn");a(UR,"Yn");a(jR,"Kn");Nu=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}},F_=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}},q_=Buffer.alloc(1024),Ua=Symbol("onStat"),$s=Symbol("ended"),pt=Symbol("queue"),Us=Symbol("pendingLinks"),zr=Symbol("current"),kn=Symbol("process"),js=Symbol("processing"),Na=Symbol("processJob"),ft=Symbol("jobs"),Yd=Symbol("jobDone"),ja=Symbol("addFSEntry"),z_=Symbol("addTarEntry"),fu=Symbol("stat"),mu=Symbol("readdir"),Ma=Symbol("onreaddir"),Ba=Symbol("pipe"),W_=Symbol("entry"),Xd=Symbol("entryOpt"),Fa=Symbol("writeEntryClass"),gg=Symbol("write"),Kd=Symbol("ondrain"),Za=class extends Nn{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;[Fa];onWriteEntry;[pt];[Us]=new Map;[ft]=0;[js]=!1;[$s]=!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=P(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[Fa]=_g,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 zx(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Hx(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Jx(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[Kd]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Kd]);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[pt]=new DR,this[ft]=0,this.jobs=Number(t.jobs)||4,this[js]=!1,this[$s]=!1}[gg](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[$s]=!0,this[kn](),r&&r(),this}write(t){if(this[$s])throw new Error("write after end");return typeof t=="string"?this[ja](t):this[z_](t),this.flowing}[z_](t){let e=P(B_.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new F_(t.path,e);r.entry=new CR(t,this[Xd](r)),r.entry.on("end",()=>this[Yd](r)),this[ft]+=1,this[pt].push(r)}this[kn]()}[ja](t){let e=P(B_.resolve(this.cwd,t));this[pt].push(new F_(t,e)),this[kn]()}[fu](t){t.pending=!0,this[ft]+=1;let e=this.follow?"stat":"lstat";Wa[e](t.absolute,(r,n)=>{t.pending=!1,this[ft]-=1,r?this.emit("error",r):this[Ua](t,n)})}[Ua](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[zr])this[Na](t);else{let r=`${e.dev}:${e.ino}`,n=this[Us].get(r);n?n.push(t):this[Us].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[kn]()}[mu](t){t.pending=!0,this[ft]+=1,Wa.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[ft]-=1,e)return this.emit("error",e);this[Ma](t,r)})}[Ma](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[kn]()}[kn](){if(!this[js]){this[js]=!0;for(let t=this[pt].head;t&&this[ft]<this.jobs;t=t.next)if(this[Na](t.value),t.value.ignore){let e=t.next;this[pt].removeNode(t),t.next=e}this[js]=!1,this[$s]&&this[pt].length===0&&this[ft]===0&&(this.zip?this.zip.end(q_):(super.write(q_),super.end()))}}get[zr](){return this[pt]&&this[pt].head&&this[pt].head.value}[Yd](t){this[pt].shift(),this[ft]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,n=this[Us].get(r);if(n){this[Us].delete(r);for(let i of n)i.pending=!1,this[Na](i)}}this[kn]()}[Na](t){if(t.pending&&t.pendingLink&&t===this[zr]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[zr]&&!t.piped&&this[Ba](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Ua](t,e):this[fu](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Ma](t,e):this[mu](t),!t.readdir)return}if(t.entry=this[W_](t),!t.entry){t.ignore=!0;return}t===this[zr]&&!t.piped&&this[Ba](t)}}}[Xd](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}}[W_](t){this[ft]+=1;try{return new this[Fa](t.path,this[Xd](t)).on("end",()=>this[Yd](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Kd](){this[zr]&&this[zr].entry&&this[zr].entry.resume()}[Ba](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[ja](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={}){Xa(this,t,e,r)}},Au=class extends Za{static{a(this,"kt")}sync=!0;constructor(t){super(t),this[Fa]=LR}pause(){}resume(){}[fu](t){let e=this.follow?"statSync":"lstatSync";this[Ua](t,Wa[e](t.absolute))}[mu](t){this[Ma](t,Wa.readdirSync(t.absolute))}[Ba](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[ja](s+n)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",n=>{r.write(n)}):e.on("data",n=>{super[gg](n)})}},MR=a((t,e)=>{let r=new Au(t),n=new ig(t.file,{mode:t.mode||438});r.pipe(n),wg(r,e)},"Vn"),BR=a((t,e)=>{let r=new Za(t),n=new Va(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 yg(r,e).catch(s=>r.emit("error",s)),i},"$n"),wg=a((t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ui({file:sg.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r)}),t.end()},"fr"),yg=a(async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ui({file:sg.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:a(n=>{t.add(n)},"onReadEntry")}):t.add(r);t.end()},"dr"),FR=a((t,e)=>{let r=new Au(t);return wg(r,e),r},"Xn"),qR=a((t,e)=>{let r=new Za(t);return yg(r,e).catch(n=>r.emit("error",n)),r},"qn"),bg=Ks(MR,BR,FR,qR,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),WR=process.env.__FAKE_PLATFORM__||process.platform,Tg=WR==="win32",{O_CREAT:kg,O_NOFOLLOW:H_,O_TRUNC:xg,O_WRONLY:Rg}=Sg.constants,Og=Number(process.env.__FAKE_FS_O_FILENAME__)||Sg.constants.UV_FS_O_FILEMAP||0,HR=Tg&&!!Og,GR=512*1024,JR=Og|xg|kg|Rg,G_=!Tg&&typeof H_=="number"?H_|xg|kg|Rg:null,Ig=G_!==null?()=>G_:HR?t=>t<GR?JR:"w":()=>"w",_u=a((t,e,r)=>{try{return Qa.lchownSync(t,e,r)}catch(n){if(n?.code!=="ENOENT")throw n}},"ps"),Ga=a((t,e,r,n)=>{Qa.lchown(t,e,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},"Ei"),VR=a((t,e,r,n,i)=>{if(e.isDirectory())Ng(Ws.resolve(t,e.name),r,n,s=>{if(s)return i(s);let o=Ws.resolve(t,e.name);Ga(o,r,n,i)});else{let s=Ws.resolve(t,e.name);Ga(s,r,n,i)}},"io"),Ng=a((t,e,r,n)=>{Qa.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 Ga(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 Ga(t,e,r,n)}},"a");for(let d of s)VR(t,d,e,r,l)})},"Es"),YR=a((t,e,r,n)=>{e.isDirectory()&&Ag(Ws.resolve(t,e.name),r,n),_u(Ws.resolve(t,e.name),r,n)},"so"),Ag=a((t,e,r)=>{let n;try{n=Qa.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return _u(t,e,r);throw s}for(let i of n)YR(t,i,e,r);return _u(t,e,r)},"ws"),Lg=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"}},ec=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"}},KR=a((t,e)=>{qe.stat(t,(r,n)=>{(r||!n.isDirectory())&&(r=new Lg(t,r?.code||"ENOTDIR")),e(r)})},"no"),ZR=a((t,e,r)=>{t=P(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=P(e.cwd),p=a((m,_)=>{m?r(m):_&&l?Ng(_,o,c,w=>p(w)):s?qe.chmod(t,i,r):r()},"y");if(t===h)return KR(t,p);if(d)return XR.mkdir(t,{mode:i,recursive:!0}).then(m=>p(null,m??void 0),p);let f=P(Ja.relative(h,t)).split("/");gu(h,f,i,u,h,void 0,p)},"gr"),gu=a((t,e,r,n,i,s,o)=>{if(e.length===0)return o(null,s);let c=e.shift(),l=P(Ja.resolve(t+"/"+c));qe.mkdir(l,r,Cg(l,e,r,n,i,s,o))},"Ss"),Cg=a((t,e,r,n,i,s,o)=>c=>{c?qe.lstat(t,(l,d)=>{if(l)l.path=l.path&&P(l.path),o(l);else if(d.isDirectory())gu(t,e,r,n,i,s,o);else if(n)qe.unlink(t,u=>{if(u)return o(u);qe.mkdir(t,r,Cg(t,e,r,n,i,s,o))});else{if(d.isSymbolicLink())return o(new ec(t,t+"/"+e.join("/")));o(c)}}):(s=s||t,gu(t,e,r,n,i,s,o))},"br"),QR=a(t=>{let e=!1,r;try{e=qe.statSync(t).isDirectory()}catch(n){r=n?.code}finally{if(!e)throw new Lg(t,r??"ENOTDIR")}},"oo"),e1=a((t,e)=>{t=P(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=P(e.cwd),h=a(m=>{m&&c&&Ag(m,s,o),i&&qe.chmodSync(t,n)},"d");if(t===u)return QR(u),h();if(l)return h(qe.mkdirSync(t,{mode:n,recursive:!0})??void 0);let p=P(Ja.relative(u,t)).split("/"),f;for(let m=p.shift(),_=u;m&&(_+="/"+m);m=p.shift()){_=P(Ja.resolve(_));try{qe.mkdirSync(_,n),f=f||_}catch{let w=qe.lstatSync(_);if(w.isDirectory())continue;if(d){qe.unlinkSync(_),qe.mkdirSync(_,n),f=f||_;continue}else if(w.isSymbolicLink())return new ec(_,_+"/"+p.join("/"))}}return h(f)},"_r"),Zd=Object.create(null),J_=1e4,Oi=new Set,t1=a(t=>{Oi.has(t)?Oi.delete(t):Zd[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Oi.add(t);let e=Zd[t],r=Oi.size-J_;if(r>J_/10){for(let n of Oi)if(Oi.delete(n),delete Zd[n],--r<=0)break}return e},"Tr"),r1=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,n1=r1==="win32",i1=a(t=>t.split("/").slice(0,-1).reduce((e,r)=>{let n=e.at(-1);return n!==void 0&&(r=Pg(n,r)),e.push(r||"/"),e},[]),"lo"),s1=class{static{a(this,"yi")}#e=new Map;#r=new Map;#n=new Set;reserve(t,e){t=n1?["win32 parallelization disabled"]:t.map(n=>zs(Pg(t1(n))));let r=new Set(t.map(n=>i1(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.#s(e)}#c(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.#c(t);return e.every(n=>n&&n[0]===t)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#s(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.#s(s)),!0}},o1=a(()=>process.umask(),"Lr"),V_=Symbol("onEntry"),wu=Symbol("checkFs"),Y_=Symbol("checkFs2"),yu=Symbol("isReusable"),tt=Symbol("makeFs"),bu=Symbol("file"),vu=Symbol("directory"),qa=Symbol("link"),X_=Symbol("symlink"),K_=Symbol("hardlink"),Fs=Symbol("ensureNoSymlink"),Z_=Symbol("unsupported"),Q_=Symbol("checkPath"),Qd=Symbol("stripAbsolutePath"),Vr=Symbol("mkdir"),pe=Symbol("onError"),Aa=Symbol("pending"),eg=Symbol("pend"),Ii=Symbol("unpend"),eu=Symbol("ended"),tu=Symbol("maybeClose"),Eu=Symbol("skip"),Hs=Symbol("doChown"),Gs=Symbol("uid"),Js=Symbol("gid"),Vs=Symbol("checkedCwd"),a1=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ys=a1==="win32",c1=1024,l1=a((t,e)=>{if(!Ys)return B.unlink(t,e);let r=t+".DELETE."+Eg(16).toString("hex");B.rename(t,r,n=>{if(n)return e(n);B.unlink(r,e)})},"mo"),d1=a(t=>{if(!Ys)return B.unlinkSync(t);let e=t+".DELETE."+Eg(16).toString("hex");B.renameSync(t,e),B.unlinkSync(e)},"po"),tg=a((t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,"vr"),Lu=class extends Xs{static{a(this,"Xt")}[eu]=!1;[Vs]=!1;[Aa]=0;reservations=new s1;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[eu]=!0,this[tu]()},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:c1,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ys,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=P(oe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:o1():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[V_](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[tu](){this[eu]&&this[Aa]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Qd](t,e){let r=t[e],{type:n}=t;if(!r||this.preservePaths)return!0;let[i,s]=Ou(r),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||Ys&&/^[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=oe.posix.dirname(t.path),l=oe.posix.normalize(oe.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}[Q_](t){let e=P(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let n=P(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[Qd](t,"path")||!this[Qd](t,"linkpath"))return!1;if(t.absolute=oe.isAbsolute(t.path)?P(oe.resolve(t.path)):P(oe.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:P(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}=oe.win32.parse(String(t.absolute));t.absolute=n+D_(String(t.absolute).slice(n.length));let{root:i}=oe.win32.parse(t.path);t.path=i+D_(t.path.slice(i.length))}return!0}[V_](t){if(!this[Q_](t))return t.resume();switch(zR.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[wu](t);default:return this[Z_](t)}}[pe](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Ii](),e.resume())}[Vr](t,e,r){ZR(P(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)}[Hs](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}[Gs](t){return tg(this.uid,t.uid,this.processUid)}[Js](t){return tg(this.gid,t.gid,this.processGid)}[bu](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new Va(String(t.absolute),{flags:Ig(t.size),mode:r,autoClose:!1});n.on("error",c=>{n.fd&&B.close(n.fd,()=>{}),n.write=()=>!0,this[pe](c,t),e()});let i=1,s=a(c=>{if(c){n.fd&&B.close(n.fd,()=>{}),this[pe](c,t),e();return}--i===0&&n.fd!==void 0&&B.close(n.fd,l=>{l?this[pe](l,t):this[Ii](),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;B.futimes(l,d,u,h=>h?B.utimes(c,d,u,p=>s(p&&h)):s())}if(typeof l=="number"&&this[Hs](t)){i++;let d=this[Gs](t),u=this[Js](t);typeof d=="number"&&typeof u=="number"&&B.fchown(l,d,u,h=>h?B.chown(c,d,u,p=>s(p&&h)):s())}s()});let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",c=>{this[pe](c,t),e()}),t.pipe(o)),o.pipe(n)}[vu](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Vr](String(t.absolute),r,n=>{if(n){this[pe](n,t),e();return}let i=1,s=a(()=>{--i===0&&(e(),this[Ii](),t.resume())},"o");t.mtime&&!this.noMtime&&(i++,B.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Hs](t)&&(i++,B.chown(String(t.absolute),Number(this[Gs](t)),Number(this[Js](t)),s)),s()})}[Z_](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[X_](t,e){let r=P(oe.relative(this.cwd,oe.resolve(oe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Fs](t,this.cwd,r,()=>this[qa](t,String(t.linkpath),"symlink",e),n=>{this[pe](n,t),e()})}[K_](t,e){let r=P(oe.resolve(this.cwd,String(t.linkpath))),n=P(String(t.linkpath)).split("/");this[Fs](t,this.cwd,n,()=>this[qa](t,r,"link",e),i=>{this[pe](i,t),e()})}[Fs](t,e,r,n,i){let s=r.shift();if(this.preservePaths||s===void 0)return n();let o=oe.resolve(e,s);B.lstat(o,(c,l)=>{if(c)return n();if(l?.isSymbolicLink())return i(new ec(o,oe.resolve(o,r.join("/"))));this[Fs](t,o,r,n,i)})}[eg](){this[Aa]++}[Ii](){this[Aa]--,this[tu]()}[Eu](t){this[Ii](),t.resume()}[yu](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ys}[wu](t){this[eg]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Y_](t,r))}[Y_](t,e){let r=a(o=>{e(o)},"i"),n=a(()=>{this[Vr](this.cwd,this.dmode,o=>{if(o){this[pe](o,t),r();return}this[Vs]=!0,i()})},"r"),i=a(()=>{if(t.absolute!==this.cwd){let o=P(oe.dirname(String(t.absolute)));if(o!==this.cwd)return this[Vr](o,this.dmode,c=>{if(c){this[pe](c,t),r();return}s()})}s()},"n"),s=a(()=>{B.lstat(String(t.absolute),(o,c)=>{if(c&&(this.keep||this.newer&&c.mtime>(t.mtime??c.mtime))){this[Eu](t),r();return}if(o||this[yu](t,c))return this[tt](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[tt](u??null,t,r),"c");return l?B.chmod(String(t.absolute),Number(t.mode),d):d()}if(t.absolute!==this.cwd)return B.rmdir(String(t.absolute),l=>this[tt](l??null,t,r))}if(t.absolute===this.cwd)return this[tt](null,t,r);l1(String(t.absolute),l=>this[tt](l??null,t,r))})},"o");this[Vs]?i():n()}[tt](t,e,r){if(t){this[pe](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[bu](e,r);case"Link":return this[K_](e,r);case"SymbolicLink":return this[X_](e,r);case"Directory":case"GNUDumpDir":return this[vu](e,r)}}[qa](t,e,r,n){B[r](e,String(t.absolute),i=>{i?this[pe](i,t):(this[Ii](),t.resume()),n()})}},Ms=a(t=>{try{return[null,t()]}catch(e){return[e,null]}},"ye"),Dg=class extends Lu{static{a(this,"xe")}sync=!0;[tt](t,e){return super[tt](t,e,()=>{})}[wu](t){if(!this[Vs]){let i=this[Vr](this.cwd,this.dmode);if(i)return this[pe](i,t);this[Vs]=!0}if(t.absolute!==this.cwd){let i=P(oe.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Vr](i,this.dmode);if(s)return this[pe](s,t)}}let[e,r]=Ms(()=>B.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Eu](t);if(e||this[yu](t,r))return this[tt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[o]=s?Ms(()=>{B.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[tt](o,t)}let[i]=Ms(()=>B.rmdirSync(String(t.absolute)));this[tt](i,t)}let[n]=t.absolute===this.cwd?[]:Ms(()=>d1(String(t.absolute)));this[tt](n,t)}[bu](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=a(o=>{let c;try{B.closeSync(i)}catch(l){c=l}(o||c)&&this[pe](o||c,t),e()},"r"),i;try{i=B.openSync(String(t.absolute),Ig(t.size),r)}catch(o){return n(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[pe](o,t)),t.pipe(s)),s.on("data",o=>{try{B.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{B.futimesSync(i,c,l)}catch(d){try{B.utimesSync(String(t.absolute),c,l)}catch{o=d}}}if(this[Hs](t)){let c=this[Gs](t),l=this[Js](t);try{B.fchownSync(i,Number(c),Number(l))}catch(d){try{B.chownSync(String(t.absolute),Number(c),Number(l))}catch{o=o||d}}}n(o)})}[vu](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[Vr](String(t.absolute),r);if(n){this[pe](n,t),e();return}if(t.mtime&&!this.noMtime)try{B.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Hs](t))try{B.chownSync(String(t.absolute),Number(this[Gs](t)),Number(this[Js](t)))}catch{}e(),t.resume()}[Vr](t,e){try{return e1(P(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}}[Fs](t,e,r,n,i){if(this.preservePaths||r.length===0)return n();let s=e;for(let o of r){s=oe.resolve(s,o);let[c,l]=Ms(()=>B.lstatSync(s));if(c)return n();if(l.isSymbolicLink())return i(new ec(s,oe.resolve(e,r.join("/"))))}n()}[qa](t,e,r,n){let i=`${r}Sync`;try{B[i](e,String(t.absolute)),n(),t.resume()}catch(s){return this[pe](s,t)}}},u1=a(t=>{let e=new Dg(t),r=t.file,n=vg.statSync(r),i=t.maxReadSize||16*1024*1024;new Ox(r,{readSize:i,size:n.size}).pipe(e)},"Eo"),h1=a((t,e)=>{let r=new Lu(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("close",s),vg.stat(i,(c,l)=>{if(c)o(c);else{let d=new Tu(i,{readSize:n,size:l.size});d.on("error",o),d.pipe(r)}})})},"wo"),$g=Ks(u1,h1,t=>new Dg(t),t=>new Lu(t),(t,e)=>{e?.length&&pg(t,e)}),p1=a((t,e)=>{let r=new Au(t),n=!0,i,s;try{try{i=Fe.openSync(t.file,"r+")}catch(l){if(l?.code==="ENOENT")i=Fe.openSync(t.file,"w+");else throw l}let o=Fe.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=Fe.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 In(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,f1(t,r,s,i,e)}finally{if(n)try{Fe.closeSync(i)}catch{}}},"yo"),f1=a((t,e,r,n,i)=>{let s=new ig(t.file,{fd:n,start:r});e.pipe(s),_1(e,i)},"Ro"),m1=a((t,e)=>{e=Array.from(e);let r=new Za(t),n=a((i,s,o)=>{let c=a((p,f)=>{p?Fe.close(i,m=>o(p)):o(null,f)},"a"),l=0;if(s===0)return c(null,0);let d=0,u=Buffer.alloc(512),h=a((p,f)=>{if(p||f===void 0)return c(p);if(d+=f,d<512&&f)return Fe.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 In(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,Fe.read(i,u,0,512,l,h)},"y");Fe.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+",Fe.open(t.file,o,c);if(l||!d)return s(l);Fe.fstat(d,(u,h)=>{if(u)return Fe.close(d,()=>s(u));n(d,h.size,(p,f)=>{if(p)return s(p);let m=new Va(t.file,{fd:d,start:f});r.pipe(m),m.on("error",s),m.on("close",i),g1(r,e)})})},"a");Fe.open(t.file,o,c)})},"go"),_1=a((t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ui({file:Ug.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r)}),t.end()},"bo"),g1=a(async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ui({file:Ug.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:a(n=>t.add(n),"onReadEntry")}):t.add(r);t.end()},"_o"),Bs=Ks(p1,m1,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!$x(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")}),cM=Ks(Bs.syncFile,Bs.asyncFile,Bs.syncNoFile,Bs.asyncNoFile,(t,e=[])=>{Bs.validate?.(t,e),w1(t)}),w1=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{execFile as y1}from"node:child_process";import{createHash as b1,randomUUID as Bg}from"node:crypto";import{existsSync as Cu}from"node:fs";import{lstat as Fg,mkdir as v1,readdir as E1,rename as Mg,rm as tc,stat as qg,open as S1}from"node:fs/promises";import{basename as zg,dirname as Zs,isAbsolute as T1,join as ji,relative as k1,resolve as Dt,sep as x1}from"node:path";async function Hg(t,e={}){let r=Dt(t);if(!(await Fg(r)).isDirectory())throw new Error(`Directory source expected: ${r}`);let i=await A1(r,e.gitignore?await I1(r):null),s=Dt(e.stagingDirectory||ji(x(),"staging"));xe(s);let o=Dt(e.output||ji(s,`directory-${Bg()}.tar`));return await bg({cwd:r,file:o,portable:!0,noMtime:!0,noDirRecurse:!0,follow:!1,gzip:!1,strict:!0},i.length>0?i:["."]),{path:o,kind:R1,source_name:`${zg(r)}.tar`,original_path:r,entries:i.length,size:(await qg(o)).size,temporary:!0}}async function Gg(t,e,r={}){r.signal?.throwIfAborted();let n=Dt(t),i=Dt(e),s=await qg(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 L1(n,o),r.signal?.throwIfAborted(),Cu(i)&&!r.overwrite)throw new Error(`Destination already exists: ${i}`);let{stage:c,backup:l}=O1(i,r.transferId||Bg());await tc(c,{recursive:!0,force:!0}),await v1(c,{recursive:!0,mode:448});let d=!1;try{if(await $g({cwd:c,file:n,preservePaths:!1,strict:!0,unlink:!0,filter:a((u,h)=>Wg.has(h.type),"filter")}),r.signal?.throwIfAborted(),await r.onStaged?.({destination:i,stage:c,backup:l}),d=!0,r.signal?.throwIfAborted(),Cu(i)){if(!r.overwrite)throw Object.assign(new Error(`Destination already exists: ${i}`),{code:"destination_exists"});if(Cu(l))throw Object.assign(new Error(`Directory backup already exists: ${l}`),{code:"directory_recovery_required"});await Mg(i,l),await Pu(Zs(i)),await r.onBackedUp?.({destination:i,stage:c,backup:l})}await Mg(c,i),await Pu(Zs(i)),await r.onPublished?.({destination:i,stage:c,backup:l}),await tc(l,{recursive:!0,force:!0}),await Pu(Zs(i)),await r.onCleaned?.({destination:i,stage:c,backup:l})}catch(u){throw d||await tc(c,{recursive:!0,force:!0}),u}return i}function O1(t,e){let r=Dt(t),n=b1("sha256").update(String(e)).digest("hex").slice(0,24),i=`.${zg(r).slice(0,40)}.interscale-${n}`;return{destination:r,stage:ji(Zs(r),`${i}.stage`),backup:ji(Zs(r),`${i}.backup`)}}async function Pu(t){if(process.platform==="win32")return;let e=await S1(t,"r");try{await e.sync()}catch(r){if(!["EINVAL","ENOTSUP"].includes(r.code))throw r}finally{await e.close()}}async function An(t){let e=Dt(ji(x(),"staging")),r=Dt(t),n=k1(e,r);return!n||n.startsWith("..")||T1(n)?!1:(await tc(r,{force:!0}),!0)}async function I1(t,{run:e=N1}={}){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 N1(t,e){return new Promise((r,n)=>y1(t,e,{encoding:"utf8",maxBuffer:256*1024*1024,windowsHide:!0,timeout:6e4},(i,s)=>i?n(i):r(s)))}async function A1(t,e=null){let r=[];return await n(""),r;async function n(i){let s=Dt(t,i),o=await E1(s,{withFileTypes:!0});o.sort((c,l)=>P1(c.name,l.name));for(let c of o){let l=i?ji(i,c.name):c.name,d=l.split(x1).join("/");if(e&&!e(d,c.isDirectory()))continue;let u=await Fg(Dt(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 L1(t,e){let r=0,n=null,i=new Map;if(await Ui({file:t,strict:!0,onReadEntry(s){if(!n)try{if(C1(s.path),!Wg.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 C1(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 P1(t,e){return Buffer.compare(Buffer.from(t,"utf8"),Buffer.from(e,"utf8"))}var R1,Wg,rc=v(()=>{jg();Re();Z();R1="directory-tar",Wg=new Set(["File","OldFile","Directory"]);a(Hg,"createDirectoryArchive");a(Gg,"extractDirectoryArchive");a(O1,"directoryPublicationPaths");a(Pu,"syncDirectory");a(An,"cleanupStagedArchive");a(I1,"gitTrackedFilter");a(N1,"execFileText");a(A1,"enumerateDirectory");a(L1,"validateDirectoryArchive");a(C1,"validateArchivePath");a(P1,"compareNames")});import{createHash as D1}from"node:crypto";import{lstat as $1,open as U1}from"node:fs/promises";function nc(t){return JSON.stringify([t.dev,t.ino,t.size,t.mtimeMs,t.ctimeMs,t.birthtimeMs])}function Ln(t,e){if(!e.isFile()||e.isSymbolicLink()||nc(t)!==nc(e))throw Object.assign(new Error("Source changed while its content was being indexed; retry after writes finish"),{code:"source_changed"})}async function Kr(t,{expected:e,signal:r,io:n={lstat:$1,open:U1}}={}){r?.throwIfAborted();let i=e||await n.lstat(t);Ln(i,i);let s=await n.open(t,"r");try{Ln(i,await s.stat());let o=D1("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(),Ln(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 Ln(i,d),o.digest("hex")}finally{await s.close()}}var Qs=v(()=>{a(nc,"fileRevision");a(Ln,"assertFileRevision");a(Kr,"hashStableFile")});import{constants as Jg}from"node:fs";import{copyFile as j1,chmod as M1,lstat as B1,mkdir as F1,open as q1,rm as z1,statfs as W1}from"node:fs/promises";import{randomUUID as H1}from"node:crypto";import{basename as G1,join as J1}from"node:path";async function Vg(t,{stagingDirectory:e,reserve:r=1024**3,signal:n,hash:i=Kr,filesystem:s={copyFile:j1,chmod:M1,lstat:B1,mkdir:F1,open:q1,rm:z1,statfs:W1}}={}){n?.throwIfAborted();let o=await s.lstat(t);Ln(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=J1(e,`file-${H1()}.snapshot`);try{n?.throwIfAborted(),await s.copyFile(t,l,Jg.COPYFILE_EXCL|Jg.COPYFILE_FICLONE),n?.throwIfAborted(),await s.chmod(l,384),Ln(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:G1(t),size:d.size,temporary:!0,sha256:u}}catch(d){throw await s.rm(l,{force:!0}).catch(()=>{}),d}}var Yg=v(()=>{Qs();a(Vg,"createFileSnapshot")});var Xg={};K(Xg,{FileHasher:()=>Cn});import{Worker as V1}from"node:worker_threads";var Cn,ic=v(()=>{Qs();Cn=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:nc(r)})}catch(u){this.retire(i,u)}})}start(){let e=new V1(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 Y1}from"node:fs/promises";import{join as X1}from"node:path";async function Mi(t,e={}){e.signal?.throwIfAborted();let r=await Y1(t);if(r.isSymbolicLink())throw new Error(`Symbolic links are not accepted as transfer sources: ${t}`);if(r.isFile()){let n=new Cn;try{return await Vg(t,{stagingDirectory:e.stagingDirectory||X1(x(),"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
|
|
23
|
+
`);let n=await Hg(t,{stagingDirectory:e.stagingDirectory,gitignore:e.gitignore===!0});return e.json||process.stderr.write(`Prepared deterministic archive (${n.size} bytes, ${n.entries} entries).
|
|
24
|
+
`),n}throw new Error(`Transfer source must be a regular file or directory: ${t}`)}var Du=v(()=>{rc();Yg();Z();ic();a(Mi,"prepareTransferSource")});import{chmodSync as K1,existsSync as Z1,mkdirSync as Qg}from"node:fs";import{dirname as Q1,join as Kg,resolve as sc}from"node:path";import{DatabaseSync as eO}from"node:sqlite";import{randomUUID as tO}from"node:crypto";import{isDeepStrictEqual as ew}from"node:util";function ac(t,e=ys()){if(!Z1(e))return null;let r=new Pn(e);try{return r.database.prepare("SELECT token FROM transfers WHERE id = ?").get(t)?.token??null}finally{r.close()}}var oc,Zg,Pn,Dn,cc=v(()=>{Z();oc=class{static{a(this,"ResumeStateStore")}constructor(e,r){this.kind=r,Qg(Q1(e),{recursive:!0,mode:448}),this.database=new eO(e,{timeout:5e3});try{K1(e,384)}catch{}this.database.exec(`
|
|
25
|
+
PRAGMA journal_mode = WAL;
|
|
26
|
+
CREATE TABLE IF NOT EXISTS ${r}_requests (
|
|
27
|
+
request_id TEXT PRIMARY KEY,
|
|
28
|
+
server_url TEXT NOT NULL,
|
|
29
|
+
input_json TEXT NOT NULL,
|
|
30
|
+
${r==="download"?"output_path TEXT NOT NULL,":""}
|
|
31
|
+
${r}_id TEXT,
|
|
32
|
+
created_at INTEGER NOT NULL
|
|
33
|
+
) STRICT;
|
|
34
|
+
`)}prepareRequest({serverUrl:e,input:r,outputPath:n,requestId:i=tO()}){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:sc(n)}:{},o=this.database.prepare(`SELECT * FROM ${this.kind}_requests WHERE request_id=?`).get(i);if(o){if(o.server_url!==e||!ew(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()}},Zg=`
|
|
35
|
+
id TEXT PRIMARY KEY,
|
|
36
|
+
server_url TEXT NOT NULL,
|
|
37
|
+
token TEXT NOT NULL,
|
|
38
|
+
job_id TEXT,
|
|
39
|
+
relative_path TEXT NOT NULL,
|
|
40
|
+
source_path TEXT,
|
|
41
|
+
output_path TEXT NOT NULL,
|
|
42
|
+
part_path TEXT NOT NULL,
|
|
43
|
+
download_json TEXT NOT NULL,
|
|
44
|
+
manifest_json TEXT,
|
|
45
|
+
received_json TEXT NOT NULL DEFAULT '[]',
|
|
46
|
+
published INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
state TEXT NOT NULL,
|
|
48
|
+
created_at INTEGER NOT NULL,
|
|
49
|
+
updated_at INTEGER NOT NULL
|
|
50
|
+
`,Pn=class extends oc{static{a(this,"TransferStateStore")}constructor(e=ys()){super(e,"transfer"),this.database.exec(`
|
|
51
|
+
CREATE TABLE IF NOT EXISTS transfers (
|
|
52
|
+
id TEXT PRIMARY KEY,
|
|
53
|
+
server_url TEXT NOT NULL,
|
|
54
|
+
token TEXT NOT NULL,
|
|
55
|
+
source_path TEXT NOT NULL,
|
|
56
|
+
target TEXT NOT NULL,
|
|
57
|
+
destination_path TEXT NOT NULL,
|
|
58
|
+
transfer_json TEXT NOT NULL,
|
|
59
|
+
temporary INTEGER NOT NULL DEFAULT 0,
|
|
60
|
+
state TEXT NOT NULL,
|
|
61
|
+
created_at INTEGER NOT NULL,
|
|
62
|
+
updated_at INTEGER NOT NULL
|
|
63
|
+
) STRICT;
|
|
64
|
+
`),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(`
|
|
65
|
+
INSERT INTO transfers(
|
|
66
|
+
id, server_url, token, source_path, target, destination_path,
|
|
67
|
+
transfer_json, temporary, state, created_at, updated_at
|
|
68
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
|
|
69
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
70
|
+
token = excluded.token,
|
|
71
|
+
source_path = excluded.source_path,
|
|
72
|
+
transfer_json = excluded.transfer_json,
|
|
73
|
+
temporary = excluded.temporary,
|
|
74
|
+
state = 'active',
|
|
75
|
+
updated_at = excluded.updated_at
|
|
76
|
+
`).run(o.id,e,r,sc(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(ac,"storedTransferToken");Dn=class extends oc{static{a(this,"DownloadStateStore")}constructor(e=jm(),r={}){super(e,"download"),this.partRoot=sc(r.partRoot||Kg(x(),"downloads")),this.database.exec(`
|
|
77
|
+
CREATE TABLE IF NOT EXISTS downloads (${Zg}) STRICT;
|
|
78
|
+
`),this.migrateForPulls(),this.database.exec(`CREATE TABLE IF NOT EXISTS download_chunk_hashes (
|
|
79
|
+
download_id TEXT NOT NULL, chunk_index INTEGER NOT NULL, sha256 TEXT NOT NULL,
|
|
80
|
+
PRIMARY KEY(download_id,chunk_index)
|
|
81
|
+
) 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(`
|
|
82
|
+
CREATE TABLE downloads_migrated (${Zg}) STRICT;
|
|
83
|
+
INSERT INTO downloads_migrated (
|
|
84
|
+
id, server_url, token, job_id, relative_path, output_path, part_path,
|
|
85
|
+
download_json, manifest_json, received_json, published, state, created_at, updated_at
|
|
86
|
+
)
|
|
87
|
+
SELECT id, server_url, token, job_id, relative_path, output_path, part_path,
|
|
88
|
+
download_json, manifest_json, received_json, published, state, created_at, updated_at
|
|
89
|
+
FROM downloads;
|
|
90
|
+
DROP TABLE downloads;
|
|
91
|
+
ALTER TABLE downloads_migrated RENAME TO downloads;
|
|
92
|
+
`)}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;Qg(u,{recursive:!0,mode:448});let h=Kg(u,`${c.id}.part`);return this.database.prepare(`
|
|
93
|
+
INSERT INTO downloads(
|
|
94
|
+
id, server_url, token, job_id, relative_path, source_path, output_path, part_path,
|
|
95
|
+
download_json, state, created_at, updated_at
|
|
96
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
|
|
97
|
+
ON CONFLICT(id) DO UPDATE SET token = excluded.token, download_json = excluded.download_json,
|
|
98
|
+
state = 'active', updated_at = excluded.updated_at
|
|
99
|
+
`).run(c.id,e,r,n,i||".",s,sc(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&&!ew(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(`
|
|
100
|
+
UPDATE downloads SET manifest_json = ?, updated_at = ? WHERE id = ?
|
|
101
|
+
`).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(`
|
|
102
|
+
SELECT id, job_id, relative_path, source_path, output_path, published, updated_at
|
|
103
|
+
FROM downloads WHERE state = 'active' ORDER BY updated_at DESC
|
|
104
|
+
`).all().map(e=>({...e,published:!!e.published}))}}});import{Agent as rO,request as nO}from"node:http";function iO(t){let e=t||"",r=tw.get(e);return r||(r=new rO({keepAlive:!0,keepAliveMsecs:15e3,maxSockets:32,...t?{localAddress:t}:{}}),tw.set(e,r)),r}async function mr(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(),$u();for await(let h of l.body||[]){if(u+=h.length,u>c)throw $u();d.push(h)}return rw(l.status,l.headers,Buffer.concat(d))}return new Promise((l,d)=>{let u=!1,h=a((w,g)=>{u||(u=!0,_(),w(g))},"finish"),p=new URL(t),f=nO({protocol:p.protocol,hostname:p.hostname.replace(/^\[/,"").replace(/\]$/,""),port:p.port||80,path:`${p.pathname}${p.search}`,method:r,headers:n,agent:iO(o)},w=>{let g=[],y=0,E=a(()=>{h(d,$u()),w.destroy(),f.destroy()},"tooLarge");if(w.on("data",S=>{if(y+=S.length,y>c){E();return}g.push(S)}),w.on("error",S=>h(d,S)),w.on("aborted",()=>h(d,new Error("Direct response ended prematurely"))),Number(w.headers["content-length"])>c){E();return}w.on("end",()=>{let S=Buffer.concat(g);h(l,rw(w.statusCode,{get:a(k=>w.headers[String(k).toLowerCase()]??null,"get")},S))})}),m=a(()=>{f.destroy(),h(d,sO(s))},"onAbort"),_=a(()=>s?.removeEventListener?.("abort",m),"cleanup");if(s){if(s.aborted)return m();s.addEventListener("abort",m,{once:!0})}f.on("error",w=>h(d,w)),i==null?f.end():f.end(i)})}function rw(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 $u(){return Object.assign(new Error("Direct response exceeds its permitted size"),{code:"response_too_large"})}function sO(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 tw,lc=v(()=>{tw=new Map;a(iO,"agentFor");a(mr,"directFetch");a(rw,"bufferedResponse");a($u,"responseLimitError");a(sO,"abortReason")});import{createCipheriv as oO,createDecipheriv as aO,createHash as cO,createHmac as lO,hkdfSync as iw,randomBytes as sw,timingSafeEqual as dO}from"node:crypto";function nw(t){return cO("sha256").update(t).digest()}function Uu(t=32){return sw(t).toString("base64url")}function ow(t,e){let r=nw(Buffer.from(String(t))),n=nw(Buffer.from(String(e)));return dO(r,n)}function aw(t,e,r,n){let i=lw(t,e),s=sw(12),o=oO("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 cw(t,e,r,n){if(n.length<28)throw new Error("Encrypted transfer chunk is truncated");let i=lw(t,e),s=n.subarray(0,12),o=n.subarray(12,28),c=n.subarray(28),l=aO("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 $n(t,e,r,n){let i=Buffer.from(iw("sha256",Buffer.from(t,"base64url"),Buffer.from(e,"utf8"),Buffer.from("interscale-transfer-auth-v1","utf8"),32));return lO("sha256",i).update(`${String(r).toUpperCase()}
|
|
105
|
+
${n}`,"utf8").digest("base64url")}function lw(t,e){return Buffer.from(iw("sha256",Buffer.from(t,"base64url"),Buffer.from(e,"utf8"),Buffer.from("interscale-transfer-v1","utf8"),32))}var Bi=v(()=>{a(nw,"sha256");a(Uu,"randomToken");a(ow,"constantTimeTextEqual");a(aw,"encryptTransferChunk");a(cw,"decryptTransferChunk");a($n,"transferRequestProof");a(lw,"deriveTransferKey")});import{randomBytes as uO}from"node:crypto";import{networkInterfaces as hO}from"node:os";function pO(t,e,r,n){return $n(t,e,"ROUTE_RESPONSE",JSON.stringify([r,n]))}function dc(t,e){_r.get(t)?.route===$t(e)&&_r.delete(t)}async function uc(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(hO()),c=_r.get(e),l=[...t];c&&c.expires>Date.now()&&c.network===o?l.sort((j,C)=>+($t(C)===c.route)-+($t(j)===c.route)):_r.delete(e);let d=new AbortController,u=s?AbortSignal.any([s,d.signal]):d.signal,h=new Set,p=new Set,f=new Set,m=0,_=0,w=1,g=null,y,E=new Promise(j=>{y=j}),S=a(async j=>{let C=uO(24).toString("base64url"),ee=`/v1/${i}/${encodeURIComponent(r)}/probe/${C}`,lt=new AbortController,re=setTimeout(()=>lt.abort(),750);try{let Rf=await mr(`${j.url.replace(/\/$/,"")}${ee}`,{headers:{authorization:`Interscale ${$n(n,r,"GET",ee)}`},signal:AbortSignal.any([u,lt.signal]),localAddress:j.localAddress,maxResponseBytes:4096});if(p.add($t(j)),!Rf.ok)return;let Fl;try{Fl=await Rf.json()}catch{h.add($t(j));return}if(Fl?.node_id!==e||!ow(String(Fl.proof||""),pO(n,r,e,C))){h.add($t(j));return}!g&&!u.aborted&&(g=j,y())}catch{u.aborted||h.add($t(j))}finally{clearTimeout(re)}},"probe"),k=a(()=>{for(;!u.aborted&&!g&&_<w&&m<l.length;){let j=l[m++];_++;let C=S(j).finally(()=>{_--,f.delete(C),k(),!_&&m===l.length&&y()});f.add(C)}},"launch"),$=a(()=>y(),"abort");u.addEventListener("abort",$,{once:!0});let q=setTimeout(()=>y(),2e3),V=setTimeout(()=>{w=3,k()},150);try{k(),await E}finally{d.abort(),clearTimeout(q),clearTimeout(V),await Promise.allSettled([...f]),u.removeEventListener("abort",$)}return s?.throwIfAborted(),g?(_r.size>=256&&_r.delete(_r.keys().next().value),_r.set(e,{route:$t(g),expires:Date.now()+3e5,network:o})):_r.delete(e),[...g?[g]:[],...l.filter(j=>j!==g&&!h.has($t(j))&&(g||p.has($t(j))))]}var _r,$t,ju=v(()=>{lc();Bi();a(pO,"routeResponseProof");_r=new Map,$t=a(t=>JSON.stringify([t.url,t.localAddress||""]),"routeKey");a(dc,"invalidateRoute");a(uc,"prioritizeDirectRoutes")});async function eo(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 Mu=v(()=>{a(eo,"parallelTransferMap")});import{constants as dw}from"node:fs";import{open as fO}from"node:fs/promises";function uw(t){return fO(t,dw.O_RDWR|dw.O_CREAT,384)}async function to(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 hw(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 Bu=v(()=>{a(uw,"openPartialFile");a(to,"readExactly");a(hw,"writeExactly")});function mO(t){if(!Number.isSafeInteger(t)||t<1||t>sa)throw Un("Transfer chunk size must be between 1 byte and 64 MiB")}function ro(t,{defaultKind:e}={}){if(!t||typeof t!="object"||Array.isArray(t))throw Un("Transfer manifest must be an object");let r=t.kind??e;if(!["file","directory-tar"].includes(r))throw Un("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 Un(`Transfer manifest has invalid ${n}`);if(mO(t.chunk_size),t.total_chunks>pw)throw Un(`Transfer exceeds ${pw} 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 Un("Transfer size and chunk count are inconsistent");if(typeof t.sha256!="string"||!/^[a-f0-9]{64}$/.test(t.sha256))throw Un("Transfer manifest has an invalid SHA-256");return{...t,kind:r}}var pw,Un,Fu=v(()=>{me();ye();pw=1e5,Un=a(t=>Object.assign(new N(400,"invalid_transfer_manifest",t),{terminal:!0}),"invalid");a(mO,"validateTransferChunkSize");a(ro,"validateTransferManifest")});import{createReadStream as _O}from"node:fs";import{mkdir as gO}from"node:fs/promises";import{createHash as zu}from"node:crypto";import{dirname as wO}from"node:path";async function Wu(t,e,r,n={}){if(e=ro(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 gO(wO(i.part_path),{recursive:!0,mode:448});let s=await uw(i.part_path),o=new Set(i.received);try{await s.truncate(e.size);for(let d of o){qu(n.signal);let u=i.chunk_hashes[d];(!Number.isSafeInteger(d)||d<0||d>=e.total_chunks||!u||await yO(s,d*e.chunk_size,fw(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 eo(l,Number(n.concurrency||4),async(d,u)=>{u.throwIfAborted();let h=fw(e,d),p=await n.fetchChunk({index:d,expectedBytes:h+28,signal:u});if(!Buffer.isBuffer(p)||p.length!==h+28)throw new Error(`Encrypted result chunk ${d} does not match its manifest size`);let f=cw(i.token,i.id,d,p);if(f.length!==h)throw new Error(`Result chunk ${d} has an invalid size`);u.throwIfAborted(),await hw(s,f,d*e.chunk_size),await s.sync(),r.markChunk(i.id,d,zu("sha256").update(f).digest("hex")),n.onProgress?.({index:d,total:e.total_chunks,bytes:f.length,skipped:!1,route:n.route||"direct"})},n.signal)}finally{await s.close()}qu(n.signal);let c=await bO(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 yO(t,e,r,n){let i=zu("sha256"),s=Buffer.allocUnsafe(Math.min(1024*1024,Math.max(1,r)));for(let o=0;o<r;){qu(n);let c=s.subarray(0,Math.min(s.length,r-o));await to(t,c,e+o),i.update(c),o+=c.length}return i.digest("hex")}function fw(t,e){return e===t.total_chunks-1?t.size-e*t.chunk_size:t.chunk_size}function bO(t,e){return new Promise((r,n)=>{let i=zu("sha256"),s=_O(t,{signal:e});s.on("error",n),s.on("data",o=>i.update(o)),s.on("end",()=>r(i.digest("hex")))})}function qu(t){t?.throwIfAborted()}var mw=v(()=>{Mu();Bi();Bu();Fu();a(Wu,"receiveDownloadChunks");a(yO,"hashChunk");a(fw,"chunkLength");a(bO,"hashFile");a(qu,"throwIfAborted")});var hc=M(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});Hu.default=vO;var _w=/[A-Z]/g;function gw(t){return t.toLowerCase()}a(gw,"toLowerCase");function vO(t,e){let r=t.replace(_w,gw),n=e.replace(_w,gw);return r===n}a(vO,"dnsEqual")});var Gu=M(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.DnsTxt=void 0;var pc=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},{})}};no.DnsTxt=pc;no.default=pc});var Ju=M(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.toType=Fi.toString=void 0;var ww=a(t=>"_"+t,"Prefix"),EO=a(t=>["name","protocol","subtype"].includes(t),"AllowedProp"),SO=a(t=>{let e={name:t.name,protocol:t.protocol,subtype:t.subtype};return Object.entries(e).filter(([n,i])=>EO(n)&&i!==void 0).reduce((n,[i,s])=>(typeof s==="object"?s.map(o=>n.push(ww(o))):n.push(ww(s)),n),[]).join(".")},"toString");Fi.toString=SO;var TO=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");Fi.toType=TO});var Vu=M(jn=>{"use strict";var bw=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.Service=void 0;var yw=bw(W("os")),kO=bw(Gu()),xO=W("events"),RO=Ju(),qi=".local",fc=class extends xO.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 kO.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,RO.toString)({name:e.type,protocol:this.protocol}),this.port=e.port,this.host=e.host||yw.default.hostname(),this.fqdn=`${this.name}.${this.type}${qi}`,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(yw.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}${qi}`,type:"PTR",ttl:28800,data:e.fqdn}}RecordServicePTR(e){return{name:`_services._dns-sd._udp${qi}`,type:"PTR",ttl:120,data:`${e.type}${qi}`}}RecordSubtypePTR(e,r){return{name:`_${r}._sub.${e.type}${qi}`,type:"PTR",ttl:28800,data:`${e.name}.${e.type}${qi}`}}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}}};jn.Service=fc;jn.default=fc});var Ew=M(Mn=>{"use strict";var vw=Mn&&Mn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Registry=void 0;var OO=vw(hc()),Yu=vw(Vu()),IO=3600*1e3,NO=3,AO=a(function(){},"noop"),mc=class{static{a(this,"Registry")}constructor(e){this.services=[],this.server=e}publish(e){let r=e.probe!==!1,n=new Yu.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 Yu.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=AO),!n.activated||!(n instanceof Yu.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,OO.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*NO,n<IO&&!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)})}};Mn.Registry=mc;Mn.default=mc});var Sw=M(Xu=>{"use strict";Xu.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};Xu.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 Tw=M(Ku=>{"use strict";Ku.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};Ku.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 kw=M(Zu=>{"use strict";Zu.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};Zu.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 xw=M(Qu=>{"use strict";Qu.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};Qu.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 Rw=M(eh=>{"use strict";eh.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}`};eh.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 Nw=M((Iw,th)=>{var Ow=(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(p=>e.test(p),"isFormat"),encode(p,f,m){m=~~m,f=f||new Uint8Array(m+r);let _=p.length,w=0;for(let g=0;g<_;){let y=p.charCodeAt(g++);y===46?(f[m++]=w,w=0):w=w*10+(y-48)}return f[m]=w,f},decode(p,f){return f=~~f,`${p[f++]}.${p[f++]}.${p[f++]}.${p[f]}`}};t.v4=s;let o={name:"v6",size:i,isFormat:a(p=>p.length>0&&n.test(p),"isFormat"),encode(p,f,m){m=~~m;let _=m+i,w=-1,g=0,y=0,E=!0,S=!1;f=f||new Uint8Array(m+i);for(let k=0;k<p.length;k++){let $=p.charCodeAt(k);$===58?(E?w!==-1?(m<_&&(f[m]=0),m<_-1&&(f[m+1]=0),m+=2):m<_&&(w=m):(S===!0?(m<_&&(f[m]=y),m++):(m<_&&(f[m]=g>>8),m<_-1&&(f[m+1]=g&255),m+=2),g=0,y=0),E=!0,S=!1):$===46?(m<_&&(f[m]=y),m++,y=0,g=0,E=!1,S=!0):(E=!1,$>=97?$-=87:$>=65?$-=55:($-=48,y=y*10+$),g=(g<<4)+$)}if(E===!1)S===!0?(m<_&&(f[m]=y),m++):(m<_&&(f[m]=g>>8),m<_-1&&(f[m+1]=g&255),m+=2);else if(w===0)m<_&&(f[m]=0),m<_-1&&(f[m+1]=0),m+=2;else if(w!==-1){m+=2;for(let k=Math.min(m-1,_-1);k>=w+2;k--)f[k]=f[k-2];f[w]=0,f[w+1]=0,w=m}if(w!==m&&w!==-1)for(m>_-2&&(m=_-2);_>w;)f[--_]=m<_&&m>w?f[--m]:0;else for(;m<_;)f[m++]=0;return f},decode(p,f){f=~~f;let m="";for(let _=0;_<i;_+=2)_!==0&&(m+=":"),m+=(p[f+_]<<8|p[f+_+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(p){if(s.isFormat(p))return s.size;if(o.isFormat(p))return o.size;throw Error(`Invalid ip address: ${p}`)}a(l,"sizeOf");function d(p){return l(p)===s.size?1:2}a(d,"familyOf");function u(p,f,m){m=~~m;let _=l(p);return typeof f=="function"&&(f=f(m+_)),_===s.size?s.encode(p,f,m):o.encode(p,f,m)}a(u,"encode");function h(p,f,m){if(f=~~f,m=m||p.length-f,m===s.size)return s.decode(p,f,m);if(m===o.size)return o.decode(p,f,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 Ow}):typeof th=="object"&&typeof Iw=="object"&&(th.exports=Ow)});var Cw=M(R=>{"use strict";var O=W("buffer").Buffer,xr=Sw(),LO=Tw(),CO=kw(),gc=xw(),rh=Rw(),Bn=Nw(),PO=0,Aw=32768,nh=32768,DO=~nh,Lw=32768,$O=~Lw,T=R.name={};T.encode=function(t,e,r,{mail:n=!1}={}){e||(e=O.alloc(T.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,T.encode.bytes=r-i,e};T.encode.bytes=0;T.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 T.decode.bytes=o,n.length===0?".":n.join(".")};T.decode.bytes=0;T.encodingLength=function(t){return t==="."||t===".."?1:O.byteLength(t.replace(/^\.|\.$/gm,""))+2};var D={};D.encode=function(t,e,r){e||(e=O.alloc(D.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,D.encode.bytes=n+1,e};D.encode.bytes=0;D.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return D.decode.bytes=r+1,n};D.decode.bytes=0;D.encodingLength=function(t){return O.byteLength(t)+1};var yt={};yt.encode=function(t,e,r){e||(e=yt.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?Aw:PO;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};yt.encode.bytes=12;yt.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&Aw?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:CO.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:LO.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))}};yt.decode.bytes=12;yt.encodingLength=function(){return 12};var gr=R.unknown={};gr.encode=function(t,e,r){return e||(e=O.alloc(gr.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),gr.encode.bytes=t.length+2,e};gr.encode.bytes=0;gr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return gr.decode.bytes=r+2,n};gr.decode.bytes=0;gr.encodingLength=function(t){return t.length+2};var wr=R.ns={};wr.encode=function(t,e,r){return e||(e=O.alloc(wr.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),wr.encode.bytes=T.encode.bytes+2,e};wr.encode.bytes=0;wr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=T.decode(t,e+2);return wr.decode.bytes=r+2,n};wr.decode.bytes=0;wr.encodingLength=function(t){return T.encodingLength(t)+2};var yr=R.soa={};yr.encode=function(t,e,r){e||(e=O.alloc(yr.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mname,e,r),r+=T.encode.bytes,T.encode(t.rname,e,r,{mail:!0}),r+=T.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),yr.encode.bytes=r-n,e};yr.encode.bytes=0;yr.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=T.decode(t,e),e+=T.decode.bytes,n.rname=T.decode(t,e,{mail:!0}),e+=T.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,yr.decode.bytes=e-r,n};yr.decode.bytes=0;yr.encodingLength=function(t){return 22+T.encodingLength(t.mname)+T.encodingLength(t.rname)};var br=R.txt={};br.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]=O.from(t[i])),!O.isBuffer(t[i]))throw new Error("Must be a Buffer");e||(e=O.alloc(br.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),br.encode.bytes=r-n,e};br.encode.bytes=0;br.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 br.decode.bytes=e-r,i};br.decode.bytes=0;br.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=O.byteLength(r)+1:e+=r.length+1}),e};var vr=R.null={};vr.encode=function(t,e,r){e||(e=O.alloc(vr.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=O.from(t)),t||(t=O.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),vr.encode.bytes=r-n,e};vr.encode.bytes=0;vr.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,vr.decode.bytes=e-r,i};vr.decode.bytes=0;vr.encodingLength=function(t){return t?(O.isBuffer(t)?t.length:O.byteLength(t))+2:2};var Er=R.hinfo={};Er.encode=function(t,e,r){e||(e=O.alloc(Er.encodingLength(t))),r||(r=0);let n=r;return r+=2,D.encode(t.cpu,e,r),r+=D.encode.bytes,D.encode(t.os,e,r),r+=D.encode.bytes,e.writeUInt16BE(r-n-2,n),Er.encode.bytes=r-n,e};Er.encode.bytes=0;Er.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=D.decode(t,e),e+=D.decode.bytes,n.os=D.decode(t,e),e+=D.decode.bytes,Er.decode.bytes=e-r,n};Er.decode.bytes=0;Er.encodingLength=function(t){return D.encodingLength(t.cpu)+D.encodingLength(t.os)+2};var gt=R.ptr={},UO=R.cname=gt,jO=R.dname=gt;gt.encode=function(t,e,r){return e||(e=O.alloc(gt.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),gt.encode.bytes=T.encode.bytes+2,e};gt.encode.bytes=0;gt.decode=function(t,e){e||(e=0);let r=T.decode(t,e+2);return gt.decode.bytes=T.decode.bytes+2,r};gt.decode.bytes=0;gt.encodingLength=function(t){return T.encodingLength(t)+2};var Sr=R.srv={};Sr.encode=function(t,e,r){e||(e=O.alloc(Sr.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),T.encode(t.target,e,r+8);let n=T.encode.bytes+6;return e.writeUInt16BE(n,r),Sr.encode.bytes=n+2,e};Sr.encode.bytes=0;Sr.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=T.decode(t,e+8),Sr.decode.bytes=r+2,n};Sr.decode.bytes=0;Sr.encodingLength=function(t){return 8+T.encodingLength(t.target)};var ze=R.caa={};ze.ISSUER_CRITICAL=128;ze.encode=function(t,e,r){let n=ze.encodingLength(t);return e||(e=O.alloc(ze.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=ze.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,D.encode(t.tag,e,r),r+=D.encode.bytes,e.write(t.value,r),r+=O.byteLength(t.value),ze.encode.bytes=n,e};ze.encode.bytes=0;ze.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=D.decode(t,e),e+=D.decode.bytes,i.value=t.toString("utf-8",e,n+r),i.issuerCritical=!!(i.flags&ze.ISSUER_CRITICAL),ze.decode.bytes=r+2,i};ze.decode.bytes=0;ze.encodingLength=function(t){return D.encodingLength(t.tag)+D.encodingLength(t.value)+2};var Zr=R.mx={};Zr.encode=function(t,e,r){e||(e=O.alloc(Zr.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,T.encode(t.exchange,e,r),r+=T.encode.bytes,e.writeUInt16BE(r-n-2,n),Zr.encode.bytes=r-n,e};Zr.encode.bytes=0;Zr.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=T.decode(t,e),e+=T.decode.bytes,Zr.decode.bytes=e-r,n};Zr.encodingLength=function(t){return 4+T.encodingLength(t.exchange)};var Tr=R.a={};Tr.encode=function(t,e,r){return e||(e=O.alloc(Tr.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Bn.v4.encode(t,e,r),Tr.encode.bytes=6,e};Tr.encode.bytes=0;Tr.decode=function(t,e){e||(e=0),e+=2;let r=Bn.v4.decode(t,e);return Tr.decode.bytes=6,r};Tr.decode.bytes=0;Tr.encodingLength=function(){return 6};var kr=R.aaaa={};kr.encode=function(t,e,r){return e||(e=O.alloc(kr.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Bn.v6.encode(t,e,r),kr.encode.bytes=18,e};kr.encode.bytes=0;kr.decode=function(t,e){e||(e=0),e+=2;let r=Bn.v6.decode(t,e);return kr.decode.bytes=18,r};kr.decode.bytes=0;kr.encodingLength=function(){return 18};var $e=R.option={};$e.encode=function(t,e,r){e||(e=O.alloc($e.encodingLength(t))),r||(r=0);let n=r,i=rh.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||Bn.familyOf(t.ip),c=Bn.encode(t.ip,O.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 $e.encode.bytes=r-n,e};$e.encode.bytes=0;$e.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=rh.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=O.alloc(r.family===1?4:16);t.copy(i,0,e,e+n-4),r.ip=Bn.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 $e.decode.bytes=n+4,r};$e.decode.bytes=0;$e.encodingLength=function(t){if(t.data)return t.data.length+4;switch(rh.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 He=R.opt={};He.encode=function(t,e,r){e||(e=O.alloc(He.encodingLength(t))),r||(r=0);let n=r,i=zi(t,$e);return e.writeUInt16BE(i,r),r=io(t,$e,e,r+2),He.encode.bytes=r-n,e};He.encode.bytes=0;He.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++]=$e.decode(t,e),e+=$e.decode.bytes,i-=$e.decode.bytes;return He.decode.bytes=e-r,n};He.decode.bytes=0;He.encodingLength=function(t){return 2+zi(t||[],$e)};var Ie=R.dnskey={};Ie.PROTOCOL_DNSSEC=3;Ie.ZONE_KEY=128;Ie.SECURE_ENTRYPOINT=32768;Ie.encode=function(t,e,r){e||(e=O.alloc(Ie.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!O.isBuffer(i))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(Ie.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,Ie.encode.bytes=r-n,e.writeUInt16BE(Ie.encode.bytes-2,n),e};Ie.encode.bytes=0;Ie.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)!==Ie.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,Ie.decode.bytes=e-r,n};Ie.decode.bytes=0;Ie.encodingLength=function(t){return 6+O.byteLength(t.key)};var Ut=R.rrsig={};Ut.encode=function(t,e,r){e||(e=O.alloc(Ut.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!O.isBuffer(i))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(xr.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,T.encode(t.signersName,e,r),r+=T.encode.bytes,i.copy(e,r,0,i.length),r+=i.length,Ut.encode.bytes=r-n,e.writeUInt16BE(Ut.encode.bytes-2,n),e};Ut.encode.bytes=0;Ut.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.typeCovered=xr.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=T.decode(t,e),e+=T.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Ut.decode.bytes=e-r,n};Ut.decode.bytes=0;Ut.encodingLength=function(t){return 20+T.encodingLength(t.signersName)+O.byteLength(t.signature)};var jt=R.rp={};jt.encode=function(t,e,r){e||(e=O.alloc(jt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mbox||".",e,r,{mail:!0}),r+=T.encode.bytes,T.encode(t.txt||".",e,r),r+=T.encode.bytes,jt.encode.bytes=r-n,e.writeUInt16BE(jt.encode.bytes-2,n),e};jt.encode.bytes=0;jt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=T.decode(t,e,{mail:!0})||".",e+=T.decode.bytes,n.txt=T.decode(t,e)||".",e+=T.decode.bytes,jt.decode.bytes=e-r,n};jt.decode.bytes=0;jt.encodingLength=function(t){return 2+T.encodingLength(t.mbox||".")+T.encodingLength(t.txt||".")};var fe={};fe.encode=function(t,e,r){e||(e=O.alloc(fe.encodingLength(t))),r||(r=0);let n=r;for(var i=[],s=0;s<t.length;s++){var o=xr.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=O.from(i[s]);e.writeUInt8(s,r),r+=1,e.writeUInt8(c.length,r),r+=1,c.copy(e,r),r+=c.length}return fe.encode.bytes=r-n,e};fe.encode.bytes=0;fe.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=xr.toString(s<<8|c<<3|d);i.push(u)}e+=o}return fe.decode.bytes=e-n,i};fe.decode.bytes=0;fe.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=xr.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 Mt=R.nsec={};Mt.encode=function(t,e,r){e||(e=O.alloc(Mt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.nextDomain,e,r),r+=T.encode.bytes,fe.encode(t.rrtypes,e,r),r+=fe.encode.bytes,Mt.encode.bytes=r-n,e.writeUInt16BE(Mt.encode.bytes-2,n),e};Mt.encode.bytes=0;Mt.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.nextDomain=T.decode(t,e),e+=T.decode.bytes,n.rrtypes=fe.decode(t,e,i-(e-r)),e+=fe.decode.bytes,Mt.decode.bytes=e-r,n};Mt.decode.bytes=0;Mt.encodingLength=function(t){return 2+T.encodingLength(t.nextDomain)+fe.encodingLength(t.rrtypes)};var Bt=R.nsec3={};Bt.encode=function(t,e,r){e||(e=O.alloc(Bt.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!O.isBuffer(i))throw new Error("salt must be a Buffer");let s=t.nextDomain;if(!O.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,fe.encode(t.rrtypes,e,r),r+=fe.encode.bytes,Bt.encode.bytes=r-n,e.writeUInt16BE(Bt.encode.bytes-2,n),e};Bt.encode.bytes=0;Bt.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=fe.decode(t,e,i-(e-r)),e+=fe.decode.bytes,Bt.decode.bytes=e-r,n};Bt.decode.bytes=0;Bt.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+fe.encodingLength(t.rrtypes)};var Ft=R.ds={};Ft.encode=function(t,e,r){e||(e=O.alloc(Ft.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!O.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,Ft.encode.bytes=r-n,e.writeUInt16BE(Ft.encode.bytes-2,n),e};Ft.encode.bytes=0;Ft.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,Ft.decode.bytes=e-r,n};Ft.decode.bytes=0;Ft.encodingLength=function(t){return 6+O.byteLength(t.digest)};var We=R.sshfp={};We.getFingerprintLengthForHashType=a(function(e){switch(e){case 1:return 20;case 2:return 32}},"getFingerprintLengthForHashType");We.encode=a(function(e,r,n){r||(r=O.alloc(We.encodingLength(e))),n||(n=0);let i=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let s=O.from(e.fingerprint.toUpperCase(),"hex");if(s.length!==We.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return s.copy(r,n),n+=s.byteLength,We.encode.bytes=n-i,r.writeUInt16BE(We.encode.bytes-2,i),r},"encode");We.encode.bytes=0;We.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=We.getFingerprintLengthForHashType(i.hash);return i.fingerprint=e.slice(r,r+s).toString("hex").toUpperCase(),r+=s,We.decode.bytes=r-n,i},"decode");We.decode.bytes=0;We.encodingLength=function(t){return 4+O.from(t.fingerprint,"hex").byteLength};var qt=R.naptr={};qt.encode=function(t,e,r){e||(e=O.alloc(qt.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,D.encode(t.flags,e,r),r+=D.encode.bytes,D.encode(t.services,e,r),r+=D.encode.bytes,D.encode(t.regexp,e,r),r+=D.encode.bytes,T.encode(t.replacement,e,r),r+=T.encode.bytes,qt.encode.bytes=r-n,e.writeUInt16BE(qt.encode.bytes-2,n),e};qt.encode.bytes=0;qt.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=D.decode(t,e),e+=D.decode.bytes,n.services=D.decode(t,e),e+=D.decode.bytes,n.regexp=D.decode(t,e),e+=D.decode.bytes,n.replacement=T.decode(t,e),e+=T.decode.bytes,qt.decode.bytes=e-r,n};qt.decode.bytes=0;qt.encodingLength=function(t){return D.encodingLength(t.flags)+D.encodingLength(t.services)+D.encodingLength(t.regexp)+T.encodingLength(t.replacement)+6};var zt=R.tlsa={};zt.encode=function(t,e,r){e||(e=O.alloc(zt.encodingLength(t))),r||(r=0);let n=r,i=t.certificate;if(!O.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,zt.encode.bytes=r-n,e.writeUInt16BE(zt.encode.bytes-2,n),e};zt.encode.bytes=0;zt.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,zt.decode.bytes=e-r,n};zt.decode.bytes=0;zt.encodingLength=function(t){return 5+O.byteLength(t.certificate)};var ih=R.record=function(t){switch(t.toUpperCase()){case"A":return Tr;case"PTR":return gt;case"CNAME":return UO;case"DNAME":return jO;case"TXT":return br;case"NULL":return vr;case"AAAA":return kr;case"SRV":return Sr;case"HINFO":return Er;case"CAA":return ze;case"NS":return wr;case"SOA":return yr;case"MX":return Zr;case"OPT":return He;case"DNSKEY":return Ie;case"RRSIG":return Ut;case"RP":return jt;case"NSEC":return Mt;case"NSEC3":return Bt;case"SSHFP":return We;case"DS":return Ft;case"NAPTR":return qt;case"TLSA":return zt}return gr},_e=R.answer={};_e.encode=function(t,e,r){e||(e=O.alloc(_e.encodingLength(t))),r||(r=0);let n=r;if(T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(xr.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,He.encode(t.options||[],e,r),r+=He.encode.bytes}else{let i=gc.toClass(t.class===void 0?"IN":t.class);t.flush&&(i|=nh),e.writeUInt16BE(i,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let s=ih(t.type);s.encode(t.data,e,r),r+=s.encode.bytes}return _e.encode.bytes=r-n,e};_e.encode.bytes=0;_e.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=T.decode(t,e),e+=T.decode.bytes,r.type=xr.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=He.decode(t,e+8),e+=8+He.decode.bytes;else{let i=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=gc.toString(i&DO),r.flush=!!(i&nh);let s=ih(r.type);r.data=s.decode(t,e+8),e+=8+s.decode.bytes}return _e.decode.bytes=e-n,r};_e.decode.bytes=0;_e.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return T.encodingLength(t.name)+8+ih(t.type).encodingLength(e)};var wt=R.question={};wt.encode=function(t,e,r){e||(e=O.alloc(wt.encodingLength(t))),r||(r=0);let n=r;return T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(xr.toType(t.type),r),r+=2,e.writeUInt16BE(gc.toClass(t.class===void 0?"IN":t.class),r),r+=2,wt.encode.bytes=r-n,t};wt.encode.bytes=0;wt.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=T.decode(t,e),e+=T.decode.bytes,n.type=xr.toString(t.readUInt16BE(e)),e+=2,n.class=gc.toString(t.readUInt16BE(e)),e+=2,n.class&Lw&&(n.class&=$O),wt.decode.bytes=e-r,n};wt.decode.bytes=0;wt.encodingLength=function(t){return T.encodingLength(t.name)+4};R.AUTHORITATIVE_ANSWER=1024;R.TRUNCATED_RESPONSE=512;R.RECURSION_DESIRED=256;R.RECURSION_AVAILABLE=128;R.AUTHENTIC_DATA=32;R.CHECKING_DISABLED=16;R.DNSSEC_OK=32768;R.encode=function(t,e,r){let n=!e;n&&(e=O.alloc(R.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=[]),yt.encode(t,e,r),r+=yt.encode.bytes,r=io(t.questions,wt,e,r),r=io(t.answers,_e,e,r),r=io(t.authorities,_e,e,r),r=io(t.additionals,_e,e,r),R.encode.bytes=r-i,n&&R.encode.bytes!==e.length?e.slice(0,R.encode.bytes):e};R.encode.bytes=0;R.decode=function(t,e){e||(e=0);let r=e,n=yt.decode(t,e);return e+=yt.decode.bytes,e=_c(n.questions,wt,t,e),e=_c(n.answers,_e,t,e),e=_c(n.authorities,_e,t,e),e=_c(n.additionals,_e,t,e),R.decode.bytes=e-r,n};R.decode.bytes=0;R.encodingLength=function(t){return yt.encodingLength(t)+zi(t.questions||[],wt)+zi(t.answers||[],_e)+zi(t.authorities||[],_e)+zi(t.additionals||[],_e)};R.streamEncode=function(t){let e=R.encode(t),r=O.alloc(2);r.writeUInt16BE(e.byteLength);let n=O.concat([r,e]);return R.streamEncode.bytes=n.byteLength,n};R.streamEncode.bytes=0;R.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=R.decode(t.slice(2));return R.streamDecode.bytes=R.decode.bytes,r};R.streamDecode.bytes=0;function zi(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}a(zi,"encodingLengthList");function io(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(io,"encodeList");function _c(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(_c,"decodeList")});var $w=M((xF,Dw)=>{"use strict";var Pw=WO;process.nextTick(zO,42);Dw.exports=MO;function MO(t){var e=n;return r;function r(i){e(i||FO)}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=BO(l)?n:u;s.length;)u(s.shift());function u(h){Pw(qO,h,d)}a(u,"finished")}a(c,"done")}}a(MO,"thunky");function BO(t){return Object.prototype.toString.call(t)==="[object Error]"}a(BO,"isError");function FO(){}a(FO,"noop");function qO(t,e){t.apply(null,e)}a(qO,"apply");function zO(t){t===42&&(Pw=process.nextTick)}a(zO,"upgrade");function WO(t,e,r){process.nextTick(function(){t(e,r)})}a(WO,"nextTickArgs")});var Mw=M((OF,jw)=>{var sh=Cw(),HO=W("dgram"),GO=$w(),JO=W("events"),ah=W("os"),oh=a(function(){},"noop");jw.exports=function(t){t||(t={});var e=new JO.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||HO.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,p){try{h=sh.decode(h)}catch(f){e.emit("warning",f);return}e.emit("packet",h,p),h.type==="query"&&e.emit("query",h,p),h.type==="response"&&e.emit("response",h,p)}),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=GO(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,p,f){if(typeof p=="function")return e.send(h,null,p);f||(f=oh),p?!p.host&&!p.address&&(p.address=s.address):p=s,u(m);function m(_){if(c)return f();if(_)return f(_);var w=sh.encode(h);d.send(w,0,w.length,p.port,p.address||p.host,f)}a(m,"onbind")},e.response=e.respond=function(h,p,f){Array.isArray(h)&&(h={answers:h}),h.type="response",h.flags=(h.flags||0)|sh.AUTHORITATIVE_ANSWER,e.send(h,p,f)},e.query=function(h,p,f,m){if(typeof p=="function")return e.query(h,null,null,p);if(typeof p=="object"&&p&&p.port)return e.query(h,null,p,f);if(typeof f=="function")return e.query(h,p,null,f);m||(m=oh),typeof h=="string"&&(h=[{name:h,type:p||"ANY"}]),Array.isArray(h)&&(h={type:"query",questions:h}),h.type="query",e.send(h,f,m)},e.destroy=function(h){if(h||(h=oh),c)return process.nextTick(h);c=!0,clearInterval(l);for(var p in o)try{d.dropMembership(i,p)}catch{}o={},d.close(h)},e.update=function(){for(var h=t.interface?[].concat(t.interface):YO(),p=!1,f=0;f<h.length;f++){var m=h[f];if(!o[m])try{d.addMembership(i,m),o[m]=!0,p=!0}catch(_){e.emit("warning",_)}}if(p){if(d.setMulticastInterface)try{d.setMulticastInterface(t.interface||VO())}catch(_){e.emit("warning",_)}e.emit("networkInterface")}},e};function VO(){for(var t=ah.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(Uw(s.family)&&!s.internal)return ah.platform()==="darwin"&&e[r]==="en0"?s.address:"0.0.0.0"}return"127.0.0.1"}a(VO,"defaultInterface");function YO(){for(var t=ah.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(Uw(o.family)){r.push(o.address);break}}return r}a(YO,"allInterfaces");function Uw(t){return t===4||t==="IPv4"}a(Uw,"isIPv4")});var Fw=M((NF,Bw)=>{"use strict";Bw.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 qw=M(Fn=>{"use strict";var ch=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Server=void 0;var XO=ch(Mw()),KO=ch(Fw()),ZO=ch(hc()),wc=class{static{a(this,"Server")}constructor(e,r){this.registry={},this.mdns=(0,XO.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,ZO.default)(i,e)}):[]}isDuplicateRecord(e){return r=>e.type===r.type&&e.name===r.name&&(0,KO.default)(e.data,r.data)}unique(){var e=[];return r=>~e.indexOf(r)?!1:(e.push(r),!0)}};Fn.Server=wc;Fn.default=wc});var zw=M(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});lh.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 Ww=M(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});dh.default=t=>Object.keys(t).filter(e=>!e.includes("binary")).reduce((e,r)=>Object.assign(e,{[r]:t[r]}),{})});var Hw=M(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});uh.default=QO;function QO(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(QO,"equalTxt")});var Vw=M(qn=>{"use strict";var so=qn&&qn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qn,"__esModule",{value:!0});qn.Browser=void 0;var eI=so(Gu()),Qr=so(hc()),tI=W("events"),hh=Ju(),Gw=so(zw()),rI=so(Ww()),nI=so(Hw()),Jw=".local",iI="_services._dns-sd._udp"+Jw,yc=class t extends tI.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 eI.default(r!==null&&r.txt!=null?r.txt:void 0),r===null||r.type===void 0?(this.name=iI,this.wildcard=!0):(this.name=(0,hh.toString)({name:r.type,protocol:r.protocol||"tcp"})+Jw,r.name&&(this.name=r.name+"."+this.name),this.wildcard=!1),r!=null&&r.txt!==void 0&&(this.txtQuery=(0,rI.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,Qr.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,Gw.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,nI.default)(r.txt,e?.txt||{})){if(!(0,Gw.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,Qr.default)(r.fqdn,e.fqdn)?e:r)}removeService(e){var r,n;this._services.some(function(i,s){if((0,Qr.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,Qr.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,Qr.default)(c.name,e)).map(c=>{let l={addresses:[],subtypes:[],ttl:c.ttl,lastSeen:s};if(o.filter(d=>d.type==="PTR"&&(0,Qr.default)(d.data,c.data)&&d.name.includes("._sub")).forEach(d=>{let u=(0,hh.toType)(d.name);l.subtypes.push(u.subtype)}),o.filter(d=>(d.type==="SRV"||d.type==="TXT")&&(0,Qr.default)(d.name,c.data)).forEach(d=>{if(d.type==="SRV"){var u=d.name.split("."),h=u[0],p=(0,hh.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=p.name,l.protocol=p.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,Qr.default)(d.name,l.host)).forEach(d=>l.addresses.push(d.data)),l}).filter(c=>!!c)}};qn.Browser=yc;qn.default=yc});var mh=M(Rr=>{"use strict";var bc=Rr&&Rr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.Browser=Rr.Service=void 0;var sI=bc(Ew()),oI=bc(qw()),ph=bc(Vw());Rr.Browser=ph.default;var aI=bc(Vu());Rr.Service=aI.default;var fh=class{static{a(this,"Bonjour")}constructor(e={},r){this.server=new oI.default(e,r),this.registry=new sI.default(this.server)}publish(e){return this.registry.publish(e)}unpublishAll(e){return this.registry.unpublishAll(e)}find(e=null,r){return new ph.default(this.server.mdns,e,r)}findOne(e=null,r=1e4,n){let i=new ph.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)}};Rr.default=fh});var Yw=M((Or,Wi)=>{"use strict";var cI=Or&&Or.__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]})),lI=Or&&Or.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dI=Or&&Or.__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"&&cI(r,e,n[i]);return lI(r,e),r}})(),uI=Or&&Or.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},hI=uI(mh()),vc=dI(mh()),Wt=class extends hI.default{static{a(this,"Bonjour")}},pI=Wt;(function(t){t.Bonjour=pI,t.Service=vc.Service,t.Browser=vc.Browser})(Wt||(Wt={}));Object.defineProperty(Wt,"default",{enumerable:!0,value:Wt});Wi.exports.Bonjour=Wt;Wi.exports.Service=vc.Service;Wi.exports.Browser=vc.Browser;Wi.exports.default=Wt;Wi.exports=Wt});import{isIP as fI}from"node:net";function Ec(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(()=>p(n.reason instanceof Error?n.reason:new Error("Discovery cancelled"))),"abort");n?.addEventListener("abort",h,{once:!0});try{u=(e.createBonjour||(m=>new Xw.Bonjour(void 0,m)))(()=>queueMicrotask(()=>p())),l=u.find({type:mI,protocol:"tcp"}),l.on("up",m=>{if(!(c||_I(m.txt?.node_id)!==t||!gI(m.port)))for(let _ of m.addresses||[])Ss(_)&&o.add(`http://${wI(_)}:${Number(m.port)}`)}),l.on("error",()=>p()),d=setTimeout(()=>p(),r),d.unref?.(),n?.aborted&&h()}catch(f){p(f)}function p(f){if(c)return;c=!0,clearTimeout(d),n?.removeEventListener("abort",h);let m=a(()=>{let _=f||(n?.aborted?n.reason||new Error("Discovery cancelled"):null);_?s(_):i([...o])},"complete");try{l?.stop()}catch(_){f||=_}try{u?u.destroy(m):m()}catch(_){f||=_,m()}}a(p,"finish")})}function _I(t){return Buffer.isBuffer(t)?t.toString("utf8"):typeof t=="string"?t:""}function gI(t){let e=Number(t);return Number.isInteger(e)&&e>=1&&e<=65535}function wI(t){return fI(t)===6?`[${t}]`:t}var Xw,mI,_h=v(()=>{Xw=nr(Yw(),1);yd();mI="interscale-data";a(Ec,"discoverTransferCandidates");a(_I,"txtValue");a(gI,"validPort");a(wI,"formatHost")});function yI(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 zn(t){let e=yI(t);return Object.assign(new Error(e.message),e,{terminal:!0})}function gh(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 Kw=v(()=>{a(yI,"downloadFailure");a(zn,"failedDownloadError");a(gh,"localDownloadFailure")});import*as oo from"node:path";import{stat as Qw,statfs as bI,realpath as ey}from"node:fs/promises";async function Sc(t,e={stat:Qw,realpath:ey}){let r=oo.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=oo.dirname(r);if(i===r)throw n;r=i}}async function Tc({stagingPath:t,destinationPath:e,size:r,reserve:n=1024**3,directory:i=!1,staged:s=!1,movable:o=!1},c={stat:Qw,realpath:ey,statfs:bI}){if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(n)||n<0)throw Zw("invalid_transfer_size","Transfer size and reserve must be nonnegative safe integers");let[l,d]=await Promise.all([Sc(t,c),Sc(oo.dirname(e),c)]),u=new Map;for(let[h,p]of[[l,s?0n:BigInt(r)],[d,BigInt(r)*(i?2n:1n)]]){if(s&&h===l)continue;let f=String(h.metadata.dev),m=u.get(f);u.set(f,{path:h.path,required:(m?.required||BigInt(n))+(o&&m?0n:p)})}for(let h of u.values()){let p=await c.statfs(h.path,{bigint:!0}),f=BigInt(p.bavail)*BigInt(p.bsize);if(f<h.required)throw Zw("insufficient_space",`Insufficient storage on ${h.path}: ${f} bytes available, ${h.required} required`)}}function Zw(t,e){return Object.assign(new Error(e),{code:t})}var wh=v(()=>{a(Sc,"existingAncestor");a(Tc,"checkTransferSpace");a(Zw,"failure")});import{constants as ty,createReadStream as vI}from"node:fs";import{copyFile as EI,link as SI,mkdir as TI,open as yh,rename as kc,rm as bh,stat as ny}from"node:fs/promises";import{basename as kI,dirname as ry,join as xI}from"node:path";import{createHash as RI,randomUUID as OI}from"node:crypto";async function iy(t,e,{overwrite:r=!1,move:n=!1,sha256:i,onStaged:s,onPublished:o,minimumFreeBytes:c=1024**3,signal:l}={}){l?.throwIfAborted();let d=ry(e),u=await ny(t),h=a(()=>Tc({stagingPath:ry(t),destinationPath:e,size:u.size,reserve:c,staged:!0}),"checkSpace");n||await h(),await TI(d,{recursive:!0,mode:448});let p=xI(d,`.${kI(e).slice(0,60)}.interscale-${OI()}.part`),f=!1,m=!1;try{if(l?.throwIfAborted(),n)try{await kc(t,p),f=!0}catch(w){if(w.code!=="EXDEV")throw w;await h()}if(!f&&(await EI(t,p,ty.COPYFILE_EXCL|ty.COPYFILE_FICLONE),l?.throwIfAborted(),i)){let w=RI("sha256");for await(let g of vI(p,{signal:l}))w.update(g);if(w.digest("hex")!==i)throw Object.assign(new Error("Staged destination failed SHA-256 verification"),{code:"publication_hash_mismatch"})}let _=await yh(p,"r+");try{await _.sync()}finally{await _.close()}if(await s?.(p),l?.throwIfAborted(),r?await kc(p,e):await II(p,e),m=!0,process.platform!=="win32"){let w=await yh(d,"r");try{await w.sync()}catch(g){if(!["EINVAL","ENOTSUP"].includes(g.code))throw g}finally{await w.close()}}await o?.()}finally{f&&!m?await kc(p,t).catch(()=>bh(p,{force:!0})):await bh(p,{force:!0})}}async function II(t,e,{linkFile:r=SI}={}){try{await r(t,e);return}catch(s){if(s.code==="EEXIST")throw s}let n=await yh(e,"wx"),i=await n.stat().finally(()=>n.close());try{await kc(t,e)}catch(s){let o=await ny(e).catch(()=>null);throw o&&o.ino===i.ino&&o.size===0&&await bh(e,{force:!0}),s}}var sy=v(()=>{wh();a(iy,"publishFile");a(II,"claimCreateOnly")});function Ee(t){return JSON.stringify(vh(t))}function vh(t){return Array.isArray(t)?t.map(vh):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,vh(t[e])])):t}var Hi=v(()=>{a(Ee,"canonicalJson");a(vh,"canonical")});import{rm as NI}from"node:fs/promises";import{setTimeout as Eh}from"node:timers/promises";async function AI(t,e,r,n={}){if(e.published)return xc(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 p=(await t.request(`/v1/downloads/${encodeURIComponent(e.id)}`,{signal:c})).download;throw zn(d.error||p)}if(d.source_relay_support==="upgrade_required")throw Object.assign(new G("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 G("download_stopped",`Relay download is ${d.state}; inspect its outcome`);await Eh(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=ro(d.manifest),h=await Wu(e,u,r,{...n,signal:c,route:"r2",concurrency:4,fetchChunk:a(async({index:p,expectedBytes:f,signal:m})=>{for(let _=0;_<2;_++){let w=await t.request(`${l}/read-plan`,{method:"POST",signal:m,json:{token:e.token,relay_id:d.relay_id,indices:[p]}}),g=w.chunks?.[0];if(w.download_id!==e.id||w.relay_id!==d.relay_id||Ee(w.manifest)!==Ee(d.manifest)||w.chunks?.length!==1||g?.index!==p||g.encrypted_size!==f||typeof g.url!="string")throw new G("invalid_relay_read_plan","Relay read plan does not match the retained download");let y=await mr(g.url,{signal:m,maxResponseBytes:f});if(!([401,403].includes(y.status)&&_===0)){if(!y.ok)throw new G("relay_chunk_unavailable",`Relay chunk ${p} returned HTTP ${y.status}`);return Buffer.from(await y.arrayBuffer())}}},"fetchChunk")});return await oy(h,u,{...n,signal:c}),r.markPublished(h.id),h=r.get(h.id),await xc(t,h,r,null,c,"r2")}catch(d){throw s.signal.aborted&&!n.signal?.aborted?Object.assign(new G("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."}):gh(d)}finally{clearTimeout(o)}}async function co(t,e,r,n,i={}){if(ao(i.signal),e.published)return xc(t,e,n,null,i.signal);let s=new Set,o,c=a(async p=>{for(let f of await uc(Ti(p),{nodeId:e.download.target_node_id,id:e.id,token:e.token,kind:"downloads",signal:i.signal})){let m=f.url,_=`${m}|${f.localAddress||""}`;if(s.has(_))continue;s.add(_);let w={...i,localAddress:f.localAddress};try{i.onLinkAttempt?.(f);let g=await LI(t,m,e.id,e.token,w);try{return await CI(t,m,e,g,n,w)}catch(y){throw gh(y)}}catch(g){if(dc(e.download.target_node_id,f),g.terminal||cy(g,i.signal))throw g;o=g}}return null},"tryCandidates"),l=await c(r);if(l)return l;let d=await Ec(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 zn(h);if(h?.r2_available??e.download.r2_available)return i.onFallback?.({route:"r2",reason:o?.message||"No direct route"}),AI(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 LI(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;){ao(i.signal);try{let u=await mr(`${s}${o}`,{headers:{authorization:ay(n,r,"GET",o)},signal:ly(i.signal,Number(i.connectTimeoutMs||2e3)),maxResponseBytes:65536,localAddress:i.localAddress});if(u.ok){let h=await u.json();if(h.state==="ready")return ro(h);if(h.state==="failed")throw zn(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 zn(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||cy(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 zn(h)}if(l+=1,l>=3)throw u}await Eh(250,void 0,{signal:i.signal})}throw new Error("Timed out while the agent prepared the job result")}async function CI(t,e,r,n,i,s){let o=await Wu(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 mr(`${e.replace(/\/$/,"")}${u}`,{headers:{authorization:ay(r.token,r.id,"GET",u)},signal:ly(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 oy(o,n,s),i.markPublished(o.id),o=i.get(o.id),xc(t,o,i,e,s.signal)}async function oy(t,e,r){if(ao(r.signal),e.kind==="directory-tar"){await Gg(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 iy(t.part_path,t.output_path,{overwrite:!!r.overwrite,sha256:e.sha256,signal:r.signal})}async function xc(t,e,r,n=null,i,s="direct"){let o=Date.now()+1e4;for(;Date.now()<o;){ao(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 zn(l);await Eh(100,void 0,{signal:i})}ao(i);let c=await t.request(`/v1/downloads/${encodeURIComponent(e.id)}/complete`,{method:"POST",json:{},signal:i});return r.complete(e.id),await NI(e.part_path,{force:!0}),{download:c.download,route:s,candidate:n,output:e.output_path}}function ay(t,e,r,n){return`Interscale ${$n(t,e,r,n)}`}function ao(t){if(!t?.aborted)return;let e=t.reason instanceof Error?t.reason:new Error("Download interrupted");throw e.code||="download_interrupted",e}function cy(t,e){return!!e?.aborted||t?.code==="download_interrupted"||t?.name==="AbortError"}function ly(t,e){let r=AbortSignal.timeout(Math.max(1,e));return t?AbortSignal.any([t,r]):r}var Sh=v(()=>{ju();mw();Bi();rc();_h();ks();lc();Kw();sy();Fu();Hi();ye();a(AI,"receiveRelayDownload");a(co,"receiveDownload");a(LI,"waitForManifest");a(CI,"receiveFromCandidate");a(oy,"publishResult");a(xc,"finishPublishedDownload");a(ay,"authorization");a(ao,"throwIfAborted");a(cy,"isInterrupted");a(ly,"combinedSignal")});function Th(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 Rc(t){return Th({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 dy,Oc=v(()=>{dy={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(Th,"validateJobOutputs");a(Rc,"normalizeJobOutputs")});function hy(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=Rc(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 uy,py=v(()=>{Oc();uy="jobs.inputs.v1";a(hy,"validateJobInputs")});import{existsSync as PI,mkdirSync as DI,readFileSync as kh,rmSync as fy,statSync as $I,writeFileSync as UI}from"node:fs";import{uptime as jI}from"node:os";import{dirname as MI}from"node:path";import{randomUUID as BI}from"node:crypto";function ge(t){DI(MI(t),{recursive:!0,mode:448});let e=JSON.stringify({pid:process.pid,nonce:BI()});for(let r=0;r<2;r++)try{UI(t,e,{flag:"wx",mode:384});break}catch(n){if(n.code!=="EEXIST")throw n;let i=kh(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&&$I(t).mtimeMs<Date.now()-jI()*1e3-2e3&&(o=!1),o||r)throw Object.assign(new Error("Another updater is already running"),{code:"update_in_progress"});kh(t,"utf8")===i&&fy(t)}return()=>{PI(t)&&kh(t,"utf8")===e&&fy(t)}}var Wn=v(()=>{a(ge,"acquireProcessLock")});var gy={};K(gy,{collectRunResults:()=>lo,prepareRunFiles:()=>GI});import{existsSync as FI}from"node:fs";import{createHash as qI}from"node:crypto";import{lstat as zI,rm as my}from"node:fs/promises";import{dirname as WI,join as HI,resolve as _y}from"node:path";async function GI(t,e,r,n){if(!Array.isArray(n.inputs)||n.inputs.length>100)throw Hn("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 Hn("Each input needs a local source and relative destination path");return{source:_y(u.source),path:u.path,...u.include_ignored?{include_ignored:!0}:{}}});for(let u of i)if(!FI(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"});hy({type:"exec",inputs:i.map(u=>({path:u.path,transfer_id:"transfer_validation",sha256:"0".repeat(64),kind:"file"}))}),Th({type:"exec",outputs:n.outputs});let{node:s}=await t.node(e);if(!s.capabilities?.protocol_features?.includes(uy))throw Hn("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=ge(HI(WI(n.transferStatePath||ys()),"run-locks",`${xh("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 Pn(n.transferStatePath);for(let[u,h]of i.entries()){n.signal?.throwIfAborted();let p=xh("input",t.serverUrl,n.idempotencyKey,u),f=l.requestRecord(p),m,_=!1;try{let w=f?.input.executable??!!((await zI(h.source)).mode&73),g=h.include_ignored!==!0;f||(m=await Mi(h.source,{json:!0,signal:n.signal,stagingDirectory:n.stagingDirectory,gitignore:g}));let y=f?.input.kind||m.kind;l.prepareRequest({serverUrl:t.serverUrl,requestId:p,input:{contract:o,kind:y,executable:w}});let E;if(f?.transfer_id){let k=l.get(f.transfer_id);E=await t.resumeCopy(k.source_path,k.id,k.token,{signal:n.signal})}else{m||=await Mi(h.source,{json:!0,signal:n.signal,stagingDirectory:n.stagingDirectory,gitignore:g});let k=m.sha256||await Kr(m.path,{signal:n.signal}),$=`.run-inputs/${k}`;E=await t.copyFile(m.path,s.id,$,{kind:"file",sourceName:k,requestId:p,signal:n.signal,onCreated:a(({transfer:q,token:V})=>{l.save({serverUrl:t.serverUrl,requestId:p,transfer:q,token:V,sourcePath:m.path,target:s.id,destinationPath:$,temporary:!0}),_=!0},"onCreated")})}if(E.transfer.state!=="completed")throw Hn("Input transfer has not completed");let S=l.get(E.transfer.id);d.push({transfer_id:S.id,path:h.path,kind:y,executable:w,sha256:S.transfer.sha256}),l.complete(S.id),await my(S.source_path,{force:!0})}finally{m&&!_&&await my(m.path,{force:!0})}}return d}finally{l?.close(),c()}}async function lo(t,e,r,n={}){if(e.state!=="succeeded")return[];if(typeof r!="string"||!r.length)throw Hn("Provide a local result directory");if(!Array.isArray(e.payload.task.outputs))throw Hn("Declare outputs before requesting local result collection");let i=Rc(e.payload.task.outputs),s=new Dn(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 Hn(`No verified output was registered for ${c.path}`)}let d=_y(r,...c.path.split("/")),u=xh("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),p,f;if(h?.download_id)p=s.get(h.download_id),f=(await t.resumeDownload(p.id,p.token)).direct_candidates;else{let _=await t.createArtifactDownload(l.artifact_id,{requestId:u});p=s.saveCreated({serverUrl:t.serverUrl,token:_.token,jobId:e.id,relativePath:l.relative_path,outputPath:d,download:_.download,requestId:u}),f=_.direct_candidates}if(await co(t,p,f,s,{signal:n.signal}),await Kr(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:p.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 xh(t,...e){return`run-${t}-${qI("sha256").update(JSON.stringify(e)).digest("hex")}`}function Hn(t){return Object.assign(new Error(t),{code:"invalid_run_files"})}var Ic=v(()=>{Du();cc();Sh();Qs();Oc();py();Wn();Z();a(GI,"prepareRunFiles");a(lo,"collectRunResults");a(xh,"requestKey");a(Hn,"invalid")});async function Gi(t,e,r,{signals:n=process}={}){let i=new AbortController,s,o=a(d=>{s||(s=Object.assign(new G("follow_interrupted",`Stopped waiting for ${e}; remote work may still be running`),{exitCode:d==="SIGINT"?130:143,next_action:`Inspect ${e} before retrying or use its explicit cancellation command.`}),i.abort(s))},"interrupt"),c=a(()=>o("SIGINT"),"onInt"),l=a(()=>o("SIGTERM"),"onTerm");n.on("SIGINT",c),n.on("SIGTERM",l);try{let d=await r(i.signal);return i.signal.throwIfAborted(),d}catch(d){throw s||d}finally{n.removeListener("SIGINT",c),n.removeListener("SIGTERM",l),t.close()}}var wy=v(()=>{ye();a(Gi,"followWithSignals")});import{randomBytes as JI,scrypt as VI,timingSafeEqual as Kq}from"node:crypto";import{promisify as YI}from"node:util";async function Rh(t,{account:e=!1}={}){ZI(t);let r=JI(16),n=await XI(t,r,32,{...KI,p:e?3:1});return`scrypt-v${e?2:1}:${r.toString("hex")}:${n.toString("hex")}`}function ZI(t){if(typeof t!="string"||t.length<12||Buffer.byteLength(t)>1024)throw new Error("Fleet password must contain at least 12 characters and at most 1024 bytes")}var XI,KI,yy=v(()=>{XI=YI(VI),KI={N:32768,r:8,p:1,maxmem:64*1024*1024};a(Rh,"hashJoinPassword");a(ZI,"validatePassword")});import{spawnSync as by}from"node:child_process";function Ge(t,e=process.platform){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e==="win32"?by("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter 'ProcessId=${t}').CommandLine`],{encoding:"utf8",windowsHide:!0,timeout:15e3}):by("ps",["-p",String(t),"-o","command="],{encoding:"utf8",timeout:5e3});return(r.status===0?String(r.stdout||"").trim():"")||null}var Gn=v(()=>{a(Ge,"processCommandLine")});import{createHash as QI}from"node:crypto";import{join as Nc,resolve as eN}from"node:path";function vy(t=x(),e=process.platform){let r=Nc(eN(t),"graphical-worker"),n=e==="win32"?`\\\\.\\pipe\\interscale-desktop-${QI("sha256").update(r.toLowerCase()).digest("hex").slice(0,32)}`:Nc(r,"control.sock");return{directory:r,socket:n,token:Nc(r,"channel-token"),lock:Nc(r,"worker.lock")}}var Ey=v(()=>{Z();a(vy,"graphicalWorkerPaths")});import{spawnSync as tN}from"node:child_process";function Ji({domain:t,label:e,plist:r,execute:n=tN,wrap:i=a(c=>c,"wrap"),sleep:s=rN,timeoutMs:o=1e4}={}){let c=a((u,h={})=>n("/bin/launchctl",i(u),{encoding:"utf8",timeout:3e4,...h}),"launchctl"),l=a(()=>c(["print",`${t}/${e}`],{stdio:"ignore"}).status===0,"loaded");c(["bootout",`${t}/${e}`],{stdio:"ignore"});for(let u=0;l()&&u<o;u+=250)s(250);let d;for(let u=0;u<5&&(d=c(["bootstrap",t,r]),d.status!==0);u++)s(1e3);if(d.status!==0&&!l()){let u=String(d.stderr||d.stdout||"").trim().split(`
|
|
106
|
+
`).at(-1);throw Object.assign(new Error(`launchctl could not load ${e}${u?`: ${u}`:""}`),{code:"launchd_bootstrap_failed"})}return c(["enable",`${t}/${e}`],{stdio:"ignore"}),{label:e,domain:t,plist:r}}var rN,Ac=v(()=>{rN=a(t=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t),"pause");a(Ji,"reloadLaunchJob")});import{existsSync as Ty,mkdirSync as ho,readFileSync as nN,readlinkSync as ky,rmSync as Oh,symlinkSync as iN,writeFileSync as Nh}from"node:fs";import{dirname as uo,join as Ne}from"node:path";import{homedir as xy}from"node:os";import{fileURLToPath as sN}from"node:url";import{spawnSync as Ry}from"node:child_process";function Oy(t=Ty){return[Sy,oN].find(e=>t(Ne(e,"Contents","MacOS","InterscaleGraphicalWorker")))||Sy}function Lc(t=process.platform){return t==="win32"?!1:t!=="darwin"||Ty(Ne(Oy(),"Contents","MacOS","InterscaleGraphicalWorker"))}async function po(t={}){let{env:e=process.env,platform:r=process.platform,execute:n=Ry,userHome:i=xy(),node:s=process.execPath}=t,o=x(e,r),c=L(e),l=t.entry||sN(new URL("../bin/interscale-graphical-worker.mjs",import.meta.url)),d=Ne(o,"logs","graphical-worker.log");ho(uo(d),{recursive:!0,mode:448});let u;if(r==="darwin"){if(!t.bundle&&!Lc(r))throw new Error("Install the complete signed macOS package to enable the graphical service");if(u=Ne(i,"Library","LaunchAgents",`${Vi}.plist`),ho(uo(u),{recursive:!0}),Nh(u,aN({bundle:t.bundle||Oy(),node:s,entry:l,root:o,config:c,log:d}),{mode:384}),n("/bin/launchctl",["print",`gui/${process.getuid()}`],{stdio:"ignore"}).status!==0)return n("/bin/launchctl",["bootout",`gui/${process.getuid()}/${Vi}`],{stdio:"ignore"}),{installed:!0,path:u,scope:"graphical_session",awaiting_login:!0};Ji({domain:`gui/${process.getuid()}`,label:Vi,plist:u,execute:n,...t.sleep?{sleep:t.sleep}:{}})}else if(r==="linux"){u=Ne(e.XDG_CONFIG_HOME||Ne(i,".config"),"systemd","user",Ht),ho(uo(u),{recursive:!0}),Nh(u,cN({node:s,entry:l,root:o,config:c}),{mode:384});let h=Ne(uo(u),"graphical-session.target.wants",Ht);ho(uo(h),{recursive:!0});try{iN(`../${Ht}`,h)}catch(p){if(p.code!=="EEXIST"||![`../${Ht}`,u].includes(ky(h)))throw p}if(n("systemctl",["--user","show-environment"],{stdio:"ignore",timeout:1e4}).status!==0)return{installed:!0,path:u,scope:"graphical_session",awaiting_login:!0};if(Ih(n,"systemctl",["--user","daemon-reload"]),e.DISPLAY||e.WAYLAND_DISPLAY||n("systemctl",["--user","is-active","--quiet","graphical-session.target"],{stdio:"ignore"}).status===0){let p=["DISPLAY","WAYLAND_DISPLAY","XAUTHORITY","XDG_CURRENT_DESKTOP","DBUS_SESSION_BUS_ADDRESS"].filter(f=>e[f]);p.length&&Ih(n,"systemctl",["--user","import-environment",...p]),Ih(n,"systemctl",["--user","restart",Ht])}}else throw new Error("Unsupported graphical service platform");return{installed:!0,path:u,scope:"graphical_session"}}async function Iy({platform:t=process.platform,env:e=process.env,execute:r=Ry,userHome:n=xy()}={}){if(t==="darwin")r("/bin/launchctl",["bootout",`gui/${process.getuid()}/${Vi}`],{stdio:"ignore"}),Oh(Ne(n,"Library","LaunchAgents",`${Vi}.plist`),{force:!0});else if(t==="linux"){r("systemctl",["--user","disable","--now",Ht],{stdio:"ignore"});let i=Ne(e.XDG_CONFIG_HOME||Ne(n,".config"),"systemd","user"),s=Ne(i,"graphical-session.target.wants",Ht);try{[`../${Ht}`,Ne(i,Ht)].includes(ky(s))&&Oh(s)}catch(o){if(o.code!=="ENOENT")throw o}Oh(Ne(i,Ht),{force:!0}),r("systemctl",["--user","daemon-reload"],{stdio:"ignore"})}else if(t==="win32"){let i=x(e,t);ho(i,{recursive:!0}),Nh(Ne(i,"graphical-worker-disabled"),`disabled
|
|
107
|
+
`),await lN(i),r("reg.exe",["delete","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run","/v","InterscaleGraphicalWorker","/f"],{stdio:"ignore"})}return{installed:!1}}function aN({bundle:t,node:e,entry:r,root:n,config:i,log:s}){let o=a(c=>String(c).replaceAll("&","&").replaceAll("<","<").replaceAll('"',"""),"e");return`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>
|
|
108
|
+
<key>Label</key><string>${Vi}</string><key>LimitLoadToSessionType</key><string>Aqua</string>
|
|
109
|
+
<key>ProgramArguments</key><array>${[Ne(t,"Contents","MacOS","InterscaleGraphicalWorker"),e,r].map(c=>`<string>${o(c)}</string>`).join("")}</array>
|
|
110
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>10</integer>
|
|
111
|
+
<key>EnvironmentVariables</key><dict><key>INTERSCALE_HOME</key><string>${o(n)}</string><key>INTERSCALE_AGENT_CONFIG</key><string>${o(i)}</string></dict>
|
|
112
|
+
<key>StandardOutPath</key><string>${o(s)}</string><key>StandardErrorPath</key><string>${o(s)}</string></dict></plist>
|
|
113
|
+
`}function cN({node:t,entry:e,root:r,config:n}){return`[Unit]
|
|
114
|
+
Description=InterScale graphical session host
|
|
115
|
+
PartOf=graphical-session.target
|
|
116
|
+
After=graphical-session-pre.target
|
|
117
|
+
[Service]
|
|
118
|
+
ExecStart=${Gt(t)} ${Gt(e)}
|
|
119
|
+
Environment=${Gt(`INTERSCALE_HOME=${r}`,!1)}
|
|
120
|
+
Environment=${Gt(`INTERSCALE_AGENT_CONFIG=${n}`,!1)}
|
|
121
|
+
Restart=on-failure
|
|
122
|
+
RestartSec=10
|
|
123
|
+
[Install]
|
|
124
|
+
WantedBy=graphical-session.target
|
|
125
|
+
`}function Gt(t,e=!0){let r=String(t);if(/[\r\n\0]/.test(r))throw new Error("Service paths cannot contain control characters");return'"'+r.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("%","%%").replaceAll("$",e?"$$":"$")+'"'}function Ih(t,e,r){if(t(e,r,{encoding:"utf8",windowsHide:!0,timeout:3e4}).status!==0)throw new Error("Could not register the graphical session service")}async function lN(t){try{let{pid:e}=JSON.parse(nN(vy(t).lock,"utf8"));if(Number.isSafeInteger(e)&&e>0&&Ge(e)?.includes("interscale-graphical-worker.mjs")){process.kill(e,"SIGTERM");let r=Date.now()+1e4;for(;Ge(e)?.includes("interscale-graphical-worker.mjs");){if(Date.now()>r)throw new Error("The previous graphical worker has not finished stopping");await new Promise(n=>setTimeout(n,100))}}}catch(e){if(!["ENOENT","ESRCH"].includes(e.code))throw e}}var Sy,oN,Vi,Ht,Cc=v(()=>{Z();Gn();Ey();Ac();Sy="/Library/Application Support/Interscale/Helpers.noindex/InterscaleGraphicalWorker.app",oN="/Library/Application Support/Interscale/InterscaleGraphicalWorker.app";a(Oy,"macGraphicalBundle");Vi="com.interscale.graphical-worker",Ht="interscale-graphical-worker.service";a(Lc,"graphicalWorkerAvailable");a(po,"installGraphicalService");a(Iy,"uninstallGraphicalService");a(aN,"graphicalPlist");a(cN,"graphicalUnit");a(Gt,"unitQuote");a(Ih,"checked");a(lN,"stopWindowsWorker")});import{chmodSync as dN,existsSync as Pc,lstatSync as Dc,mkdirSync as uN,readFileSync as Ay,renameSync as hN,rmSync as Jn,writeFileSync as pN}from"node:fs";import{dirname as $c,isAbsolute as Ly,join as bt,resolve as Cy}from"node:path";import{spawnSync as en}from"node:child_process";import{randomUUID as fN}from"node:crypto";function Yi(t,e,r=process.getuid?.()===0){return r?["asuser",String(t),"/bin/launchctl",...e]:e}function Ah(t=process.platform){if(t==="darwin")return"/Library/Application Support/Interscale/machine-installation.json";if(t==="linux")return"/etc/interscale/machine-installation.json";throw new Error("Machine service registration is not supported on this platform")}function Ir(t=process.platform){let e=Ah(t);if(!Pc(e))return null;let r=Dc(e);if(!r.isFile()||r.uid!==0||r.mode&18||r.size>16*1024)throw new Error("Machine installation receipt is not administrator-owned");let n=JSON.parse(Ay(e,"utf8"));if(n.schema!=="interscale.machine-installation/v1")throw new Error("Invalid machine installation receipt");return Fc(n.owner),n}function Uc(t,{platform:e=process.platform,execute:r=en}={}){if(!/^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/.test(t||"")||t==="root")throw new Error("Select a non-root local account for the machine service");let n=Number(vt(r,"/usr/bin/id",["-u",t]).trim()),i=Number(vt(r,"/usr/bin/id",["-g",t]).trim()),s;e==="darwin"?s=vt(r,"/usr/bin/dscl",[".","-read",`/Users/${t}`,"NFSHomeDirectory"]).replace(/^NFSHomeDirectory:\s*/,"").trim():e==="linux"&&(s=vt(r,"getent",["passwd",t]).trim().split(":")[5]);let o={name:t,uid:n,gid:i,home:s};return Fc(o),o}function mN({owner:t,node:e,entry:r,root:n,config:i=bt(n,"agent.json"),platform:s=process.platform}){Fc(t);for(let c of[e,r,n,i])if(!Ly(c)||/[\0\r\n]/.test(c))throw new Error("Machine service requires absolute paths without control characters");let o={HOME:t.home,PATH:`${bt(t.home,".local","bin")}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,INTERSCALE_HOME:n,INTERSCALE_AGENT_CONFIG:i,INTERSCALE_MACHINE_CREDENTIAL:Me(n),INTERSCALE_GRAPHICAL_WORKER:"1",INTERSCALE_OWNER_UID:String(t.uid)};if(s==="darwin"){let c=a(l=>String(l).replaceAll("&","&").replaceAll("<","<").replaceAll('"',"""),"e");return{path:`/Library/LaunchAgents/${rt}.plist`,label:rt,text:`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>
|
|
126
|
+
<key>Label</key><string>${rt}</string><key>LimitLoadToSessionType</key><string>Aqua</string>
|
|
127
|
+
<key>ProgramArguments</key><array><string>${c(e)}</string><string>${c(r)}</string></array>
|
|
128
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>15</integer>
|
|
129
|
+
<key>ProcessType</key><string>Standard</string><key>Umask</key><integer>63</integer>
|
|
130
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(o).map(([l,d])=>`<key>${l}</key><string>${c(d)}</string>`).join("")}</dict>
|
|
131
|
+
<key>StandardOutPath</key><string>${c(bt(n,"logs","agent.log"))}</string>
|
|
132
|
+
<key>StandardErrorPath</key><string>${c(bt(n,"logs","agent.log"))}</string></dict></plist>
|
|
133
|
+
`}}if(s==="linux")return{path:`/etc/systemd/system/${Jt}`,label:Jt,text:`[Unit]
|
|
134
|
+
Description=InterScale machine service
|
|
135
|
+
After=network-online.target
|
|
136
|
+
Wants=network-online.target
|
|
137
|
+
[Service]
|
|
138
|
+
Type=simple
|
|
139
|
+
User=${t.name}
|
|
140
|
+
Group=${t.gid}
|
|
141
|
+
ExecStart=${Gt(e)} ${Gt(r)}
|
|
142
|
+
${Object.entries(o).map(([c,l])=>`Environment=${Gt(`${c}=${l}`,!1)}
|
|
143
|
+
`).join("")}Restart=always
|
|
144
|
+
RestartSec=15
|
|
145
|
+
UMask=0077
|
|
146
|
+
NoNewPrivileges=true
|
|
147
|
+
ProtectSystem=full
|
|
148
|
+
[Install]
|
|
149
|
+
WantedBy=multi-user.target
|
|
150
|
+
`};throw new Error("Machine service platform is unsupported")}function fo({owner:t,runtimeRoot:e,root:r,config:n,platform:i=process.platform,execute:s=en}={}){if(process.getuid?.()!==0)throw new Error("Installing the boot service requires the operating system's administrator authorization");Fc(t),e=Cy(e);let o=bt(e,"node","bin","node"),c=bt(e,"app","bin","interscale-agent.mjs");if(!Pc(o)||!Pc(c))throw new Error("Complete machine runtime is missing");let l=mN({owner:t,node:o,entry:c,root:r,config:n,platform:i}),d=n||bt(r,"agent.json"),u=Dc(d);if(!u.isFile()||u.size>1024*1024||u.uid!==t.uid)throw new Error("Activate InterScale under the machine's service account before enabling boot");let h=JSON.parse(Ay(d,"utf8"));if(Dc(Me(r)).uid!==t.uid)throw new Error("The boot credential must belong to the service account");Ze(Me(r),h.node_id);let p=Ir(i);if(p&&p.owner.uid!==t.uid)throw new Error("This machine belongs to a different local service account; migrate its identity before changing owners");i==="darwin"?(s("/bin/launchctl",["bootout",`system/${rt}`],{stdio:"ignore"}),Jn(`/Library/LaunchDaemons/${rt}.plist`,{force:!0})):s("runuser",["-u",t.name,"--","systemctl","--user","disable","--now",Jt],{stdio:"ignore",timeout:3e4,env:{...process.env,XDG_RUNTIME_DIR:`/run/user/${t.uid}`}}),Ny(l.path,l.text);let f=!1;i==="darwin"?(Jn(bt(t.home,"Library","LaunchAgents",`${rt}.plist`),{force:!0}),s("/bin/launchctl",Yi(t.uid,["print",`gui/${t.uid}`]),{stdio:"ignore"}).status!==0?(s("/bin/launchctl",Yi(t.uid,["bootout",`gui/${t.uid}/${rt}`]),{stdio:"ignore"}),f=!0):Ji({domain:`gui/${t.uid}`,label:rt,plist:l.path,execute:s,wrap:a(_=>Yi(t.uid,_),"wrap")})):(vt(s,"systemctl",["daemon-reload"]),vt(s,"systemctl",["enable","--now",Jt]),vt(s,"systemctl",["restart",Jt]),Jn(bt(t.home,".config","systemd","user",Jt),{force:!0}));let m={schema:"interscale.machine-installation/v1",owner:t,runtime_root:e,data_root:r,config_path:n||bt(r,"agent.json"),installed_at:Date.now()};return Ny(Ah(i),JSON.stringify(m)+`
|
|
151
|
+
`),{installed:!0,scope:"boot",user:t.name,path:l.path,...f?{awaiting_login:!0}:{}}}function tn({platform:t=process.platform,execute:e=en}={}){let r=Ir(t);if(!r)return null;if(t==="darwin"){let i=e("/bin/launchctl",Yi(r.owner.uid,["print",`gui/${r.owner.uid}/${rt}`]),{encoding:"utf8"}),s=Number(i.stdout?.match(/\bpid = (\d+)/)?.[1])||null;return{installed:!0,scope:"boot",user:r.owner.name,loaded:i.status===0&&!!s,detail:{pid:s,state:i.stdout?.match(/\bstate = ([^\n]+)/)?.[1]?.trim()||null}}}let n=e("systemctl",["show",Jt,"--property=LoadState,ActiveState,SubState,MainPID"],{encoding:"utf8"});return{installed:!0,scope:"boot",user:r.owner.name,loaded:n.status===0&&n.stdout.includes("ActiveState=active"),detail:n.stdout?.trim()||""}}function jc(t){let e=Ir();if(!e)return null;if(process.getuid()===0)return fo({owner:e.owner,runtimeRoot:t,root:e.data_root,config:e.config_path});if(e.owner.uid!==process.getuid())throw new Error("The machine service belongs to another local account");if(Cy(t)!==e.runtime_root)throw new Error("A boot installation must be upgraded by the system updater");return{...tn(),reused:!0}}function Mc(){let t=Ir();if(!t)return null;let e=tn(),r=e.detail?.pid||Number(String(e.detail).match(/(?:^|\n)MainPID=(\d+)/)?.[1]);if(r&&Ge(r)?.includes(bt(t.runtime_root,"app","bin","interscale-agent.mjs"))){try{process.kill(r,"SIGTERM")}catch(n){if(n.code!=="ESRCH")throw n}return{restarted:!0,scope:"boot",pending:!0}}if(process.getuid()!==0)throw new Error("The boot service is stopped; repair its installation with administrator authorization");return process.platform==="darwin"?vt(en,"/bin/launchctl",Yi(t.owner.uid,["kickstart","-k",`gui/${t.owner.uid}/${rt}`])):vt(en,"systemctl",["restart",Jt]),{restarted:!0,scope:"boot"}}function Bc(){let t=Ir();if(!t)return null;if(process.getuid()!==0)throw new Error("Removing the boot service requires administrator authorization; machine data will be preserved");return process.platform==="darwin"?(en("/bin/launchctl",Yi(t.owner.uid,["bootout",`gui/${t.owner.uid}/${rt}`]),{stdio:"ignore"}),Jn(`/Library/LaunchAgents/${rt}.plist`,{force:!0})):(vt(en,"systemctl",["disable","--now",Jt]),Jn(`/etc/systemd/system/${Jt}`,{force:!0}),vt(en,"systemctl",["daemon-reload"])),Jn(Ah(),{force:!0}),{removed:!0,scope:"boot",data_preserved:!0}}function Fc(t){if(!t||!/^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/.test(t.name)||t.name==="root"||!Number.isSafeInteger(t.uid)||t.uid<=0||!Number.isSafeInteger(t.gid)||t.gid<0||typeof t.home!="string"||!Ly(t.home)||/[\r\n\0]/.test(t.home))throw new Error("Machine jobs require a valid non-root local account")}function vt(t,e,r){let n=t(e,r,{encoding:"utf8",timeout:3e4});if(n.status!==0)throw new Error(`Could not configure machine service (${e})`);return n.stdout||""}function Ny(t,e){Py($c(t)),uN($c(t),{recursive:!0,mode:493});let r=`${t}.${fN()}.tmp`;try{pN(r,e,{flag:"wx",mode:420}),dN(r,420),hN(r,t)}finally{Jn(r,{force:!0})}}function Py(t){if(t===$c(t)||(Py($c(t)),!Pc(t)))return;let e=Dc(t);if(!e.isDirectory()||e.uid!==0||e.mode&18)throw new Error("System service paths must be administrator-owned directories without writable or symlink parents")}var rt,Jt,Xi=v(()=>{bi();Cc();Gn();Ac();rt="com.interscale.agent",Jt="interscale-agent.service";a(Yi,"guiLaunchctl");a(Ah,"machineInstallationPath");a(Ir,"readMachineInstallation");a(Uc,"resolveMachineOwner");a(mN,"machineServiceSpec");a(fo,"installMachineService");a(tn,"machineServiceStatus");a(jc,"reuseMachineService");a(Mc,"restartMachineService");a(Bc,"uninstallMachineService");a(Fc,"validateOwner");a(vt,"command");a(Ny,"writeSystemFile");a(Py,"assertSystemParents")});import{existsSync as Dy,mkdirSync as Lh,readFileSync as Ph,renameSync as _N,rmSync as P6,writeFileSync as Ch}from"node:fs";import{join as Se,resolve as $6}from"node:path";function Ki(t){let e=Se(t,"startup");return{startup:e,launcher:Se(e,"InterscaleUpdater.vbs"),loop:Se(e,"InterscaleUpdaterLoop.cmd"),legacyLoop:Se(e,"InterscaleUpdater.cmd"),pointer:Se(e,"updater-runtime.txt"),disabled:Se(t,"updater-disabled"),lock:Se(t,"updater.lock"),log:Se(t,"logs","updater.log"),process:Se(t,"updater-process.json"),updates:Se(t,"updates")}}function gN({root:t,config:e,log:r,fallback:n}){let i=Ki(t);return["@echo off",`set "INTERSCALE_HOME=${rn(t)}"`,`set "INTERSCALE_AGENT_CONFIG=${rn(e)}"`,":run",`if exist "${rn(i.disabled)}" exit /b 0`,'set "UPDATER_NODE="','set "UPDATER_ENTRY="',`if exist "${rn(i.pointer)}" for /f "usebackq tokens=1,* delims==" %%k in ("${rn(i.pointer)}") do set "%%k=%%l"`,'if not exist "%UPDATER_NODE%" goto fallback','if exist "%UPDATER_ENTRY%" goto launch',":fallback",`set "UPDATER_NODE=${rn(n.node)}"`,`set "UPDATER_ENTRY=${rn(n.entry)}"`,":launch",`"%UPDATER_NODE%" "%UPDATER_ENTRY%" >> "${rn(r)}" 2>&1`,"timeout /t 10 /nobreak >nul","goto run",""].join(`\r
|
|
152
|
+
`)}function wN({node:t,entry:e}){return`UPDATER_NODE=${t}\r
|
|
153
|
+
UPDATER_ENTRY=${e}\r
|
|
154
|
+
`}function yN(t){return`CreateObject("WScript.Shell").Run Chr(34) & "${t.replaceAll('"','""')}" & Chr(34), 0, False\r
|
|
155
|
+
`}function $y(t){try{let e=JSON.parse(Ph(Se(t,"updates","active-runtime.json"),"utf8"));return typeof e?.node!="string"||typeof e?.app_root!="string"?null:{node:e.node,entry:Se(e.app_root,"bin","interscale-updater.mjs")}}catch{return null}}function Uy(t,e){let{startup:r,pointer:n}=Ki(t),i=wN(e);try{if(Ph(n,"utf8")===i)return!1}catch{}Lh(r,{recursive:!0});let s=`${n}.${process.pid}.tmp`;return Ch(s,i),_N(s,n),!0}function jy({root:t,config:e,fallback:r}){let n=Ki(t),i=gN({root:t,config:e,log:n.log,fallback:r}),s=yN(n.loop),o=a(c=>{try{return Ph(c,"utf8")}catch{return null}},"read");return o(n.loop)===i&&o(n.launcher)===s?!1:(Lh(n.startup,{recursive:!0}),Lh(Se(t,"logs"),{recursive:!0}),Ch(n.loop,i),Ch(n.launcher,s),!0)}function My(t=process.env){let e=Se(t.LOCALAPPDATA||"","Programs","Interscale"),r={node:Se(e,"node","node.exe"),entry:Se(e,"app","bin","interscale-updater.mjs")};return Dy(r.node)&&Dy(r.entry)?r:null}var rn,By=v(()=>{Wn();Gn();a(Ki,"windowsUpdaterPaths");rn=a(t=>String(t).replaceAll("%","%%"),"cmd");a(gN,"windowsUpdaterLoop");a(wN,"windowsUpdaterPointer");a(yN,"windowsUpdaterLauncher");a($y,"activeUpdaterRuntime");a(Uy,"writeWindowsUpdaterPointer");a(jy,"writeWindowsUpdaterLoop");a(My,"windowsInstallRuntime")});import{existsSync as nn,mkdirSync as qc,writeFileSync as Uh,readFileSync as Fy,rmSync as zc}from"node:fs";import{dirname as Dh,join as Nr}from"node:path";import{homedir as Wc}from"node:os";import{fileURLToPath as bN}from"node:url";import{spawnSync as qy}from"node:child_process";function Hc({env:t=process.env,platform:e=process.platform,execute:r=qy,node:n=process.execPath,entry:i=bN(new URL("../bin/interscale-updater.mjs",import.meta.url)),machineInstallation:s=Ir}={}){if(e==="darwin"&&s(e)){let p="/Library/LaunchDaemons/com.interscale.system-updater.plist";return{installed:nn(p),reused:!0,scope:"boot",path:p,pending:!nn(p)}}if(e==="darwin")return{installed:!1,reason:"machine_setup_required",next_action:"Install the signed Interscale package on this Mac"};if(e==="linux"&&s(e)){let p="/etc/systemd/system/interscale-system-updater.service";return{installed:nn(p),reused:!0,scope:"boot",path:p,pending:!nn(p)}}let o=x(t,e),c=L(t),l=Nr(o,"logs","updater.log");qc(Dh(l),{recursive:!0,mode:448});let d,u,h;if(e==="darwin"){if(d=Nr(Wc(),"Library","LaunchAgents","com.interscale.updater.plist"),nn(d)&&r("/bin/launchctl",["print",`gui/${process.getuid()}/com.interscale.updater`],{stdio:"ignore"}).status===0)return{installed:!0,reused:!0,path:d};qc(Dh(d),{recursive:!0}),Uh(d,vN({node:n,entry:i,config:c,root:o,log:l}),{mode:384}),u="/bin/launchctl",h=["bootstrap",`gui/${process.getuid()}`,d]}else if(e==="linux"){if(d=Nr(t.XDG_CONFIG_HOME||Nr(Wc(),".config"),"systemd","user","interscale-updater.service"),nn(d)&&r("systemctl",["--user","is-active","--quiet","interscale-updater.service"],{stdio:"ignore"}).status===0)return{installed:!0,reused:!0,path:d};qc(Dh(d),{recursive:!0}),Uh(d,EN({node:n,entry:i,config:c,root:o}),{mode:384}),$h(r,"systemctl",["--user","daemon-reload"]),u="systemctl",h=["--user","enable","--now","interscale-updater.service"]}else if(e==="win32"){let p=Ki(o);d=p.launcher;let f=nn(p.disabled),m=jy({root:o,config:c,fallback:My(t)||{node:n,entry:i}});if(nn(p.pointer)||Uy(o,$y(o)||{node:n,entry:i}),!m&&!f)return{installed:!0,reused:!0,path:d};if(zc(p.disabled,{force:!0}),$h(r,"reg.exe",["add","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run","/v","InterscaleUpdater","/t","REG_SZ","/d",`wscript.exe "${d}"`,"/f"]),SN(p.lock))return{installed:!0,reused:!1,path:d,restart_pending:!0};u="wscript.exe",h=[d]}else throw new Error("Unsupported updater service platform");return $h(r,u,h),{installed:!0,reused:!1,path:d}}function vN({node:t,entry:e,config:r,root:n,log:i}){let s=a(o=>String(o).replaceAll("&","&").replaceAll("<","<").replaceAll('"',"""),"e");return`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>
|
|
156
|
+
<key>Label</key><string>com.interscale.updater</string><key>ProgramArguments</key><array><string>${s(t)}</string><string>${s(e)}</string></array>
|
|
157
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>30</integer>
|
|
158
|
+
<key>EnvironmentVariables</key><dict><key>INTERSCALE_HOME</key><string>${s(n)}</string><key>INTERSCALE_AGENT_CONFIG</key><string>${s(r)}</string></dict>
|
|
159
|
+
<key>StandardOutPath</key><string>${s(i)}</string><key>StandardErrorPath</key><string>${s(i)}</string></dict></plist>
|
|
160
|
+
`}function EN({node:t,entry:e,config:r,root:n}){let i=a(s=>'"'+String(s).replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll("%","%%").replaceAll("$","$$")+'"',"q");return`[Unit]
|
|
161
|
+
Description=InterScale update supervisor
|
|
162
|
+
After=network-online.target
|
|
163
|
+
[Service]
|
|
164
|
+
ExecStart=${i(t)} ${i(e)}
|
|
165
|
+
Environment=${i(`INTERSCALE_HOME=${n}`)}
|
|
166
|
+
Environment=${i(`INTERSCALE_AGENT_CONFIG=${r}`)}
|
|
167
|
+
Restart=always
|
|
168
|
+
RestartSec=30
|
|
169
|
+
[Install]
|
|
170
|
+
WantedBy=default.target
|
|
171
|
+
`}function $h(t,e,r){if(t(e,r,{encoding:"utf8",windowsHide:!0,timeout:3e4}).status!==0)throw new Error("Could not register the independent update supervisor")}function zy({env:t=process.env,platform:e=process.platform,execute:r=qy}={}){let n=x(t,e);if(e==="darwin")r("/bin/launchctl",["bootout",`gui/${process.getuid()}/com.interscale.updater`],{stdio:"ignore"}),zc(Nr(Wc(),"Library","LaunchAgents","com.interscale.updater.plist"),{force:!0});else if(e==="linux")r("systemctl",["--user","disable","--now","interscale-updater.service"],{stdio:"ignore"}),zc(Nr(t.XDG_CONFIG_HOME||Nr(Wc(),".config"),"systemd","user","interscale-updater.service"),{force:!0}),r("systemctl",["--user","daemon-reload"],{stdio:"ignore"});else if(e==="win32"){qc(n,{recursive:!0}),Uh(Nr(n,"updater-disabled"),`disabled
|
|
172
|
+
`),r("reg.exe",["delete","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run","/v","InterscaleUpdater","/f"],{stdio:"ignore"});try{let{pid:s}=JSON.parse(Fy(Nr(n,"updater.lock"),"utf8"));Number.isInteger(s)&&s>0&&Ge(s)?.includes("interscale-updater.mjs")&&process.kill(s,"SIGTERM")}catch(s){if(!["ENOENT","ESRCH"].includes(s.code))throw s}let i=Ki(n);for(let s of[i.launcher,i.loop,i.legacyLoop,i.pointer])zc(s,{force:!0})}return{installed:!1}}function SN(t){try{let{pid:e}=JSON.parse(Fy(t,"utf8"));return Number.isSafeInteger(e)&&e>0&&/interscale-updater\.mjs/i.test(Ge(e)||"")}catch{return!1}}var Wy=v(()=>{Gn();Z();Xi();By();a(Hc,"installAutomaticUpdater");a(vN,"updaterPlist");a(EN,"updaterUnit");a($h,"checked");a(zy,"uninstallAutomaticUpdater");a(SN,"updaterRunning")});import{chmodSync as TN,existsSync as kN,mkdirSync as xN,renameSync as RN,writeFileSync as ON}from"node:fs";import{join as jh,resolve as IN}from"node:path";function Mh({root:t=x(),runtimeRoot:e,node:r=process.execPath,platform:n=process.platform}={}){if(!e)throw new Error("Runtime root is required");let i=jh(t,"bin");xN(i,{recursive:!0,mode:448});let s={};for(let[o,c]of[["interscale","interscale.mjs"],["interscale-mcp","interscale-mcp.mjs"]]){let l=IN(e,"bin",c),d=jh(i,o+(n==="win32"?".cmd":"")),u=n==="win32"?f=>{if(/["\r\n%!]/.test(f))throw new Error("Unsupported launcher path");return`"${f}"`}:f=>`'${f.replaceAll("'","'\\''")}'`,h=n==="win32"?`@echo off\r
|
|
173
|
+
${u(r)} ${u(l)} %*\r
|
|
174
|
+
`:`#!/bin/sh
|
|
175
|
+
exec ${u(r)} ${u(l)} "$@"
|
|
176
|
+
`,p=`${d}.${process.pid}.tmp`;ON(p,h,{mode:448}),RN(p,d),n!=="win32"&&TN(d,448),s[o]=d}return{...s,mcp_command:n==="win32"?"cmd.exe":s["interscale-mcp"],mcp_args:n==="win32"?["/d","/c",s["interscale-mcp"]]:[]}}function Hy({root:t=x(),platform:e=process.platform,exists:r=kN}={}){let n=jh(t,"bin",`interscale-mcp${e==="win32"?".cmd":""}`);return r(n)?e==="win32"?{mcp_command:"cmd.exe",mcp_args:["/d","/c",n]}:{mcp_command:n,mcp_args:[]}:null}var Gy=v(()=>{Z();a(Mh,"installStableLaunchers");a(Hy,"installedMcpLauncher")});import{statSync as NN}from"node:fs";import{win32 as Jy}from"node:path";function Gc(t,e,{platform:r=process.platform,env:n=process.env,cwd:i=process.cwd(),isFile:s=CN}={}){if(r!=="win32")return{command:t,args:e};let o=AN(t,{env:n,cwd:i,isFile:s});if(!o)return{command:t,args:e};if(!/\.(?:bat|cmd)$/i.test(o))return{command:o,args:e};if(e.some(l=>/[\r\n]/.test(String(l))))throw Object.assign(new Error("cmd.exe cannot pass arguments containing line breaks to a .cmd or .bat command"),{code:"invalid_windows_arguments"});let c=[`"${o}"`,...e.map(l=>LN(String(l)))].join(" ");return{command:Bh(n,"COMSPEC")||"cmd.exe",args:["/d","/s","/c",`"${c}"`],windowsVerbatimArguments:!0}}function AN(t,{env:e,cwd:r,isFile:n}){if(typeof t!="string"||!t||t.includes("\0"))return null;let i=(Bh(e,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").map(c=>c.trim().toLowerCase()).filter(c=>Vy.has(c)),s=Vy.has(Jy.extname(t).toLowerCase())?[t]:[];s.push(...i.map(c=>`${t}${c}`));let o=/[\\/]/.test(t)?[r]:[r,...String(Bh(e,"PATH")||"").split(";").map(c=>c.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean)];for(let c of o)for(let l of s){let d=Jy.resolve(r,c,l);if(n(d))return d}return null}function LN(t){let e='"',r=0;for(let n of t){if(n==="\\"){r+=1;continue}e+="\\".repeat(n==='"'?r*2+1:r)+n,r=0}return e+=`${"\\".repeat(r*2)}"`,e.replace(Yy,"^$1").replace(Yy,"^$1")}function Bh(t,e){return Object.entries(t||{}).find(([r])=>r.toUpperCase()===e)?.[1]}function CN(t){try{return NN(t).isFile()}catch{return!1}}var Vy,Yy,Fh=v(()=>{Vy=new Set([".com",".exe",".bat",".cmd"]),Yy=/([()\][%!^"`<>&|;, *?])/g;a(Gc,"resolveSpawnCommand");a(AN,"findWindowsExecutable");a(LN,"escapeCmdArgument");a(Bh,"environmentValue");a(CN,"fileExists")});import{arch as Vc,cpus as Xy,freemem as PN,homedir as Vn,hostname as DN,networkInterfaces as $N,platform as Ae,release as Yn,totalmem as UN,uptime as jN,loadavg as MN}from"node:os";import{execFileSync as _o}from"node:child_process";import{existsSync as Yc,readFileSync as Qy,readdirSync as BN,statfsSync as FN}from"node:fs";import{basename as Ky,dirname as Jc,join as Te}from"node:path";import{createHash as qN}from"node:crypto";function eb(t=process.cwd()){let e=JN(),r=XN();return{schema_version:2,collected_at:Date.now(),hostname:DN(),platform:Ae(),release:Yn(),arch:Vc(),os:VN(),device:YN(),cpu_model:e.model,cpu_cores:e.cores,cpu_threads:e.threads,cpu_topology:e.topology,memory_total_bytes:UN(),memory_free_bytes:PN(),load_average:Ae()==="win32"?null:MN(),uptime_seconds:Math.floor(jN()),network_fingerprint:GN(),storage:KN(t),gpus:r,software:ZN()}}function GN(){let t=Object.entries($N()).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,(r||[]).filter(n=>!n.internal).map(n=>({family:n.family,address:n.address,netmask:n.netmask,scopeid:n.scopeid||0})).sort((n,i)=>JSON.stringify(n).localeCompare(JSON.stringify(i)))]);return qN("sha256").update(JSON.stringify(t)).digest("hex")}function tb(t){return l_(t?Si({classes:t}):void 0)}function JN(){let t=Xy().length,e=null,r=null;if(Ae()==="darwin"){let n=Vt("/usr/sbin/sysctl",["-n","hw.physicalcpu","hw.logicalcpu","hw.perflevel0.physicalcpu","hw.perflevel1.physicalcpu"])?.trim().split(/\r?\n/).map(Number);n?.length>=2&&(e=mo(n[0]),r={performance_cores:mo(n[2]),efficiency_cores:mo(n[3])})}else if(Ae()==="linux")try{let n=JSON.parse(Vt("lscpu",["-J"],{env:{...process.env,LC_ALL:"C"}})||"{}"),i=Object.fromEntries((n.lscpu||[]).map(c=>[String(c.field).replace(/:$/,""),c.data])),s=Number(i["Core(s) per socket"]),o=Number(i["Socket(s)"]);Number.isInteger(s)&&Number.isInteger(o)&&(e=s*o)}catch{}else if(Ae()==="win32"){let n=Vt("powershell.exe",["-NoProfile","-NonInteractive","-Command","[Console]::Out.Write((Get-CimInstance Win32_Processor | Measure-Object NumberOfCores -Sum).Sum)"]);e=mo(Number(n))}return{model:Xy()[0]?.model||"unknown",cores:e,threads:t,topology:r}}function VN(){if(Ae()==="darwin")return{name:"macOS",version:Vt("/usr/bin/sw_vers",["-productVersion"])?.trim()||Yn(),kernel:Yn(),arch:Vc()};if(Ae()==="win32")return{name:"Windows",version:Yn(),kernel:Yn(),arch:Vc()};let t=cA("/etc/os-release");return{name:Zy(t.PRETTY_NAME)||"Linux",version:Zy(t.VERSION_ID)||Yn(),kernel:Yn(),arch:Vc()}}function YN(){if(Ae()==="darwin")try{let e=JSON.parse(Vt("/usr/sbin/system_profiler",["SPHardwareDataType","-json"],{timeout:5e3})||"{}").SPHardwareDataType?.[0]||{};return{manufacturer:"Apple",family:e.machine_name||null,model:e.machine_model||null}}catch{return{manufacturer:"Apple",family:null,model:null}}if(Ae()==="win32")try{let t=Vt("powershell.exe",["-NoProfile","-NonInteractive","-Command","$v=Get-CimInstance Win32_ComputerSystem; [Console]::Out.Write(($v | Select-Object Manufacturer,Model | ConvertTo-Json -Compress))"]),e=JSON.parse(t||"{}");return{manufacturer:e.Manufacturer||null,family:null,model:e.Model||null}}catch{return{manufacturer:null,family:null,model:null}}return{manufacturer:Wh("/sys/devices/virtual/dmi/id/sys_vendor"),family:Wh("/sys/devices/virtual/dmi/id/product_family"),model:Wh("/sys/devices/virtual/dmi/id/product_name")}}function XN(){let t=tA();if(t.length>0)return t;if(Ae()==="darwin")return iA();if(Ae()==="win32"){let e=rA();return e.length>0?e:nA()}return[]}function KN(t){try{let e=FN(t,{bigint:!0});return{path:t,total_bytes:Number(e.blocks*e.bsize),available_bytes:Number(e.bavail*e.bsize)}}catch{return{path:t,total_bytes:null,available_bytes:null}}}function ZN(){let t=QN(),e=[];for(let r of t)for(let[n,i]of Object.entries(r.packages))e.push({name:sA(n),distribution:n,version:i,environment:r.environment,runtime_path:r.path});return{runtimes:[{name:"Node.js",version:process.version.replace(/^v/,""),path:process.execPath},...t.map(({packages:r,...n})=>n)],frameworks:e,tools:eA()}}function QN(){let t=[];for(let e of rb().slice(0,12))try{let r=JSON.parse(_o(e,["-c",WN],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],maxBuffer:131072}));t.push({name:"Python",version:r.version,path:r.executable||e,environment:oA(r.executable||e),packages:r.packages||{}})}catch{}return dA(t,e=>e.path)}function rb(){let t=[],e=a(r=>{!r||!Yc(r)||t.push(r)},"add");if(Ae()!=="win32"){for(let r of[process.env.VIRTUAL_ENV&&Te(process.env.VIRTUAL_ENV,"bin","python"),Te(Vn(),".olivia-venv","bin","python"),Te(Vn(),".venv","bin","python"),Te(Vn(),"miniconda3","bin","python"),Te(Vn(),"anaconda3","bin","python"),"/opt/homebrew/bin/python3","/usr/local/bin/python3","/usr/bin/python3"])e(r);for(let r of zh("python3"))e(r);for(let r of zh("python"))e(r);qh(t,Te(Vn(),".pyenv","versions"),Te("bin","python")),qh(t,Te(Vn(),".local","share","uv","python"),Te("bin","python3"))}else{let r=process.env.USERPROFILE||Vn();for(let n of[process.env.VIRTUAL_ENV&&Te(process.env.VIRTUAL_ENV,"Scripts","python.exe"),Te(r,".venv","Scripts","python.exe"),Te(r,"miniconda3","python.exe"),Te(r,"anaconda3","python.exe")])e(n);for(let n of zh("python.exe"))e(n);qh(t,Te(process.env.LOCALAPPDATA||"","Programs","Python"),"python.exe")}return[...new Set(t)]}function qh(t,e,r){if(!(!e||!Yc(e)))try{for(let n of BN(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let i=Te(e,n.name,r);Yc(i)&&t.push(i)}}catch{}}function zh(t){let e=Ae()==="win32"?"where.exe":"/usr/bin/which";return Vt(e,Ae()==="win32"?[t]:["-a",t])?.split(/\r?\n/).map(n=>n.trim()).filter(Boolean)||[]}function eA(){let t=[["FFmpeg","ffmpeg",["-version"],/ffmpeg version\s+([^\s]+)/i],["Blender","blender",["--version"],/Blender\s+([^\s]+)/i],["Docker","docker",["--version"],/Docker version\s+([^,\s]+)/i],["Ollama","ollama",["--version"],/(?:ollama version is|ollama version|ollama)\s+v?([^\s]+)/i],["CUDA Toolkit","nvcc",["--version"],/release\s+([^,\s]+)/i],["uv","uv",["--version"],/uv\s+([^\s]+)/i],["Conda","conda",["--version"],/conda\s+([^\s]+)/i],["tmux","tmux",["-V"],/tmux\s+([^\s]+)/i],["Claude Code","claude",["--version"],/^\s*v?(\d+\.\d+[^\s]*)/],["Codex","codex",["--version"],/(\d+\.\d+[^\s]*)/],["Node.js","node",["--version"],/v?(\d+\.\d+[^\s]*)/],["Git","git",["--version"],/git version\s+([^\s]+)/i],["GitHub CLI","gh",["--version"],/gh version\s+([^\s]+)/i],["Python",Ae()==="win32"?"python":"python3",["--version"],/Python\s+([^\s]+)/i]],e=[];for(let[r,n,i,s]of t){let c=Vt(n,i,{timeout:n==="blender"?8e3:3e3})?.match(s)?.[1]?.replace(/,$/,"");c&&e.push({name:r,version:c})}return e}function tA(){try{let t=_o("nvidia-smi",["--query-gpu=name,memory.total,driver_version","--format=csv,noheader,nounits"],{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]}),r=Vt("nvidia-smi",[],{timeout:3e3})?.match(/CUDA Version:\s*([0-9.]+)/i)?.[1]||null;return t.trim().split(/\r?\n/).filter(Boolean).map(n=>{let[i,s,o]=n.split(",").map(c=>c.trim());return{vendor:"nvidia",name:i,memory_bytes:Number(s)*1024*1024,driver:o,cuda:r}})}catch{return[]}}function rA(){for(let t of rb().slice(0,8))try{let e=JSON.parse(_o(t,["-c",HN],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"],maxBuffer:131072}));if(!Array.isArray(e)||e.length===0)continue;return e.map(r=>({vendor:"nvidia",name:r.name||"NVIDIA GPU",memory_bytes:mo(Number(r.memory_bytes)),driver:null,cuda:r.cuda||null,inventory_source:"pytorch"}))}catch{}return[]}function nA(){try{let t=Vt("powershell.exe",["-NoProfile","-NonInteractive","-Command","@(Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion) | ConvertTo-Json -Compress"],{timeout:5e3}),e=JSON.parse(t||"[]");return(Array.isArray(e)?e:[e]).filter(r=>r?.Name).map(r=>({vendor:/nvidia/i.test(r.Name)?"nvidia":null,name:r.Name,driver:r.DriverVersion||null,inventory_source:"windows-cim"}))}catch{return[]}}function iA(){try{let t=_o("/usr/sbin/system_profiler",["SPDisplaysDataType","-json"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return(JSON.parse(t).SPDisplaysDataType||[]).map(r=>({vendor:"apple",name:r.sppci_model||r._name||"Apple GPU",cores:lA(r.sppci_cores),metal:aA(r.spdisplays_mtlgpufamilysupport||r.spdisplays_metal),unified_memory:!0}))}catch{return[]}}function Vt(t,e,r={}){try{let n=Gc(t,e,{env:r.env||process.env});return _o(n.command,n.args,{encoding:"utf8",timeout:r.timeout||3e3,stdio:["ignore","pipe","ignore"],maxBuffer:256*1024,env:r.env||process.env,windowsHide:!0,windowsVerbatimArguments:n.windowsVerbatimArguments===!0})}catch{return null}}function sA(t){return{mlx:"MLX","mlx-metal":"MLX Metal",torch:"PyTorch",torchvision:"TorchVision",torchaudio:"TorchAudio",tensorflow:"TensorFlow",jax:"JAX",jaxlib:"JAXlib",onnxruntime:"ONNX Runtime","onnxruntime-gpu":"ONNX Runtime GPU",transformers:"Transformers",diffusers:"Diffusers",accelerate:"Accelerate",xformers:"xFormers",triton:"Triton",bitsandbytes:"bitsandbytes","llama-cpp-python":"llama.cpp Python",vllm:"vLLM","pytorch-lightning":"PyTorch Lightning",deepspeed:"DeepSpeed","cupy-cuda12x":"CuPy CUDA 12","mlx-whisper":"MLX Whisper","faster-whisper":"faster-whisper"}[t]||t}function oA(t){let e=Jc(Jc(t)),r=Ky(e);return r===".olivia-venv"?"olivia":r===".venv"?Ky(Jc(e))||".venv":/python/i.test(r)&&Jc(e).endsWith(Te("uv","python"))?`uv:${r}`:r||"system"}function aA(t){let e=String(t||"").match(/metal\s*([0-9.]+)/i);return e?`Metal ${e[1]}`:t?String(t):null}function cA(t){if(!Yc(t))return{};try{return Object.fromEntries(Qy(t,"utf8").split(/\r?\n/).filter(e=>e.includes("=")).map(e=>{let r=e.indexOf("=");return[e.slice(0,r),e.slice(r+1)]}))}catch{return{}}}function Wh(t){try{return Qy(t,"utf8").trim()||null}catch{return null}}function Zy(t){return String(t||"").replace(/^['\"]|['\"]$/g,"")||null}function mo(t){return Number.isFinite(t)&&t>0?Number(t):null}function lA(t){let e=String(t||"").match(/\d+/);return e?Number(e[0]):null}function dA(t,e){let r=new Set;return t.filter(n=>{let i=e(n);return r.has(i)?!1:(r.add(i),!0)})}var f4,zN,WN,HN,nb=v(()=>{Fh();ks();f4=3600*1e3,zN=["mlx","mlx-metal","torch","torchvision","torchaudio","tensorflow","jax","jaxlib","onnxruntime","onnxruntime-gpu","transformers","diffusers","accelerate","xformers","triton","bitsandbytes","llama-cpp-python","vllm","pytorch-lightning","deepspeed","cupy-cuda12x","mlx-whisper","faster-whisper"],WN=["import json, sys","from importlib import metadata",`names=${JSON.stringify(zN)}`,"packages={}","for name in names:"," try: packages[name]=metadata.version(name)"," except metadata.PackageNotFoundError: pass"," except Exception: pass","print(json.dumps({'version':sys.version.split()[0],'executable':sys.executable,'packages':packages}))"].join(`
|
|
177
|
+
`),HN=["import json","try:"," import torch"," devices=[]"," for index in range(torch.cuda.device_count()):"," props=torch.cuda.get_device_properties(index)"," devices.append({'name':props.name,'memory_bytes':props.total_memory,'cuda':torch.version.cuda})"," print(json.dumps(devices))","except Exception:"," print('[]')"].join(`
|
|
178
|
+
`);a(eb,"collectCapabilities");a(GN,"networkFingerprint");a(tb,"lanAddresses");a(JN,"collectCpu");a(VN,"collectOperatingSystem");a(YN,"collectDeviceModel");a(XN,"collectGpus");a(KN,"collectStorage");a(ZN,"collectSoftware");a(QN,"collectPythonEnvironments");a(rb,"pythonCandidates");a(qh,"addPythonVersions");a(zh,"discoverCommandPaths");a(eA,"collectTools");a(tA,"tryNvidia");a(rA,"tryPyTorchGpus");a(nA,"tryWindowsGpus");a(iA,"tryMacGpus");a(Vt,"tryCommand");a(sA,"frameworkDisplayName");a(oA,"pythonEnvironmentName");a(aA,"metalName");a(cA,"parseKeyValueFile");a(Wh,"readTextFile");a(Zy,"unquote");a(mo,"positiveNumber");a(lA,"numberFromText");a(dA,"dedupeBy")});function sb(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)){(!uA.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()}}var uA,ib,Hh=v(()=>{uA=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/,ib={environment_profile:{type:"string",minLength:1,maxLength:100,description:"Environment profile configured on the machine; its values stay there"}};a(sb,"validateEnvironmentProfiles")});import{posix as b4,win32 as v4,isAbsolute as hA}from"node:path";import{createHash as pA}from"node:crypto";function go(t,e){return pA("sha256").update(JSON.stringify(["workspace.v1",t,e])).digest("hex")}function Xc(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")||!hA(i))&&e(),r+=Buffer.byteLength(JSON.stringify([n,i])),r>256*1024&&e()}var ob,wo=v(()=>{a(go,"workspaceRevision");a(Xc,"validateWorkspaceAliases");ob={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"}}});import{isIP as fA}from"node:net";function Gh(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>ab)throw new Error(`Agent wake_targets cannot contain more than ${ab} machines`);let r={};for(let[n,i]of e){if(!_A(n)||!i||typeof i!="object"||Array.isArray(i))throw new Error(`Invalid Wake-on-LAN target: ${n}`);let s=gA(i.mac),o=i.broadcast_addresses??i.broadcasts;if(!Array.isArray(o)||o.length<1||o.length>cb)throw new Error(`Wake-on-LAN target ${n} needs 1-${cb} broadcast_addresses`);let c=[...new Set(o.map(d=>wA(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}function _A(t){return typeof t=="string"&&t.length>0&&t.length<=200&&!t.includes("\0")}function gA(t){if(typeof t!="string"||!mA.test(t))throw new Error("Wake-on-LAN MAC must contain six hexadecimal octets");return t.replaceAll("-",":").toLowerCase()}function wA(t,e){if(typeof t!="string"||fA(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}var ab,cb,mA,lb=v(()=>{ab=64,cb=8,mA=/^(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}$/i;a(Gh,"validateWakeTargets");a(_A,"validIdentity");a(gA,"normalizeMac");a(wA,"validateBroadcast")});import{createHash as yA,createPrivateKey as bA,createPublicKey as Vh,sign as vA,verify as EA}from"node:crypto";function pb(t){if(!yo(t)||t.schema!==db)throw F("Release manifest schema is invalid");let e={schema:db,release_id:OA(t.release_id),version:mb(t.version),protocol_version:Yt(t.protocol_version,"protocol_version",80),protocol_features:Kc(t.protocol_features||[],"protocol_features",256),migration_compatibility:kA(t.migration_compatibility),created_at:IA(t.created_at,"created_at"),artifacts:xA(t.artifacts)};if(e.protocol_version!==wi)throw F(`Release protocol must be ${wi}`);return e}function kA(t){if(t===void 0)return{hub_database_versions:[],agent_ledger_versions:[],previous_binary_versions:[],rollback_policy:"artifact_declared"};if(!yo(t))throw F("Release migration compatibility is invalid");let e=Yt(t.rollback_policy,"rollback_policy",80);if(!["artifact_declared","retain_database_reconcile","no_binary_rollback"].includes(e))throw F("Release rollback policy is invalid");return{hub_database_versions:Kc(t.hub_database_versions,"hub_database_versions",32),agent_ledger_versions:Kc(t.agent_ledger_versions,"agent_ledger_versions",32),previous_binary_versions:Kc(t.previous_binary_versions,"previous_binary_versions",32),rollback_policy:e}}function Kc(t,e,r){if(!Array.isArray(t)||t.length>r)throw F(`${e} must be a bounded array`);let n=t.map(i=>Yt(i,e,200));if(new Set(n).size!==n.length)throw F(`${e} contains duplicate values`);return n}function fb(t,e){let r=pb(t),n;try{n=bA(e)}catch{throw F("Release private key is not a valid signing key")}if(n.asymmetricKeyType!=="ed25519")throw F("Release signing key must be Ed25519");let i=Vh(n);return{schema:Jh,key_id:Yh(i),manifest:r,signature:vA(null,Buffer.from(Ee(r)),n).toString("base64url")}}function bo(t,e){if(!yo(t)||t.schema!==Jh||typeof t.signature!="string"||!/^[A-Za-z0-9_-]{86}$/.test(t.signature))throw F("Signed release envelope is invalid");let r=nt(e).key,n=Yh(r);if(t.key_id!==n)throw F("Release signing key does not match the pinned verification key","release_key_mismatch");let i=pb(t.manifest),s=Buffer.from(t.signature,"base64url");if(s.length!==64||!EA(null,Buffer.from(Ee(i)),r,s))throw F("Release manifest signature is invalid","release_signature_invalid");return{schema:Jh,key_id:n,manifest:i,signature:t.signature}}function nt(t){if(typeof t!="string"||!t.length||Buffer.byteLength(t)>16*1024||/-----BEGIN (?:ENCRYPTED )?PRIVATE KEY-----/.test(t))throw F("Release public key is invalid");let e;try{e=Vh(t)}catch{throw F("Release public key is invalid")}if(e.asymmetricKeyType!=="ed25519")throw F("Release verification key must be Ed25519");return{key:e,pem:e.export({type:"spki",format:"pem"}).toString(),key_id:Yh(e)}}function vo(t,e,r={}){let n=bo(t,e),i=r.platform||process.platform,s=r.arch||process.arch;if(!ub.has(i)||!hb.has(s))throw F("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 F("Release has no unique artifact for this platform and architecture","release_artifact_missing");let c=o[0],l=Zc(r.configVersion??1,1,1e3,"config_version");if(!c.compatibility.agent_config_versions.includes(l))throw F("Release artifact is incompatible with the installed agent configuration","release_config_incompatible");let d=mb(r.currentVersion),u=RA(n.manifest.version,d);if(u<0&&r.allowDowngrade!==!0)throw F("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"]}}function Yh(t){let r=(t?.type==="public"?t:Vh(t)).export({type:"spki",format:"der"});return`ed25519:${yA("sha256").update(r).digest("base64url")}`}function xA(t){if(!Array.isArray(t)||t.length<1||t.length>12)throw F("Release must contain 1-12 artifacts");let e=new Set;return t.map(r=>{if(!yo(r)||!yo(r.compatibility))throw F("Release artifact is invalid");let n=Yt(r.platform,"platform",20),i=Yt(r.arch,"arch",20),s=Yt(r.package_format,"package_format",20);if(!ub.has(n)||!hb.has(i)||!SA.get(n)?.has(s))throw F("Release artifact platform, architecture, or package format is unsupported");let o=`${n}:${i}`;if(e.has(o))throw F(`Duplicate release artifact target: ${o}`);e.add(o);let c=Yt(r.file_name,"file_name",255);if(c==="."||c===".."||/[\\/\0]/.test(c))throw F("Release artifact file_name must be a basename");let l;try{l=new URL(r.url)}catch{throw F("Release artifact URL is invalid")}if(l.protocol!=="https:"||l.username||l.password||l.search||l.hash)throw F("Release artifact URL must be credential-free HTTPS without a query or fragment");let d=Yt(r.sha256,"sha256",64);if(!/^[a-f0-9]{64}$/.test(d))throw F("Release artifact sha256 is invalid");let u=r.compatibility.agent_config_versions;if(!Array.isArray(u)||u.length<1||u.length>16)throw F("Release config compatibility is invalid");let h=[...new Set(u.map(p=>Zc(p,1,1e3,"agent_config_version")))].sort((p,f)=>p-f);if(typeof r.compatibility.ledger_rollback_safe!="boolean")throw F("Release rollback compatibility must be explicit");return{platform:n,arch:i,package_format:s,file_name:c,size:Zc(r.size,1,TA,"size"),sha256:d,url:l.toString(),node_runtime_version:Yt(r.node_runtime_version,"node_runtime_version",80),compatibility:{agent_config_versions:h,ledger_rollback_safe:r.compatibility.ledger_rollback_safe}}})}function RA(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}function mb(t){if(typeof t!="string"||!/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(t))throw F("Release version must be numeric major.minor.patch");return t}function OA(t){let e=Yt(t,"release_id",200);if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(e))throw F("release_id must be safe for private staging");return e}function IA(t,e){return Zc(t,1,Number.MAX_SAFE_INTEGER,e)}function Zc(t,e,r,n){let i=Number(t);if(!Number.isSafeInteger(i)||i<e||i>r)throw F(`${n} must be an integer from ${e} through ${r}`);return i}function Yt(t,e,r){if(typeof t!="string"||!t.length||t.length>r||t.includes("\0"))throw F(`${e} must be nonempty text of at most ${r} characters`);return t}function yo(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function F(t,e="invalid_release_manifest"){return new N(400,e,t)}var db,Jh,ub,SA,hb,TA,Xn=v(()=>{Hi();me();ye();db="interscale.release/v1",Jh="interscale.signed-release/v1",ub=new Set(["darwin","linux","win32"]),SA=new Map([["darwin",new Set(["pkg"])],["linux",new Set(["deb","tar.gz"])],["win32",new Set(["zip"])]]),hb=new Set(["arm64","x64"]),TA=100*1024**3;a(pb,"validateReleaseManifest");a(kA,"validateMigrationCompatibility");a(Kc,"validateTextList");a(fb,"signReleaseManifest");a(bo,"verifySignedRelease");a(nt,"releaseVerificationKey");a(vo,"releaseUpdatePlan");a(Yh,"releaseKeyId");a(xA,"validateArtifacts");a(RA,"compareVersions");a(mb,"releaseVersion");a(OA,"releaseId");a(IA,"timestamp");a(Zc,"integer");a(Yt,"text");a(yo,"plainObject");a(F,"invalid")});import{existsSync as Xh}from"node:fs";import{lstat as Eo,mkdir as NA,readdir as AA,realpath as Qc,rename as _b,rm as LA}from"node:fs/promises";import{createHash as CA,randomUUID as PA}from"node:crypto";import{isAbsolute as Kh,join as DA,relative as el,resolve as Et}from"node:path";function Eb(t){return{dev:String(t.dev),ino:String(t.ino),size:Number(t.size),mtime_ms:t.mtimeMs,birthtime_ms:t.birthtimeMs}}function bb(t,e){let r=typeof t=="string"?JSON.parse(t):t,n=Eb(e);return r.dev===n.dev&&r.ino===n.ino&&r.size===n.size&&r.mtime_ms===n.mtime_ms&&r.birthtime_ms===n.birthtime_ms}function vb(t,e){return Number(t.updated_at)-Number(e.updated_at)||t.id.localeCompare(e.id)}var rl,nl,$A,gb,wb,yb,tl,Zh=v(()=>{Qs();rl=30,nl=100,$A=360*60*1e3,gb=new Set(["completed","failed","cancelled"]),wb=new Set(["completed","failed","cancelled"]),yb=new Set([".interscale-cache",".interscale-cleanup",".interscale-parts"]),tl=class{static{a(this,"ReceivedCleanup")}constructor(e,r,n={}){this.config=e,this.ledger=r,this.now=n.now||(()=>Date.now()),this.limit=Number(e.receive_cleanup_max_entries_per_run??nl),this.running=null}status(){return{enabled:this.config.receive_retention_days!==0,receive_root:Et(this.config.receive_root),retention_days:Number(this.config.receive_retention_days??rl),interval_hours:$A/(3600*1e3),max_entries_per_run:this.limit,journal:this.ledger.receivedCleanupStatus()}}async preview(){return this.#r({verifyContent:!0})}run(){if(this.running)return this.running;let e=PA();return this.ledger.claimReceivedCleanupRun(e)?(this.running=this.#e(e).finally(()=>{this.ledger.releaseReceivedCleanupRun(e),this.running=null}),this.running):Promise.resolve({...this.status(),state:"busy"})}async#e(e){let r=this.status();if(!r.enabled)return{...r,state:"disabled",deleted:[],preserved:{},untracked:[]};let n=await this.#u();if(!n.ready)return{...r,state:"paused",code:n.code,deleted:[],preserved:{},untracked:[]};let i=[],s=[];for(let l of this.ledger.pendingReceivedCleanup(this.limit)){if(!this.ledger.renewReceivedCleanupRun(e))throw new Error("Received cleanup lock was lost");let d=await this.#s(l,n.root);s.push(d),d.state==="deleted"&&i.push(d)}let o=Math.max(0,this.limit-s.length),c=await this.#r({verifyContent:!1,rootState:n,limit:o});for(let l of c.candidates){if(!this.ledger.renewReceivedCleanupRun(e))throw new Error("Received cleanup lock was lost");let d=this.ledger.planReceivedCleanup({itemKey:l.item_key,ownerId:l.owner_id,role:l.role,path:l.path,quarantinePath:this.#p(n.root,l.item_key),expected:l.expected,expectedSha256:l.expected_sha256}),u=await this.#s(d,n.root);u.state==="deleted"&&i.push(u)}return{...c,state:"complete",recovered:s,deleted:i,deleted_bytes:i.reduce((l,d)=>l+Number(d.size||0),0)}}async#r({verifyContent:e,rootState:r=null,limit:n=this.limit}={}){let i=this.status();if(!i.enabled)return{...i,state:"disabled",candidates:[],preserved:{},untracked:[]};if(r||=await this.#u(),!r.ready)return{...i,state:"paused",code:r.code,candidates:[],preserved:{},untracked:[]};let s=this.now()-i.retention_days*24*60*60*1e3,o=this.ledger.transfersForReceivedCleanup(),c=this.ledger.downloadsForReceivedCleanup(),l=new Set(c.filter(_=>!wb.has(_.state)).flatMap(_=>[_.source_path,_.prepared_path]).filter(Boolean).map(_=>this.#d(r,_))),d=new Map;for(let _ of o){let w=this.#d(r,_.offer.destination_path),g=d.get(w)||[];g.push(_),d.set(w,g)}let u={recent:0,active:0,changed:0,directories:0,outside_root:0,symbolic_links:0,pinned:0,internal:0,already_processed:0,missing:0},h=[],p=new Set;for(let[_,w]of d){if(!this.#a(r.root,_)||_===r.root){u.outside_root+=1;continue}if(p.add(_),this.#h(r.root,_)){u.internal+=1;continue}let g=w.sort(vb).at(-1);if(g.state!=="completed"){u.active+=1;continue}if(g.updated_at>s){u.recent+=1;continue}if(g.offer.kind!=="file"){u.directories+=1;continue}if(l.has(_)){u.pinned+=1;continue}let y=`destination:${g.id}`;if(this.ledger.receivedCleanupItem(y)){u.already_processed+=1;continue}let E=await this.#c(r.root,_,g.offer.sha256,e);if(!E.ready){u[E.reason]=(u[E.reason]||0)+1;continue}h.push(this.#n(y,g.id,"destination",_,E,g.updated_at))}for(let _ of o){if(!gb.has(_.state)||_.updated_at>s)continue;let w=this.#d(r,_.part_path);if(p.add(w),!this.#a(Et(r.root,".interscale-parts"),w)){u.outside_root+=1;continue}let g=`partial:${_.id}`;if(this.ledger.receivedCleanupItem(g)){u.already_processed+=1;continue}let y=await this.#c(r.root,w,null,!1);if(!y.ready){u[y.reason]=(u[y.reason]||0)+1;continue}h.push(this.#n(g,_.id,"partial",w,y,_.updated_at))}h.sort((_,w)=>_.completed_at-w.completed_at||_.item_key.localeCompare(w.item_key));let f=h.slice(0,Math.max(0,n)),m=await this.#f(r.root,p);return{...i,state:"ready",cutoff:new Date(s).toISOString(),candidates:f,candidate_count:h.length,bounded:h.length>f.length,preserved:u,untracked:m}}#n(e,r,n,i,s,o){return{item_key:e,owner_id:r,role:n,path:i,size:s.metadata.size,completed_at:o,expected:Eb(s.metadata),expected_sha256:s.sha256}}async#c(e,r,n,i){let s;try{s=await Eo(r)}catch(c){if(c.code==="ENOENT")return{ready:!1,reason:"missing"};throw c}if(s.isSymbolicLink())return{ready:!1,reason:"symbolic_links"};if(!s.isFile())return{ready:!1,reason:"changed"};let o;try{o=await Qc(r)}catch(c){if(c.code==="ENOENT")return{ready:!1,reason:"missing"};throw c}return this.#a(e,o)?i&&n&&await Kr(r,{expected:s})!==n?{ready:!1,reason:"changed"}:{ready:!0,metadata:s,sha256:n}:{ready:!1,reason:"outside_root"}}async#s(e,r){let n=this.#l(e.path,r),i=this.#l(e.quarantine_path,r),s=Et(r,".interscale-cleanup");if(!this.#a(r,n)||!this.#a(s,i))return this.#i(e,"failed",{code:"cleanup_path_escape",message:"Cleanup path escaped managed received storage"});await NA(s,{recursive:!0,mode:448});try{let o=await Eo(s);if(o.isSymbolicLink()||!o.isDirectory()||await Qc(s)!==s)return this.#i(e,"failed",{code:"cleanup_quarantine_unsafe",message:"Cleanup quarantine is not a private directory inside received storage"});let c=Xh(n),l=Xh(i);if(c&&l)return this.#i(e,"failed",{code:"cleanup_recovery_ambiguous",message:"Both original and quarantine paths exist"});if(!c&&!l)return this.#i(e,e.state==="deleting"?"deleted":"missing");if(c){if(this.#t(n,e,r))return this.#i(e,"changed",{code:"cleanup_item_pinned",message:"The item became active before cleanup"});let u=await Eo(n);if(!bb(e.expected_json,u)||u.isSymbolicLink()||!u.isFile())return this.#i(e,"changed",{code:"cleanup_item_changed",message:"The item changed after cleanup was planned"});let h=await Qc(n);if(!this.#a(r,h))return this.#i(e,"failed",{code:"cleanup_path_escape",message:"Cleanup item resolves outside received storage"});await _b(n,i)}let d=await Eo(i);if(!bb(e.expected_json,d)||d.isSymbolicLink()||!d.isFile())return this.#o(e,n,i,"Cleanup item changed while it was quarantined");if(e.expected_sha256){let u;try{u=await Kr(i,{expected:d})}catch(h){return this.#o(e,n,i,h.message)}if(u!==e.expected_sha256)return this.#o(e,n,i,"Cleanup item no longer matches the delivered content")}return this.ledger.setReceivedCleanupState(e.item_key,"quarantined"),this.ledger.setReceivedCleanupState(e.item_key,"deleting"),await LA(i,{force:!1}),this.#i(e,"deleted")}catch(o){return o.code==="ENOENT"?this.#i(e,e.state==="deleting"?"deleted":"missing"):(this.ledger.noteReceivedCleanupError(e.item_key,o.code||"cleanup_failed",o.message),{item_key:e.item_key,role:e.role,path:e.path,size:JSON.parse(e.expected_json).size,state:this.ledger.receivedCleanupItem(e.item_key).state,code:o.code||"cleanup_failed",message:o.message})}}#t(e,r,n){if(r.role==="destination"){let o=this.ledger.transfersForReceivedCleanup().filter(c=>this.#l(c.offer.destination_path,n)===e).sort(vb).at(-1);return!o||o.id!==r.owner_id||o.state!=="completed"?!0:this.ledger.downloadsForReceivedCleanup().some(c=>!wb.has(c.state)&&[c.source_path,c.prepared_path].filter(Boolean).some(l=>this.#l(l,n)===e))}let i=this.ledger.transfersForReceivedCleanup().find(s=>s.id===r.owner_id);return!i||!gb.has(i.state)}async#o(e,r,n,i){try{if(Xh(r))throw Object.assign(new Error("Original path was replaced while cleanup inspected quarantine"),{code:"cleanup_recovery_ambiguous"});return await _b(n,r),this.#i(e,"changed",{code:"cleanup_item_changed",message:i})}catch(s){return this.#i(e,"failed",{code:s.code||"cleanup_restore_failed",message:s.message})}}#i(e,r,n={}){return this.ledger.setReceivedCleanupState(e.item_key,r,n),{item_key:e.item_key,role:e.role,path:e.path,size:JSON.parse(e.expected_json).size,state:r,...n.code?n:{}}}async#u(){let e=Et(this.config.receive_root),r;try{r=await Eo(e)}catch(n){return{ready:!1,code:n.code==="ENOENT"?"receive_root_missing":"receive_root_unavailable"}}return r.isSymbolicLink()||!r.isDirectory()?{ready:!1,code:"receive_root_unsafe"}:{ready:!0,requested:e,root:await Qc(e)}}#a(e,r){let n=el(e,r);return n===""||!n.startsWith("..")&&!Kh(n)}#h(e,r){let n=el(e,r).split(/[\\/]/)[0];return yb.has(n)}#d(e,r){let n=Et(e.requested),i=Et(r),s=el(n,i);return s===""||!s.startsWith("..")&&!Kh(s)?Et(e.root,s):i}#l(e,r){let n=Et(this.config.receive_root),i=Et(e),s=el(n,i);return s===""||!s.startsWith("..")&&!Kh(s)?Et(r,s):i}#p(e,r){return DA(e,".interscale-cleanup",CA("sha256").update(r).digest("hex"))}async#f(e,r){let n=[];for(let i of await AA(e,{withFileTypes:!0})){if(yb.has(i.name))continue;let s=Et(e,i.name);[...r].some(c=>this.#a(s,c)||this.#a(c,s))||n.push({path:s,type:i.isSymbolicLink()?"symbolic_link":i.isDirectory()?"directory":i.isFile()?"file":"other"})}return n.sort((i,s)=>i.path.localeCompare(s.path)).slice(0,100)}};a(Eb,"cleanupRevision");a(bb,"sameCleanupRevision");a(vb,"compareUpdated")});import{existsSync as Qh,mkdirSync as UA,readFileSync as ep,realpathSync as tp}from"node:fs";import{basename as jA,dirname as Sb,join as MA,resolve as Kn}from"node:path";function BA({serverUrl:t,node:e,tmuxSocket:r=null,maxJobLogBytes:n=100*1024*1024,maxConcurrentJobs:i=null,maxConcurrentGpuJobs:s=null,maxTransferBytesPerSecond:o=null,dataPort:c=Lm,receiveRoot:l,receiveRetentionDays:d=rl,receiveCleanupMaxEntriesPerRun:u=nl,pathAliases:h={},recipes:p={},libraries:f={},environmentProfiles:m={},environment:_={},wakeTargets:w={},releasePublicKey:g=null,desktopControl:y={}}){if(!e?.id||!e?.name)throw new Error("Enrolled node identity is required");let E=x();return{version:1,server_url:Ke(t),node_id:e.id,node_name:e.name,...r?{tmux_socket:String(r)}:{},max_job_log_bytes:Number(n),...i?{max_concurrent_jobs:Number(i)}:{},...s?{max_concurrent_gpu_jobs:Number(s)}:{},...o?{max_transfer_bytes_per_second:Number(o)}:{},data_port:Number(c),receive_root:Kn(l||Kn(E,"received")),receive_retention_days:Number(d),receive_cleanup_max_entries_per_run:Number(u),work_root:Kn(E,"work"),path_aliases:h,recipes:p,libraries:f,environment_profiles:m,environment:_,wake_targets:Gh(w),desktop_control:Tb(y),release_public_key:g===null?null:nt(g).pem}}function it(t,e=L()){np(t);let r=Kn(e);UA(Sb(r),{recursive:!0,mode:448});let n=Qh(r)?tp(r):MA(tp(Sb(r)),jA(r)),i=Zi.get(t);if(i&&i.requestedPath===r&&i.path!==n)throw new N(409,"agent_config_changed","Agent configuration path changed since it was loaded; reload before saving");if(i&&i.path===n&&(!Qh(n)||ep(n,"utf8")!==i.text))throw new N(409,"agent_config_changed","Agent configuration changed since it was loaded; reload before saving");return Rt(n,t),Zi.set(t,{path:n,requestedPath:r,text:ep(n,"utf8")}),e}function rp(t,{serverUrl:e,node:r,overrides:n={}}){let i={...BA({serverUrl:e,node:r}),...t?structuredClone(t):{},...n,server_url:Ke(e),node_id:r.id,node_name:r.name};return np(i),t&&Zi.has(t)&&Zi.set(i,Zi.get(t)),i}function X(t=L()){if(!Qh(t))throw new Error(`Agent configuration not found at ${t}. Run: interscale agent install`);let e=tp(t),r=ep(e,"utf8"),n=JSON.parse(r);return np(n),Zi.set(n,{path:e,requestedPath:Kn(t),text:r}),n}function np(t){if(!t||t.version!==1)throw new Error("Unsupported agent configuration version");if(Ke(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??=rl,!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??=nl,!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(sb(t.environment_profiles),Xc(t.path_aliases),t.wake_targets=Gh(t.wake_targets),t.desktop_control=Tb(t.desktop_control),t.release_public_key!==void 0&&t.release_public_key!==null?t.release_public_key=nt(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]=Kn(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]=Kn(i)}}function Tb(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}var Zi,So=v(()=>{Hh();wo();lb();ye();Z();Re();cr();Xn();me();Zh();Zi=new WeakMap;a(BA,"createAgentConfig");a(it,"saveAgentConfig");a(rp,"reenrolledAgentConfig");a(X,"loadAgentConfig");a(np,"validateAgentConfig");a(Tb,"validateDesktopControlConfig")});function il(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 N(e==="transfer_reclaimed"?410:409,e,r),{terminal:!0,retryable:!1,transferId:t.id||null,next_action:n})}var kb=v(()=>{ye();a(il,"transferOutcomeError")});function FA(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}function qA(t){return!Number.isSafeInteger(t?.cursor)||(t.events||[]).length>1e3||Buffer.byteLength(JSON.stringify(t))>2*1024*1024?null:t}function zA(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()}function WA(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}var sl,xb=v(()=>{ia();sl=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=zA(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 p=this.subscriptions.get(s);if(!p||p.cursor!==n||p.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(f){this.subscriptions.delete(s),this.remove(s,u),i?.removeEventListener("abort",u.abort),d(f)}}})}async connect(e){if(e?.throwIfAborted(),!(this.authenticated&&this.socket?.readyState===ut.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 ut.default(this.url,{perMessageDeflate:!1,maxPayload:2097152});this.socket=s;let o,c,l=0,d=null,u=a(f=>{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(f),this.fail(f),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 p=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(f){u(f)}}},this.heartbeatIntervalMs),o.unref()},"scheduleHeartbeat");s.once("open",()=>{if(this.socket===s)try{s.send(JSON.stringify({type:"authenticate",token:this.token}))}catch(f){u(f)}}),s.on("message",(f,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 w;try{w=JSON.parse(f.toString("utf8"))}catch{return _()}if(!w||typeof w!="object"||Array.isArray(w))return _();if(w.type==="error")return u(Object.assign(new Error(w.message||"Controller stream rejected request"),{code:w.code||"event_stream_error"}));if(w.type==="authenticated"&&!this.authenticated){clearTimeout(h),this.authenticated=!0,p(),n();return}if(!this.authenticated)return _();if(w.type==="update")return this.resolve(`${w.kind}:${w.id}`,w);if(w.type==="gap")return u(Object.assign(new Error(w.reason||"Controller event cursor gap"),{code:"event_gap"}));if(w.type==="pong"){d!==null&&w.request_id===d&&(clearTimeout(c),d=null,p());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 WA(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?FA(s,r):qA(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===ut.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<ut.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"}))}};a(FA,"mergeUpdates");a(qA,"boundedUpdate");a(zA,"toWebSocketUrl");a(WA,"waitForConnection")});import{randomUUID as sn}from"node:crypto";import{open as Lb,stat as Rb,realpath as HA}from"node:fs/promises";import{basename as GA}from"node:path";import{setTimeout as JA}from"node:timers/promises";async function VA(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),p=Date.now()+Number(i.cacheCheckTimeoutMs||1800*1e3);for(;Date.now()<(d?p:h);){Kt(i.signal);try{let g=await mr(c,{headers:{authorization:Ob(r,e.id,"GET",o)},signal:sp(i.signal,Number(i.connectTimeoutMs||2e3)),localAddress:i.localAddress});if(g.ok){let y=await g.json();if(d=y.state==="checking_cache",u=0,!d){l=y;break}}else{let y=await i.checkTransferFailure?.();if(y)throw y}}catch(g){if(ip(g,i.signal)||g?.terminal)throw g;if(u+=1,!d&&u>=3)break}await Zt(250,i.signal)}if(!l){let g=await i.checkTransferFailure?.();throw g||new Error(`Direct endpoint did not become ready: ${t}`)}let f=il(l);if(f){let g=await i.checkTransferFailure?.();throw g||f}let m=new Set(l.received_chunks||[]),_=l.state==="completed"&&m.size===e.total_chunks,w=await Lb(n,"r");try{let g=[];for(let y=0;y<e.total_chunks;y+=1)m.has(y)?i.onProgress?.({index:y,total:e.total_chunks,skipped:!0,route:"direct"}):g.push(y);await eo(g,Number(i.directConcurrency||4),async(y,E)=>{E.throwIfAborted();let S=y===e.total_chunks-1?e.size-y*e.chunk_size:e.chunk_size,k=i.transferBudget?await i.transferBudget.acquire(S*3+28,{priority:"foreground",signal:E,wireBytes:S+28}):()=>{};try{let $=Buffer.alloc(S);await to(w,$,y*e.chunk_size),E.throwIfAborted();let q=aw(r,e.id,y,$),V=`/v1/transfers/${encodeURIComponent(e.id)}/chunks/${y}`,j=await mr(`${s}${V}`,{method:"PUT",headers:{authorization:Ob(r,e.id,"PUT",V),"content-type":"application/octet-stream","content-length":String(q.length)},body:q,signal:sp(E,Number(i.chunkTimeoutMs||1800*1e3)),localAddress:i.localAddress});if(!j.ok){let C=await j.text();throw new Error(`Chunk ${y} failed with HTTP ${j.status}: ${C}`)}i.onProgress?.({index:y,total:e.total_chunks,bytes:S,skipped:!1,route:"direct"})}finally{k()}},i.signal)}finally{await w.close()}return{cacheHit:_}}function Ob(t,e,r,n){return`Interscale ${$n(t,e,r,n)}`}function Kt(t){if(!t?.aborted)return;let e=t.reason instanceof Error?t.reason:new Error("Transfer interrupted");throw e.code||="transfer_interrupted",e}function ip(t,e){return!!e?.aborted||t?.code==="transfer_interrupted"||t?.name==="AbortError"}function sp(t,e){let r=AbortSignal.timeout(Math.max(1,e));return t?AbortSignal.any([t,r]):r}async function Ib(t,e,r){let n=new Cn;try{let i=await HA(t);return await n.hash(i,{expected:e,signal:r})}finally{await n.close()}}function XA(t){let e={};for(let[r,n]of Object.entries(t.payload||{}))typeof n=="string"&&n.length>Nb?(e[r]=n.slice(0,Nb),e[`${r}_truncated`]=!0):e[r]=n;return{...t,payload:e}}function Zt(t,e){return JA(t,void 0,{signal:e})}function Ab(t){return Object.assign(new G("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.`})}function Xt(t){return new URLSearchParams(Object.entries(t).filter(([,e])=>e!=null))}var Je,Nb,YA,ol=v(()=>{ju();kb();Mu();cr();ye();me();Bi();me();_h();ks();lc();Bu();ic();xb();Je=class{static{a(this,"InterscaleClient")}constructor(e,r){this.serverUrl=e,this.token=r,this.eventClient=new sl(e,r)}request(e,r={}){return ne(this.serverUrl,e,{...r,token:this.token})}nodes(e={}){let r=Xt({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=Xt({limit:r.limit,cursor:r.cursor});return this.request(`/v1/nodes/${encodeURIComponent(e)}/workspaces?${n}`,{signal:r.signal})}nodeInventory(e,r={}){let n=Xt({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-${sn()}`,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 Zt(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=Xt({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=Xt({node:e||void 0,kind:r.kind,limit:r.limit,cursor:r.cursor});return this.request(`/v1/libraries?${n}`)}artifacts(e={}){let r=Xt({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=Xt({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||Cm,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=Xt({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 p=[],f=0;for(let _ of u.events){let w=XA(_);if(f+=JSON.stringify(w).length,p.length&&f>YA)break;p.push(w)}let m=p.length<u.events.length;return{next_since_seq:m?p.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:p}},"finish");for(;;){i?.throwIfAborted();let u=await this.rcSessionEvents(e,r,o,{signal:i}),h=u.events.filter(p=>p.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 Zt(s,l).catch(()=>{});continue}try{await this.eventClient.waitFor("rc_session",e,r,l)}catch(p){if(i?.aborted)throw p;p?.code==="invalid_subscription"&&(this.rcEventsUnsupported=!0),c.aborted||await Zt(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 Zt(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 G("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 G("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 Zt(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 Zt(1e3,n.signal)}}jobs(e=100,r={}){let n=Xt({limit:e,node:r.node,state:r.state,cursor:r.cursor});return this.request(`/v1/jobs?${n}`)}transfers(e={}){let r=Xt({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||sn()},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 G("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 G("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 p=JSON.stringify(h);p!==d&&(d=p,r(h))},"emit");for(;;){if(n.signal?.throwIfAborted(),o!==null&&Date.now()>=o)throw Ab(e);let h=o===null?null:new AbortController,p=o===null?null:Math.max(1,o-Date.now()),f=h?setTimeout(()=>h.abort(Ab(e)),p):null;f?.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(g){throw h?.signal.aborted&&!n.signal?.aborted?h.signal.reason:g}finally{f&&clearTimeout(f)}if(n.signal?.throwIfAborted(),u(_),n.signal?.throwIfAborted(),c.has(_.state))return _;let w=o===null?i:Math.min(i,Math.max(1,o-Date.now()));if(l){let g=new AbortController,y=setTimeout(()=>g.abort(),w);y.unref?.();let E=n.signal?AbortSignal.any([n.signal,g.signal]):g.signal;try{let S=await this.eventClient.waitFor("transfer",e,Number(_.event_cursor||0),E);if(n.signal?.throwIfAborted(),u(S.snapshot),n.signal?.throwIfAborted(),c.has(S.snapshot.state))return S.snapshot;continue}catch(S){if(n.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:S;if(g.signal.aborted)continue;l=!1}finally{clearTimeout(y)}}try{await Zt(w,n.signal)}catch(g){throw n.signal?.reason instanceof Error?n.signal.reason:g}}}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-${sn()}`,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(()=>(Ic(),gy))).prepareRunFiles(this,e,o,{...n,idempotencyKey:i});s=!0;let l={api_version:wi,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:wi,idempotency_key:n.idempotencyKey||`term-${sn()}`,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 G(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 p of h)p.type==="state"&&p.payload?.message&&(u=p.payload.message)}),new G("terminal_job_failed",d||u||`terminal job ${s.state}`)}if(!l)throw new G("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??sn(),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??sn(),...n.chunkSize?{chunk_size:Number(n.chunkSize)}:{}}})}createArtifactDownload(e,r={}){return this.request("/v1/downloads",{method:"POST",json:{artifact:e,request_id:r.requestId??sn(),...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={}){Kt(i.signal);let s=await Rb(e);if(!s.isFile())throw new Error("Transfer source must be a regular file or a prepared directory archive");let o=await Ib(e,s,i.signal);Kt(i.signal);let c=Number(i.chunkSize||sa),l=await this.request("/v1/transfers",{method:"POST",signal:i.signal,json:{target:r,kind:i.kind||"file",source_name:i.sourceName||GA(e),destination_path:n,size:s.size,sha256:o,chunk_size:c,overwrite:!!i.overwrite,request_id:i.requestId||sn()}}),{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={}){Kt(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 Rb(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 Ib(e,l,i.signal);if(Kt(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={}){Kt(o.signal);let c,l=new Set,d=a(async()=>{try{Kt(o.signal);let f=(await this.request(`/v1/transfers/${encodeURIComponent(r.id)}`,{signal:o.signal})).transfer;return il(f)}catch(f){if(ip(f,o.signal))throw f;return null}},"checkTransferFailure"),u=a(async f=>{for(let m of await uc(Ti(f),{nodeId:r.target_node_id,id:r.id,token:n,signal:o.signal})){let _=m.url,w=`${_}|${m.localAddress||""}`;if(l.has(w))continue;l.add(w);let g=!1;try{o.onLinkAttempt?.(m);let y=await VA(_,r,n,e,{...o,localAddress:m.localAddress,checkTransferFailure:d});return g=!0,Kt(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:y.cacheHit?"cache":"direct",candidate:_,link:{kind:m.kind,interface:m.interface,local_address:m.localAddress}}}catch(y){if(dc(r.target_node_id,m),g||ip(y,o.signal)||y?.terminal)throw y;let E=await d();if(E)throw E;c=y}}return null},"tryCandidates"),h=await u(i);if(h)return h;if(r.route==="direct"&&o.mdns!==!1){let f=await Ec(r.target_node_id,{signal:o.signal,timeoutMs:o.mdnsTimeoutMs}),m=await u(f);if(m)return{...m,discovered_by:"mdns"}}let p=await d();if(p)throw p;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={}){Kt(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 Lb(e,"r");try{await eo(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,p=Buffer.alloc(h);await to(c,p,u*i.chunk_size),d.throwIfAborted();let f=await fetch(l.url,{method:"PUT",headers:{"content-length":String(p.length)},body:p,signal:sp(d,Number(n.chunkTimeoutMs||1800*1e3))});if(!f.ok)throw new Error(`R2 part ${l.part_number} failed with HTTP ${f.status}`);let m=f.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:p.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),Kt(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=il(c);if(l)throw l;await Zt(1e3,o)}}catch(c){throw i.signal.aborted&&!r.signal?.aborted?Object.assign(new G("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(ws.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(),ws.has(c.snapshot.state))continue}catch(c){if(r.signal?.aborted)throw c;await Zt(Number(r.legacyIntervalMs||1e3),r.signal)}}}}};a(VA,"uploadDirect");a(Ob,"transferAuthorization");a(Kt,"throwIfAborted");a(ip,"isTransferInterruption");a(sp,"combinedSignal");a(Ib,"hashFile");Nb=2e3,YA=6e3;a(XA,"compactRcEvent");a(Zt,"delay");a(Ab,"transferFollowTimeout");a(Xt,"queryParameters")});var jb={};K(jb,{agentServiceStatus:()=>nL,installAgentService:()=>eL,restartAgentService:()=>rL,uninstallAgentService:()=>tL});import{existsSync as Db,mkdirSync as Cb,rmSync as KA,writeFileSync as ZA}from"node:fs";import{dirname as al,resolve as op}from"node:path";import{execFileSync as $b,spawnSync as Ub}from"node:child_process";import{fileURLToPath as Pb}from"node:url";import{homedir as QA}from"node:os";function eL(t={}){let e=t.runtimeRoot||op(al(Pb(import.meta.url)),"..",".."),r=jc(e);if(r)return r;let n=ap(),i=t.entry||op(al(Pb(import.meta.url)),"..","bin","interscale-agent.mjs"),s=xt();Cb(al(n),{recursive:!0,mode:448}),Cb(al(s),{recursive:!0,mode:448}),ZA(n,iL({node:t.node||process.execPath,agentEntry:i,logPath:s}),{mode:384});let o=`gui/${process.getuid()}`;return Ji({domain:o,label:Lr,plist:n}),$b("/bin/launchctl",["kickstart","-k",`${o}/${Lr}`],{stdio:"ignore"}),{label:Lr,plist_path:n,log_path:s}}function tL(){let t=Bc();if(t)return t;let e=ap(),r=`gui/${process.getuid()}`;return Ub("/bin/launchctl",["bootout",r,e],{stdio:"ignore"}),Db(e)&&KA(e),{label:Lr,removed:!0}}function rL(){let t=Mc();if(t)return t;let e=`gui/${process.getuid()}`;return $b("/bin/launchctl",["kickstart","-k",`${e}/${Lr}`],{stdio:["ignore","pipe","pipe"]}),{restarted:!0,label:Lr,loaded:!0}}function nL(){let t=tn();if(t)return t;let e=`gui/${process.getuid()}`,r=Ub("/bin/launchctl",["print",`${e}/${Lr}`],{encoding:"utf8"});return{installed:Db(ap()),loaded:r.status===0,detail:r.status===0?sL(r.stdout):r.stderr.trim()}}function ap(){return op(QA(),"Library","LaunchAgents",`${Lr}.plist`)}function iL({node:t,agentEntry:e,logPath:r}){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
179
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
180
|
+
<plist version="1.0">
|
|
181
|
+
<dict>
|
|
182
|
+
<key>Label</key><string>${Ar(Lr)}</string>
|
|
183
|
+
<key>ProgramArguments</key>
|
|
184
|
+
<array>
|
|
185
|
+
<string>${Ar(t)}</string>
|
|
186
|
+
<string>${Ar(e)}</string>
|
|
187
|
+
</array>
|
|
188
|
+
<key>RunAtLoad</key><true/>
|
|
189
|
+
<key>KeepAlive</key>
|
|
190
|
+
<dict><key>SuccessfulExit</key><false/></dict>
|
|
191
|
+
<key>ProcessType</key><string>Standard</string>
|
|
192
|
+
<key>ThrottleInterval</key><integer>10</integer>
|
|
193
|
+
<key>StandardOutPath</key><string>${Ar(r)}</string>
|
|
194
|
+
<key>StandardErrorPath</key><string>${Ar(r)}</string>
|
|
195
|
+
<key>WorkingDirectory</key><string>${Ar(x())}</string>
|
|
196
|
+
<key>EnvironmentVariables</key>
|
|
197
|
+
<dict><key>PATH</key><string>${Ar(process.env.PATH||"/usr/local/bin:/usr/bin:/bin")}</string>
|
|
198
|
+
<key>INTERSCALE_HOME</key><string>${Ar(x())}</string>
|
|
199
|
+
<key>INTERSCALE_AGENT_CONFIG</key><string>${Ar(L())}</string></dict>
|
|
200
|
+
</dict>
|
|
201
|
+
</plist>
|
|
202
|
+
`}function sL(t){let e=t.match(/\bpid = (\d+)/)?.[1],r=t.match(/\bstate = ([^\n]+)/)?.[1]?.trim(),n=t.match(/\blast exit code = ([^\n]+)/)?.[1]?.trim();return{pid:e?Number(e):null,state:r||null,last_exit:n||null}}function Ar(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Lr,Mb=v(()=>{Z();Xi();Ac();Lr="com.interscale.agent";a(eL,"installAgentService");a(tL,"uninstallAgentService");a(rL,"restartAgentService");a(nL,"agentServiceStatus");a(ap,"launchAgentPath");a(iL,"renderPlist");a(sL,"parseLaunchctl");a(Ar,"escapeXml")});var Hb={};K(Hb,{ADMIN_CONTROL_TASK_NAME:()=>on,adminControlInstalled:()=>To,adminControlLauncherPath:()=>pp,adminControlTaskXml:()=>Fb,disableAdminControl:()=>gL,enableAdminControl:()=>_L,launchElevatedHost:()=>mL,renderAdminControlLauncher:()=>qb,runAdminControlTask:()=>zb});import{EventEmitter as oL}from"node:events";import{spawnSync as cl}from"node:child_process";import{existsSync as aL,mkdirSync as Bb,rmSync as cL,writeFileSync as cp}from"node:fs";import{createServer as lL}from"node:net";import{tmpdir as dL}from"node:os";import{dirname as lp,join as hp,win32 as uL}from"node:path";import{fileURLToPath as hL}from"node:url";function pp(t=x()){return hp(t,"startup","InterscaleDesktopHost.vbs")}function Fb({userSid:t,launcher:e}){let r=a(n=>String(n).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),"x");return`<?xml version="1.0" encoding="UTF-16"?>
|
|
203
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
204
|
+
<RegistrationInfo><Description>Starts the Interscale desktop host with this account's administrator rights, so remote input reaches admin windows such as Task Manager.</Description></RegistrationInfo>
|
|
205
|
+
<Principals><Principal id="Author"><UserId>${r(t)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals>
|
|
206
|
+
<Settings>
|
|
207
|
+
<MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy>
|
|
208
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
209
|
+
<IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings>
|
|
210
|
+
<AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden>
|
|
211
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority>
|
|
212
|
+
</Settings>
|
|
213
|
+
<Actions Context="Author"><Exec><Command>wscript.exe</Command><Arguments>//B //Nologo "${r(e)}"</Arguments></Exec></Actions>
|
|
214
|
+
</Task>
|
|
215
|
+
`}function qb({node:t,supervisor:e,pipe:r,token:n}){return['Set shell = CreateObject("WScript.Shell")',`shell.Run "${[t,e,r,n].map(s=>`""${String(s).replaceAll('"','""')}""`).join(" ")}", 0, False`,""].join(`\r
|
|
216
|
+
`)}function To(t=cl){return t("schtasks.exe",["/Query","/TN",on],{stdio:"ignore",windowsHide:!0,timeout:15e3}).status===0}function zb(t,{execute:e=cl,launcher:r=pp()}={}){if(Bb(lp(r),{recursive:!0,mode:448}),cp(r,qb(t)),e("schtasks.exe",["/Run","/I","/TN",on],{encoding:"utf8",windowsHide:!0,timeout:15e3}).status!==0)throw Zn("desktop_admin_control_unavailable","Windows did not start the Interscale desktop host task")}async function mL(t,e,r={},n={}){let{trigger:i=zb,timeoutMs:s=fL,node:o=process.execPath,supervisor:c=pL}=n,l=Uu(18),d=yL(Uu(9)),u=lL();await new Promise((f,m)=>{u.once("error",m),u.listen(d,f)});let h=null,p;try{let f=new Promise((_,w)=>{p=setTimeout(()=>w(Zn("desktop_admin_control_unavailable","The Interscale desktop host task did not start in time")),s),u.on("connection",g=>{if(h)return g.destroy();let y=new dp(g,l);y.once("hello",()=>{if(h)return g.destroy();h=y,_(y)})})});await i({node:o,supervisor:c,pipe:d,token:l});let m=await f;return clearTimeout(p),await m.start({executable:t,args:e,cwd:r.cwd,env:r.env},s),m}catch(f){throw h?.socket.destroy(),f?.code==="desktop_admin_control_unavailable"?f:Zn("desktop_admin_control_unavailable","Interscale could not start its desktop host with admin control")}finally{clearTimeout(p),u.close()}}function _L({root:t=x(),execute:e=cl,systemRoot:r=process.env.SystemRoot||"C:\\Windows"}={}){let n=wL(e,r),i=pp(t);Bb(lp(i),{recursive:!0,mode:448}),aL(i)||cp(i,`' Rewritten by the Interscale agent before each start.\r
|
|
217
|
+
`);let s=hp(lp(i),"InterscaleDesktopHostTask.xml");cp(s,Fb({userSid:n,launcher:i}));try{Wb(`Register-ScheduledTask -TaskName ${up(on)} -Xml ([IO.File]::ReadAllText(${up(s)})) -Force | Out-Null`,e)}finally{cL(s,{force:!0})}if(!To(e))throw Zn("admin_control_not_visible","Windows registered the task, but this account cannot start it");return{enabled:!0,task:on,user_sid:n,next_action:"Reconnect to this machine's desktop; the host restarts with admin control"}}function gL({execute:t=cl}={}){return To(t)?(Wb(`Unregister-ScheduledTask -TaskName ${up(on)} -Confirm:$false`,t),{enabled:!1,removed:!0}):{enabled:!1,removed:!1}}function Wb(t,e){let n=`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ArgumentList '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','${Buffer.from(`$ErrorActionPreference = 'Stop'; ${t}`,"utf16le").toString("base64")}'; exit $p.ExitCode`,i=e("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,timeout:10*6e4});if(i.status!==0){let s=String(i.stderr||i.stdout||"").trim().split(/\r?\n/)[0];throw Zn("admin_approval_refused",`Windows did not approve admin control (${s||`exit ${i.status}`})`)}}function wL(t,e){let r=t(uL.join(e,"System32","whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8",windowsHide:!0,timeout:15e3}),n=String(r.stdout||"").match(/S-1-5-[0-9-]+/)?.[0];if(r.status!==0||!n)throw Zn("admin_control_user_unknown","Interscale could not identify this Windows account");return n}function yL(t){return process.platform==="win32"?`\\\\.\\pipe\\interscale-desktop-host-${t}`:hp(dL(),`isdh-${t}.sock`)}function up(t){return`'${String(t).replaceAll("'","''")}'`}function Zn(t,e){return Object.assign(new Error(e),{code:t})}var on,pL,fL,dp,fp=v(()=>{Bi();Z();on="Interscale Desktop Host",pL=hL(new URL("./elevated-host-supervisor.mjs",import.meta.url)),fL=1e4;a(pp,"adminControlLauncherPath");a(Fb,"adminControlTaskXml");a(qb,"renderAdminControlLauncher");a(To,"adminControlInstalled");a(zb,"runAdminControlTask");a(mL,"launchElevatedHost");dp=class extends oL{static{a(this,"ElevatedChild")}constructor(e,r){super(),this.socket=e,this.token=r,this.greeted=!1,this.pid=void 0,this.exitCode=null,this.signalCode=null,this.elevated=!0;let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("close",()=>this.lost()),e.on("data",i=>{if(n+=i,n.length>64*1024)return e.destroy();let s;for(;(s=n.indexOf(`
|
|
218
|
+
`))>=0;){let o=n.slice(0,s);n=n.slice(s+1);try{this.handle(JSON.parse(o))}catch{return e.destroy()}}})}handle(e){if(!this.greeted)return e?.hello!==this.token?this.socket.destroy():(this.greeted=!0,this.emit("hello"));Number.isSafeInteger(e?.spawned)&&e.spawned>0&&!this.pid?(this.pid=e.spawned,this.emit("spawned")):typeof e?.error=="string"?this.emit("start-failed",e.error):e?.exit&&this.finish(Number.isSafeInteger(e.exit.code)?e.exit.code:null,typeof e.exit.signal=="string"?e.exit.signal:null)}start(e,r){return new Promise((n,i)=>{let s=a(()=>{l(),i(Zn("desktop_admin_control_unavailable","Interscale's admin desktop host did not start"))},"fail"),o=a(()=>{l(),n()},"done"),c=setTimeout(s,r),l=a(()=>{clearTimeout(c),this.off("spawned",o),this.off("start-failed",s),this.socket.off("close",s)},"cleanup");this.once("spawned",o),this.once("start-failed",s),this.socket.once("close",s),this.send({start:e})||s()})}send(e){return this.socket.destroyed||!this.socket.writable?!1:(this.socket.write(`${JSON.stringify(e)}
|
|
219
|
+
`),!0)}kill(e="SIGTERM"){return this.exitCode!==null||this.signalCode!=null?!1:this.send({kill:String(e)})}finish(e,r){this.exitCode!==null||this.signalCode!=null||(this.exitCode=e,this.signalCode=e===null?r||"SIGKILL":null,this.socket.destroy(),this.emit("exit",this.exitCode,this.signalCode))}lost(){if(!this.pid||this.exitCode!==null||this.signalCode!=null)return;let e=setInterval(()=>{try{process.kill(this.pid,0);return}catch(r){if(r.code==="EPERM")return}clearInterval(e),this.finish(null,"SIGKILL")},250);e.unref?.()}};a(_L,"enableAdminControl");a(gL,"disableAdminControl");a(Wb,"runElevated");a(wL,"currentUserSid");a(yL,"supervisorPipePath");a(up,"psLiteral");a(Zn,"coded")});var vp={};K(vp,{BOOT_TASK_NAME:()=>xo,agentServiceStatus:()=>OL,installAgentService:()=>kL,packagedDesktopPath:()=>_p,registerWindowsBootTask:()=>IL,renderCliCommand:()=>r0,renderStartupCommand:()=>mp,renderStartupVbs:()=>gp,renderStopLoopsScript:()=>t0,renderTrayCommand:()=>n0,repointDesktopEntry:()=>e0,restartAgentService:()=>xL,uninstallAgentService:()=>RL,unregisterWindowsBootTask:()=>Qb,windowsBootTaskXml:()=>Zb});import{existsSync as hl,mkdirSync as Gb,readFileSync as bL,rmSync as ll,writeFileSync as Qn}from"node:fs";import{dirname as Jb,join as ke,resolve as vL,win32 as Vb}from"node:path";import{spawn as EL,spawnSync as er}from"node:child_process";import{fileURLToPath as SL}from"node:url";async function kL(){let t=es(),e=vL(Jb(SL(import.meta.url)),"..");Gb(t,{recursive:!0,mode:448}),Gb(Jb(xt()),{recursive:!0,mode:448});let r=ke(t,`${Qt}.cmd`),n=ke(t,`${Qt}.vbs`);Qn(r,mp({node:process.execPath,entry:ke(e,"bin","interscale-agent.mjs"),config:L(),log:xt()})),Qn(n,gp(r)),Qn(ke(t,`${Kb}.cmd`),mp({node:process.execPath,entry:ke(e,"bin","interscale-agent.mjs"),config:L(),log:xt(),args:["--boot"]}));let i=ke(t,"interscale.cmd");Qn(i,r0({node:process.execPath,entry:ke(e,"bin","interscale.mjs")}));let s=ke(t,`${Qi}.cmd`),o=ke(t,`${Qi}.vbs`);Qn(s,n0({script:ke(e,"windows","tray.ps1"),desktop:_p(e),cli:i,icon:ke(e,"assets","interscale.ico"),log:xt(),pid:yi()})),Qn(o,gp(s));let c=e0(_p(e));if(Yb(Qt,n),Yb(Qi,o),yp(),bp(yi()),wp(n),wp(o),!await i0())throw new Error(`Agent auto-start was registered, but the agent did not start. Check ${xt()}`);return{service:Qt,mode:"per-user-autostart",elevated:!1,startup:pl,tray:{registered:!0,running:await s0(yi(),5e3)},desktop_entry:c,log:xt(),running:!0}}async function xL(){let t=ke(es(),`${Qt}.vbs`);if(!hl(t))throw new Error("Interscale auto-start is not installed");if(yp(),wp(t),!await i0())throw new Error(`Agent did not restart. Check ${xt()}`);return{restarted:!0,running:!0,elevated:!1}}function RL(){Qb(),er("schtasks.exe",["/Delete","/TN",on,"/F"],{stdio:"ignore",windowsHide:!0}),Xb(Qt),Xb(Qi);let t=yp(),e=bp(yi());return ll(es(),{recursive:!0,force:!0}),{service:Qt,removed:!dl(Qt)&&!dl(Qi),stopped:t,tray_stopped:e,elevated:!1}}function OL(){let t=dl(Qt),e=ul(aa()),r=!!(e&&ko(e)),n=ul(yi()),i=NL();return{installed:t,loaded:r,mode:"per-user-autostart",boot:i,admin_control:To()?{installed:!0}:{installed:!1,next_action:"To control admin windows such as Task Manager remotely, run: interscale agent enable-admin-control"},elevated:!1,pid:r?e:null,tray:{installed:dl(Qi),running:!!(n&&ko(n)),pid:n&&ko(n)?n:null},detail:t?r?"Per-user auto-start registered; agent is running":"Per-user auto-start registered; agent is not running":"Per-user auto-start is not registered"}}function mp({node:t,entry:e,config:r,log:n,args:i=[]}){return["@echo off",`set "INTERSCALE_AGENT_CONFIG=${st(r)}"`,":run",`"${st(t)}" "${st(e)}"${i.map(s=>` ${s}`).join("")} >> "${st(n)}" 2>&1`,'if "%ERRORLEVEL%"=="0" exit /b 0',"ping -n 6 127.0.0.1 >nul","goto run",""].join(`\r
|
|
220
|
+
`)}function Zb({user:t,command:e}){let r=a(n=>String(n).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),"x");return`<?xml version="1.0" encoding="UTF-16"?>
|
|
221
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
222
|
+
<RegistrationInfo><Description>Starts the Interscale agent while nobody is signed in.</Description></RegistrationInfo>
|
|
223
|
+
<Triggers><TimeTrigger><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled>
|
|
224
|
+
<Repetition><Interval>PT1M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger></Triggers>
|
|
225
|
+
<Principals><Principal id="Author"><UserId>${r(t)}</UserId><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
|
|
226
|
+
<Settings>
|
|
227
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
228
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
229
|
+
<StartWhenAvailable>true</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
230
|
+
<IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings>
|
|
231
|
+
<AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden>
|
|
232
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority>
|
|
233
|
+
</Settings>
|
|
234
|
+
<Actions Context="Author"><Exec><Command>cmd.exe</Command><Arguments>/d /c "${r(e)}"</Arguments></Exec></Actions>
|
|
235
|
+
</Task>
|
|
236
|
+
`}function IL({password:t,user:e=`${process.env.USERDOMAIN}\\${process.env.USERNAME}`,execute:r=er}={}){let n=ke(es(),`${Kb}.cmd`);if(!hl(n))throw new Error("Install the Interscale agent before enabling it at boot");let i=ke(es(),"InterscaleBootTask.xml");Qn(i,Zb({user:e,command:n}));let o=r("powershell.exe",["-NoProfile","-NonInteractive","-Command","$password = [Console]::In.ReadLine(); Register-ScheduledTask -TaskName $env:INTERSCALE_TASK -Xml ([IO.File]::ReadAllText($env:INTERSCALE_TASK_XML)) -User $env:INTERSCALE_TASK_USER -Password $password -Force | Out-Null"],{input:`${t}
|
|
237
|
+
`,encoding:"utf8",windowsHide:!0,timeout:6e4,env:{...process.env,INTERSCALE_TASK:xo,INTERSCALE_TASK_XML:i,INTERSCALE_TASK_USER:e}});if(ll(i,{force:!0}),o.status!==0){let c=String(o.stderr||o.stdout||"").trim().split(/\r?\n/)[0];throw Object.assign(new Error(`Windows refused the boot task (${c||`exit ${o.status}`}). Check the Windows account password; a Microsoft account uses its online password, not the PIN.`),{code:"boot_task_refused"})}return{task:xo,user:e,command:n}}function Qb(t=er){t("schtasks.exe",["/Delete","/TN",xo,"/F"],{stdio:"ignore",windowsHide:!0})}function NL(t=er){let e=t("powershell.exe",["-NoProfile","-NonInteractive","-Command",`$i = Get-ScheduledTaskInfo -TaskName '${xo}' -ErrorAction Stop; [string]$i.LastTaskResult`],{encoding:"utf8",windowsHide:!0,timeout:15e3});if(e.status!==0)return{installed:!1};let r=Number(String(e.stdout).trim());return{installed:!0,last_result:r,...r===TL?{next_action:"The Windows password changed; run: interscale agent enable-boot"}:{}}}function e0(t,{execute:e=er,exists:r=hl}={}){if(!r(t))return{repointed:!1,reason:"no_desktop_app"};let i=[`$exe = ${`'${String(t).replaceAll("'","''")}'`}`,"$shell = New-Object -ComObject WScript.Shell","$folders = @((Join-Path $env:APPDATA 'Microsoft\\Windows\\Start Menu\\Programs'), [Environment]::GetFolderPath('Desktop'), (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar'))","foreach ($folder in $folders) { Get-ChildItem -LiteralPath $folder -Filter '*.lnk' -Recurse -ErrorAction SilentlyContinue | ForEach-Object { $shortcut = $shell.CreateShortcut($_.FullName); if ($shortcut.TargetPath -match '\\\\Interscale\\.exe$' -and $shortcut.TargetPath -ne $exe) { $shortcut.TargetPath = $exe; $shortcut.WorkingDirectory = Split-Path (Split-Path $exe); $shortcut.IconLocation = $exe + ',0'; $shortcut.Save() } } }","$key = 'HKCU:\\Software\\Classes\\interscale\\shell\\open\\command'",`if (Test-Path $key) { $value = [string](Get-Item $key).GetValue(''); if ($value -match 'Interscale\\.exe' -and -not $value.Contains($exe)) { Set-Item -Path $key -Value ('"' + $exe + '" -- "%1"') } }`].join(`
|
|
238
|
+
`);return{repointed:e("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",i],{windowsHide:!0,timeout:2e4,encoding:"utf8"}).status===0,desktop:t}}function _p(t){return Vb.join(Vb.dirname(t),"desktop","Interscale.exe")}function t0(t){return[`$loops = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'cmd.exe' -and $_.CommandLine -and $_.CommandLine.ToLowerInvariant().Contains(${`'${String(t).toLowerCase().replaceAll("'","''")}'`}) })`,"foreach ($loop in $loops) { taskkill.exe /PID $loop.ProcessId /T /F | Out-Null }","$loops.Count"].join("; ")}function r0({node:t,entry:e}){return["@echo off",`"${st(t)}" "${st(e)}" %*`,""].join(`\r
|
|
239
|
+
`)}function n0({script:t,desktop:e,cli:r,icon:n,log:i,pid:s}){return["@echo off",`powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${st(t)}" -CliPath "${st(r)}" -DesktopPath "${st(e)}" -IconPath "${st(n)}" -LogPath "${st(i)}" -PidPath "${st(s)}"`,""].join(`\r
|
|
240
|
+
`)}function gp(t){return['Set shell = CreateObject("WScript.Shell")',`shell.Run Chr(34) & "${LL(t)}" & Chr(34), 0, False`,""].join(`\r
|
|
241
|
+
`)}function es(){return ke(x(),"startup")}function Yb(t,e){let r=er("reg.exe",["ADD",pl,"/v",t,"/t","REG_SZ","/d",`wscript.exe "${e}"`,"/f"],{encoding:"utf8",windowsHide:!0});if(r.status!==0)throw new Error(`Could not register ${t} per-user auto-start: ${r.stderr||r.stdout}`)}function Xb(t){er("reg.exe",["DELETE",pl,"/v",t,"/f"],{stdio:"ignore",windowsHide:!0})}function dl(t){return er("reg.exe",["QUERY",pl,"/v",t],{stdio:"ignore",windowsHide:!0}).status===0}function wp(t){EL("wscript.exe",[t],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}function ul(t){if(!hl(t))return null;let e=Number(bL(t,"utf8").trim());return Number.isInteger(e)&&e>0?e:null}function ko(t){try{return process.kill(t,0),!0}catch{return!1}}function yp(){let t=AL();return bp(aa())||t}function AL(){let t=ke(es(),`${Qt}.cmd`),e=er("powershell.exe",["-NoProfile","-NonInteractive","-Command",t0(t)],{encoding:"utf8",windowsHide:!0,timeout:3e4});return e.status===0&&Number(String(e.stdout||"").trim())>0}function bp(t){let e=ul(t);if(!e||!ko(e))return ll(t,{force:!0}),!1;let r=er("taskkill.exe",["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});return r.status===0&&ll(t,{force:!0}),r.status===0}async function i0(){return s0(aa(),5e3)}async function s0(t,e){let r=Date.now()+e;for(;Date.now()<r;){let n=ul(t);if(n&&ko(n))return!0;await new Promise(i=>setTimeout(i,100))}return!1}function st(t){return String(t).replace(/%/g,"%%").replace(/\"/g,'""')}function LL(t){return String(t).replace(/\"/g,'""')}var Qt,Kb,xo,TL,Qi,pl,Ep=v(()=>{fp();Z();Qt="InterscaleAgent",Kb="InterscaleBoot",xo="Interscale Agent",TL=2147943726,Qi="InterscaleTray",pl=String.raw`HKCU\Software\Microsoft\Windows\CurrentVersion\Run`;a(kL,"installAgentService");a(xL,"restartAgentService");a(RL,"uninstallAgentService");a(OL,"agentServiceStatus");a(mp,"renderStartupCommand");a(Zb,"windowsBootTaskXml");a(IL,"registerWindowsBootTask");a(Qb,"unregisterWindowsBootTask");a(NL,"bootTaskStatus");a(e0,"repointDesktopEntry");a(_p,"packagedDesktopPath");a(t0,"renderStopLoopsScript");a(r0,"renderCliCommand");a(n0,"renderTrayCommand");a(gp,"renderStartupVbs");a(es,"startupDirectory");a(Yb,"registerStartup");a(Xb,"deleteStartup");a(dl,"isStartupRegistered");a(wp,"startLauncher");a(ul,"readPid");a(ko,"isProcessAlive");a(yp,"stopAgent");a(AL,"stopAgentLoops");a(bp,"stopProcess");a(i0,"waitForAgentStart");a(s0,"waitForProcess");a(st,"escapeCmdValue");a(LL,"escapeVbsString")});import{chmodSync as d0,existsSync as o0,mkdirSync as a0,mkdtempSync as CL,readFileSync as c0,renameSync as PL,rmSync as Sp,writeFileSync as Tp}from"node:fs";import{tmpdir as DL}from"node:os";import{join as l0}from"node:path";import{spawnSync as ml}from"node:child_process";async function u0(t){if(process.getuid?.()!==0)throw new Error("Caddy configuration requires root");if(new URL(t.public_url).protocol!=="https:")throw new Error("Caddy automatic HTTPS requires an https:// public URL");if(!BL(t.listen.host))throw new Error("Caddy mode requires the Interscale server to listen on localhost only");await UL(),a0(xp,{recursive:!0,mode:493}),a0("/etc/caddy",{recursive:!0,mode:493});let r=o0(ts)?c0(ts,"utf8"):"",n=o0(rs)?c0(rs,"utf8"):null,i=ML(r)?r:`${r.replace(/\s*$/,"")}
|
|
242
|
+
|
|
243
|
+
${kp}
|
|
244
|
+
`;try{fl(ts,i||`${kp}
|
|
245
|
+
`,420),fl(rs,$L(t),420),tr("caddy",["validate","--config",ts,"--adapter","caddyfile"])}catch(s){throw r?fl(ts,r,420):Sp(ts,{force:!0}),n!==null?fl(rs,n,420):Sp(rs,{force:!0}),s}return tr("systemctl",["enable","--now","caddy"]),tr("systemctl",["reload","caddy"]),jL(),{configured:!0,service:"caddy.service",caddyfile:rs,site:h0(t),upstream:`127.0.0.1:${Number(t.listen.port)}`}}function $L(t){return`${h0(t)} {
|
|
246
|
+
reverse_proxy 127.0.0.1:${Number(t.listen.port)}
|
|
247
|
+
header {
|
|
248
|
+
Strict-Transport-Security "max-age=31536000"
|
|
249
|
+
X-Content-Type-Options "nosniff"
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
`}function h0(t){let e=new URL(t.public_url),r=e.hostname.includes(":")&&!e.hostname.startsWith("[")?`[${e.hostname}]`:e.hostname;return e.port&&e.port!=="443"?`${r}:${e.port}`:r}async function UL(){if(ml("caddy",["version"],{stdio:"ignore"}).status===0)return;if(ml("apt-get",["--version"],{stdio:"ignore"}).status!==0)throw new Error("Caddy is not installed and automatic installation currently supports Debian/Ubuntu only");tr("apt-get",["update"]),tr("apt-get",["install","-y","debian-keyring","debian-archive-keyring","apt-transport-https","ca-certificates","gnupg"]);let t=CL(l0(DL(),"interscale-caddy-"));try{let[e,r]=await Promise.all([fetch("https://dl.cloudsmith.io/public/caddy/stable/gpg.key",{signal:AbortSignal.timeout(3e4)}),fetch("https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt",{signal:AbortSignal.timeout(3e4)})]);if(!e.ok||!r.ok)throw new Error("Could not download the official Caddy apt repository metadata");let n=l0(t,"caddy.gpg.key");Tp(n,Buffer.from(await e.arrayBuffer()),{mode:384}),tr("gpg",["--dearmor","--yes","--output","/usr/share/keyrings/caddy-stable-archive-keyring.gpg",n]),Tp("/etc/apt/sources.list.d/caddy-stable.list",await r.text(),{mode:420}),d0("/usr/share/keyrings/caddy-stable-archive-keyring.gpg",420),tr("apt-get",["update"]),tr("apt-get",["install","-y","caddy"])}finally{Sp(t,{recursive:!0,force:!0})}}function jL(){let t=ml("ufw",["status"],{encoding:"utf8"});t.status!==0||!/^Status:\s+active/im.test(t.stdout)||(tr("ufw",["allow","80/tcp"]),tr("ufw",["allow","443/tcp"]))}function ML(t){return t.split(/\r?\n/).some(e=>e.trim()===kp)}function BL(t){return new Set(["127.0.0.1","::1","localhost"]).has(String(t).toLowerCase())}function fl(t,e,r){let n=`${t}.${process.pid}.tmp`;Tp(n,e,{mode:r}),PL(n,t),d0(t,r)}function tr(t,e){let r=ml(t,e,{stdio:"inherit",env:{...process.env,DEBIAN_FRONTEND:"noninteractive"}});if(r.status!==0)throw new Error(`${t} ${e.join(" ")} failed with status ${r.status}`)}var ts,xp,rs,kp,p0=v(()=>{ts="/etc/caddy/Caddyfile",xp="/etc/caddy/interscale.d",rs=`${xp}/interscale.caddy`,kp=`import ${xp}/*.caddy`;a(u0,"configureCaddyProxy");a($L,"renderCaddyfile");a(h0,"caddySiteAddress");a(UL,"installCaddyIfMissing");a(jL,"openFirewallIfActive");a(ML,"hasImport");a(BL,"isLoopbackHost");a(fl,"writeAtomic");a(tr,"run")});var v0={};K(v0,{agentServiceStatus:()=>VL,installAgentService:()=>HL,installServerService:()=>YL,renderUnit:()=>Np,restartAgentService:()=>JL,uninstallAgentService:()=>GL});import{chownSync as f0,existsSync as Ip,mkdirSync as FL,readdirSync as qL,rmSync as zL,statSync as WL,writeFileSync as m0}from"node:fs";import{dirname as _0,join as ti,resolve as g0}from"node:path";import{homedir as w0}from"node:os";import{execFileSync as Ro,spawnSync as ei}from"node:child_process";import{fileURLToPath as y0}from"node:url";function HL(){let t=jc(g0(_0(y0(import.meta.url)),"..",".."));if(t)return t;let e=ti(process.env.XDG_CONFIG_HOME||ti(w0(),".config"),"systemd","user"),r=ti(e,Cr);return FL(e,{recursive:!0,mode:448}),m0(r,Np("agent"),{mode:384}),Ro("systemctl",["--user","daemon-reload"]),Ro("systemctl",["--user","enable","--now",Cr]),{unit:Cr,path:r}}function GL(){let t=Bc();if(t)return t;let e=ti(process.env.XDG_CONFIG_HOME||ti(w0(),".config"),"systemd","user",Cr);return ei("systemctl",["--user","disable","--now",Cr],{stdio:"ignore"}),Ip(e)&&zL(e),ei("systemctl",["--user","daemon-reload"],{stdio:"ignore"}),{unit:Cr,removed:!0}}function JL(){let t=Mc();return t||(Ro("systemctl",["--user","restart",Cr]),{restarted:!0,unit:Cr,loaded:!0})}function VL(){let t=tn();if(t)return t;let e=ei("systemctl",["--user","show",Cr,"--property=LoadState,ActiveState,SubState,MainPID"],{encoding:"utf8"});return{installed:e.status===0,loaded:e.stdout.includes("ActiveState=active"),detail:e.stdout.trim()}}async function YL(t={}){if(process.getuid?.()!==0)throw new Error("Server service installation requires root (sudo interscale hub install)");let e=ei("id",["-u","interscale"],{encoding:"utf8"});if(e.status!==0){let u=ei("useradd",["--system","--home-dir","/var/lib/interscale","--shell","/usr/sbin/nologin","interscale"],{encoding:"utf8"});if(u.status!==0)throw new Error(`Could not create interscale system user: ${u.stderr}`);e=ei("id",["-u","interscale"],{encoding:"utf8"})}let r=ei("id",["-g","interscale"],{encoding:"utf8"}),n=Number(e.stdout.trim()),i=Number(r.stdout.trim()),s=t.config,o=t.configPath||je(),c=s?.data_dir||bs();b0(c,n,i),Ip(o)&&f0(o,n,i);let l=ti("/etc/systemd/system",Rp);m0(l,Np("server",{configPath:o,dataDirectory:c}),{mode:420}),Ro("systemctl",["daemon-reload"]),Ro("systemctl",["enable","--now",Rp]);let d=t.configureCaddy?await u0(t.config):{configured:!1};return{unit:Rp,path:l,caddy:d}}function Np(t,e={}){let r=g0(_0(y0(import.meta.url)),"..","bin",`interscale-${t}.mjs`),n=t==="server"?`User=interscale
|
|
253
|
+
Group=interscale
|
|
254
|
+
Environment=${_l("INTERSCALE_SERVER_CONFIG",e.configPath||je())}
|
|
255
|
+
Environment=${_l("INTERSCALE_SERVER_DATA",e.dataDirectory||bs())}
|
|
256
|
+
`:`Environment=${_l("INTERSCALE_HOME",x())}
|
|
257
|
+
Environment=${_l("INTERSCALE_AGENT_CONFIG",L())}
|
|
258
|
+
`,i=t==="server"?`ProtectSystem=strict
|
|
259
|
+
ProtectHome=true
|
|
260
|
+
ReadWritePaths=${Op(e.dataDirectory||bs())}
|
|
261
|
+
`:"";return`[Unit]
|
|
262
|
+
Description=Interscale ${t}
|
|
263
|
+
After=network-online.target
|
|
264
|
+
Wants=network-online.target
|
|
265
|
+
|
|
266
|
+
[Service]
|
|
267
|
+
Type=simple
|
|
268
|
+
${n}ExecStart=${Op(process.execPath)} ${Op(r)}
|
|
269
|
+
Restart=on-failure
|
|
270
|
+
RestartSec=5
|
|
271
|
+
NoNewPrivileges=true
|
|
272
|
+
PrivateTmp=true
|
|
273
|
+
${i}
|
|
274
|
+
|
|
275
|
+
[Install]
|
|
276
|
+
WantedBy=${t==="server"?"multi-user.target":"default.target"}
|
|
277
|
+
`}function Op(t){return String(t).replace(/([\\"'\s])/g,"\\$1")}function _l(t,e){return`"${t}=${String(e).replace(/([\\"])/g,"\\$1")}"`}function b0(t,e,r){if(!Ip(t))return;if(WL(t).isDirectory())for(let i of qL(t))b0(ti(t,i),e,r);f0(t,e,r)}var Cr,Rp,E0=v(()=>{Z();p0();Xi();Cr="interscale-agent.service",Rp="interscale-server.service";a(HL,"installAgentService");a(GL,"uninstallAgentService");a(JL,"restartAgentService");a(VL,"agentServiceStatus");a(YL,"installServerService");a(Np,"renderUnit");a(Op,"systemdEscape");a(_l,"systemdEnvironment");a(b0,"chownRecursive")});import{platform as gl}from"node:os";async function an(){if(gl()==="darwin")return Promise.resolve().then(()=>(Mb(),jb));if(gl()==="win32")return Promise.resolve().then(()=>(Ep(),vp));if(gl()==="linux")return Promise.resolve().then(()=>(E0(),v0));throw new Error(`Unsupported platform: ${gl()}`)}var S0=v(()=>{a(an,"platformService")});function T0(t){let e=t.capabilities||{};return{name:t.name,...t.owner_email?{owner:t.owner_email}:{},device:x0(e.device),status:t.status,os:e.os?.name||t.platform,cpu:XL(e),memory:ri(e.memory_total_bytes),gpu:(e.gpus||[]).map(ZL).join(", "),frameworks:eC(e.software?.frameworks),agent:t.agent_version,last_seen:t.last_seen?new Date(t.last_seen).toISOString():"never"}}function k0(t){let e=t.capabilities||{},r=e.os||{},n=x0(e.device),i=[`${ri(e.memory_total_bytes)} total`,e.memory_free_bytes?`${ri(e.memory_free_bytes)} free`:null].filter(Boolean).join(" \xB7 "),s=e.storage||{},o=e.gpus||[],c=e.software||{},l=(t.addresses||[]).filter(u=>u!=="127.0.0.1");return[`${t.name} \u2014 ${t.status}`,`Device: ${n||"Unknown"}`,`OS: ${[r.name||t.platform,r.version||e.release,r.arch||e.arch].filter(Boolean).join(" \xB7 ")}`,`CPU: ${KL(e)}`,`Memory: ${i||"Unknown"}`,`Storage: ${ri(s.available_bytes)} free / ${ri(s.total_bytes)} total`,`Agent: ${t.agent_version}`,"","GPU / accelerators:",...o.length?o.map(u=>` - ${QL(u)}`):[" - None detected"],"","Frameworks:",...Ap(c.frameworks,"No supported framework detected"),"","Runtimes:",...Ap(c.runtimes,"No runtime detected",!0),"","Tools:",...Ap(c.tools,"No supported tool detected"),"","LAN:",` - Addresses: ${l.length?l.join(", "):"none reported"}`,` - Direct data port: ${t.data_port||"not reported"}`," - Discovery: mDNS _interscale-data._tcp.local"," - Advertised publicly on LAN: node identity + port only; never fleet key or hardware inventory","",`Inventory collected: ${e.collected_at?new Date(e.collected_at).toISOString():"legacy agent snapshot"}`].join(`
|
|
278
|
+
`)}function Ap(t,e,r=!1){return!Array.isArray(t)||t.length===0?[` - ${e}`]:t.map(n=>{let i=n.environment?` [${n.environment}]`:"",s=r&&n.path?` \u2014 ${n.path}`:"";return` - ${n.name||n.distribution} ${n.version||""}${i}${s}`.trimEnd()})}function XL(t){let e=t.cpu_cores||t.cpu_threads;return e?`${e}c/${t.cpu_threads||e}t`:t.cpu_model||""}function KL(t){let e=[t.cpu_model||"Unknown CPU"];t.cpu_cores&&e.push(`${t.cpu_cores} cores`),t.cpu_threads&&e.push(`${t.cpu_threads} threads`);let r=t.cpu_topology;return(r?.performance_cores||r?.efficiency_cores)&&e.push(`${r.performance_cores||0} performance + ${r.efficiency_cores||0} efficiency`),e.join(" \xB7 ")}function ZL(t){let e=t.cores?` ${t.cores}c`:t.memory_bytes?` ${ri(t.memory_bytes)}`:"";return`${t.name||t.vendor||"GPU"}${e}`}function QL(t){return[t.name||t.vendor||"GPU",t.cores?`${t.cores} cores`:null,t.memory_bytes?ri(t.memory_bytes):null,t.metal||null,t.cuda?`CUDA ${t.cuda}`:null,t.driver?`driver ${t.driver}`:null,t.unified_memory?"unified memory":null].filter(Boolean).join(" \xB7 ")}function x0(t={}){let e=t.family||t.model;if(!e)return t.manufacturer||"";let r=t.family&&t.model&&t.model!==t.family?` (${t.model})`:"";return`${t.manufacturer&&!e.toLowerCase().includes(t.manufacturer.toLowerCase())?`${t.manufacturer} `:""}${e}${r}`}function eC(t=[]){let e=new Set,r=[];for(let n of t){let i=`${n.name||n.distribution} ${n.version||""}`.trim();!i||e.has(i)||(e.add(i),r.push(i))}return r.join(", ")}function ri(t){if(!Number.isFinite(Number(t))||Number(t)<0)return"unknown";let e=Number(t);return e>=1024**3?`${(e/1024**3).toFixed(1)} GiB`:e>=1024**2?`${(e/1024**2).toFixed(1)} MiB`:e>=1024?`${(e/1024).toFixed(1)} KiB`:`${e} B`}var R0=v(()=>{a(T0,"nodeTableRow");a(k0,"renderNodeInventory");a(Ap,"softwareLines");a(XL,"cpuSummary");a(KL,"cpuDetail");a(ZL,"gpuSummary");a(QL,"gpuDetail");a(x0,"deviceName");a(eC,"compactFrameworks");a(ri,"formatBytes")});function Pr(t){return tC.includes(t)?"machine":"server"}function O0(t){if(t==null||t==="")return null;if(!rC.includes(t))throw new N(400,"invalid_node_kind","kind must be machine or server");return t}var tC,rC,Oo=v(()=>{ye();tC=Object.freeze(["darwin","win32"]),rC=Object.freeze(["machine","server"]);a(Pr,"nodeKind");a(O0,"parseNodeKind")});import{createHash as L0,randomUUID as nC}from"node:crypto";import{createReadStream as iC,existsSync as sC,rmSync as I0}from"node:fs";import{link as oC,lstat as C0,open as aC,readFile as cC,unlink as lC}from"node:fs/promises";import{join as ni,resolve as dC}from"node:path";function N0(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}}async function Lp(t,e){let r=await C0(t);if(!r.isFile())throw new N(409,"release_staged_artifact_mismatch","Staged artifact is not a regular file");let n=L0("sha256");for await(let i of iC(t))e?.throwIfAborted(),n.update(i);return{size:r.size,sha256:n.digest("hex")}}async function uC(t){let e;try{e=await C0(t)}catch(r){throw r?.code==="ENOENT"?new N(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 N(409,"release_stage_receipt_invalid","The local staging receipt is invalid");try{return JSON.parse(await cC(t,"utf8"))}catch{throw new N(409,"release_stage_receipt_invalid","The local staging receipt is invalid")}}function hC(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||Ee(t.artifact)!==Ee(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 N(409,"release_stage_receipt_invalid","The local staging receipt does not match the signed release plan")}function A0(t){if(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(t))throw new N(400,"invalid_release_manifest","release_id must be safe for private staging");return t}var ns,Cp=v(()=>{ye();Xn();Re();Hi();ns=class{static{a(this,"UpdateStager")}constructor(e,r={}){this.root=dC(e),this.fetch=r.fetch||globalThis.fetch,xe(this.root)}async stage(e,r,n={}){let i=vo(e,r,n);if(i.state==="no_change")return{schema:"interscale.update-stage/v1",state:"no_change",plan:i,receipt:null};let s=ni(this.root,A0(i.release_id));xe(s);let o=ni(s,i.artifact.file_name),c=ni(s,"stage-receipt.json");if(sC(o)){let d=await Lp(o,n.signal);if(d.size!==i.artifact.size||d.sha256!==i.artifact.sha256)throw new N(409,"release_staged_artifact_mismatch","Existing staged artifact does not match the signed release");let u=N0(i,o,c,!0);return Rt(c,u),{schema:"interscale.update-stage/v1",state:"verified",plan:i,receipt:u}}let l=ni(s,`.${i.artifact.file_name}.${nC()}.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 N(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 N(409,"release_artifact_size_mismatch","Release Content-Length does not match the signed manifest");let h=await aC(l,"wx",384),p=L0("sha256"),f=0;try{for await(let g of d.body){n.signal?.throwIfAborted();let y=Buffer.from(g);if(f+=y.length,f>i.artifact.size)throw new N(409,"release_artifact_size_mismatch","Release download exceeds the signed byte size");p.update(y),await h.write(y)}await h.sync()}finally{await h.close()}let m=p.digest("hex");if(f!==i.artifact.size)throw new N(409,"release_artifact_size_mismatch","Release download is shorter than the signed byte size");if(m!==i.artifact.sha256)throw new N(409,"release_artifact_hash_mismatch","Release download does not match the signed SHA-256");let _=!1;try{await oC(l,o),await lC(l)}catch(g){if(g?.code!=="EEXIST")throw g;let y=await Lp(o,n.signal);if(y.size!==i.artifact.size||y.sha256!==i.artifact.sha256)throw new N(409,"release_staged_artifact_mismatch","Concurrent staged artifact does not match the signed release");_=!0,I0(l,{force:!0})}let w=N0(i,o,c,_);return Rt(c,w),{schema:"interscale.update-stage/v1",state:"verified",plan:i,receipt:w}}catch(d){throw I0(l,{force:!0}),d}}async preflight(e,r,n={}){let i=vo(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=ni(this.root,A0(i.release_id)),o=ni(s,i.artifact.file_name),c=ni(s,"stage-receipt.json"),l=await uC(c);hC(l,i,o,c);let d;try{d=await Lp(o,n.signal)}catch(u){throw u?.code==="ENOENT"?new N(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 N(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."}}};a(N0,"stageReceipt");a(Lp,"hashFile");a(uC,"readStageReceipt");a(hC,"validateStageReceipt");a(A0,"safeSegment")});import{createServer as Cz,connect as pC}from"node:net";import{existsSync as Dz,lstatSync as fC,mkdirSync as $z,unlinkSync as Uz,chmodSync as jz,readFileSync as mC}from"node:fs";import{createHash as _C,createHmac as gC,randomBytes as wC,timingSafeEqual as yC}from"node:crypto";import{join as bC,posix as vC,win32 as EC}from"node:path";function SC(t=x(),e=process.platform){return e==="win32"?`\\\\.\\pipe\\interscale-application-update-${_C("sha256").update(EC.resolve(t).toLowerCase()).digest("hex").slice(0,32)}`:vC.join(t,"application-update.sock")}function D0(t,{root:e=x(),timeoutMs:r=3e3,destination:n,platform:i=process.platform,socketPath:s=SC(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=kC(e)}catch{return c(new Error("Authenticated application update bridge is unavailable"))}d.nonce=wC(16).toString("hex"),d.at=Date.now(),d.mac=P0(u,"request",d)}let h=pC(s),p="",f=!1,m=a((_,w)=>{f||(f=!0,h.destroy(),_?c(_):o(w))},"finish");h.setTimeout(r,()=>m(new Error("Application update bridge timed out"))),h.once("connect",()=>h.write(JSON.stringify(d)+`
|
|
279
|
+
`)),h.on("data",_=>{if(p+=_,Buffer.byteLength(p)>2048)return m(new Error("Invalid application update response"));if(p.includes(`
|
|
280
|
+
`))try{let w=JSON.parse(p);if(!w||typeof w.idle!="boolean"||typeof w.version!="string"||l&&!xC(w.mac,P0(u,"response",d,w)))throw new Error("Unauthenticated or invalid application update response");m(null,{idle:w.idle,version:w.version})}catch(w){m(w)}}),h.once("error",_=>m(_)),h.once("close",()=>m(new Error("Application update bridge disconnected")))})}function kC(t){let e=TC(t),r=fC(e);if(!r.isFile()||r.size>1024)throw new Error("Invalid application update key");let n=JSON.parse(mC(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}function P0(t,e,r,n){let i=[e,r.action,r.destination,r.nonce,r.at];return e==="response"&&i.push(n.idle,n.version),gC("sha256",Buffer.from(t,"hex")).update(JSON.stringify(i)).digest("hex")}function xC(t,e){return typeof t=="string"&&/^[a-f0-9]{64}$/.test(t)&&yC(Buffer.from(t,"hex"),Buffer.from(e,"hex"))}var TC,$0=v(()=>{Z();Re();a(SC,"applicationUpdateSocket");TC=a(t=>bC(t,"application-update-key.json"),"keyPath");a(D0,"requestApplicationUpdate");a(kC,"readKey");a(P0,"authenticate");a(xC,"validMac")});import{cp as RC,lstat as OC,mkdir as Pp,readdir as U0,readFile as j0,rename as is,rm as St}from"node:fs/promises";import{existsSync as Dr}from"node:fs";import{dirname as Io,join as ae,resolve as Dp}from"node:path";import{homedir as IC}from"node:os";import{randomUUID as NC}from"node:crypto";import{spawnSync as AC}from"node:child_process";async function M0(t){let e=JSON.parse(ss("/usr/bin/plutil",["-convert","json","-o","-",ae(t,"Contents","Info.plist")]).stdout);ss("/usr/bin/codesign",["--verify","--deep","--strict",t]);let r=ss("/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))}}function Le(t,e,r){if(!t?.signed||t.identifier!==Up||!t.team_id||!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(t.version)||e&&t.version!==e||r&&t.team_id!==r)throw ot("application_identity_invalid","Expected a signed InterScale application with the release version and publisher")}async function $p(t){if(!(await OC(t)).isDirectory())throw ot("application_path_invalid","Application must be a real directory, not a symlink")}function LC(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}function CC(t){return ss("/bin/ps",["-axo","command="]).stdout.split(`
|
|
281
|
+
`).some(e=>e.includes(`${t}/Contents/MacOS/`))}function ss(t,e){let r=AC(t,e,{encoding:"utf8",timeout:12e4,maxBuffer:4194304});if(r.error||r.status!==0)throw ot("application_command_failed",`${t} failed while verifying or replacing InterScale`);return r}var Up,ot,wl,B0=v(()=>{Re();Wn();$0();Up="com.interscale.desktop",ot=a((t,e)=>Object.assign(new Error(e),{code:t}),"fail"),wl=class{static{a(this,"MacApplicationInstaller")}constructor(e,r={}){this.root=Dp(e),this.destination=Dp(r.destination||"/Applications/Interscale.app"),this.searchRoots=r.searchRoots||[Io(this.destination),ae(IC(),"Applications")],this.inspect=r.inspect||M0,this.candidateIdentifier=r.candidateIdentifier||(this.inspect===M0?n=>JSON.parse(ss("/usr/bin/plutil",["-convert","json","-o","-",ae(n,"Contents","Info.plist")]).stdout).CFBundleIdentifier:null),this.running=r.running||CC,this.run=r.run||ss,this.applicationRequest=r.applicationRequest||(n=>D0(n,{destination:this.destination})),this.relaunch=r.relaunch||(()=>this.run("/usr/bin/open",["-a",this.destination])),this.statePath=ae(this.root,"application-state.json")}async state(){try{return JSON.parse(await j0(this.statePath,"utf8"))}catch(e){if(e.code==="ENOENT")return null;throw e}}async assertReady(e,r){let n=await this.inspect(e);if(Le(n,r),Dr(this.destination)){let i=await this.inspect(this.destination);if(Le(i,null,n.team_id),await this.running(this.destination)&&!(await this.applicationRequest("status").catch(()=>null))?.idle)throw ot("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=ge(ae(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 Pp(this.root,{recursive:!0,mode:448});let i=await this.state();if(i&&!["succeeded","rolled_back","failed"].includes(i.state))throw ot("application_update_unresolved","Reconcile the interrupted application update before replacing it");let s=await this.inspect(e);Le(s,r),await $p(e);let o=Dr(this.destination)?await this.inspect(this.destination):null,c=!1;if(o){if(await $p(this.destination),Le(o),o.team_id!==s.team_id)throw ot("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 ot("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 ot("application_busy","InterScale has not finished closing; its update is deferred");await new Promise(w=>setTimeout(w,100))}c=!0}}let l=NC(),d=ae(this.root,l);await Pp(d,{mode:448});let u=ae(Io(this.destination),`.interscale-stage-${l}`),h=ae(Io(this.destination),`.interscale-retired-${l}`),p=o?ae(d,"previous.tar"):null,f={schema:"interscale.application-update/v1",id:l,destination:this.destination,stage:u,retired:h,backup:p,previous:o,target:s,relaunch:c,state:"preparing",created_at:Date.now()};this.write(f),se(ae(d,"transaction.json"),f);try{if(await RC(e,u,{recursive:!0,verbatimSymlinks:!0,errorOnExist:!0,force:!1}),Le(await this.inspect(u),r,s.team_id),p&&this.run("/usr/bin/tar",["-cf",p,"-C",this.destination,"."]),this.write({...f,state:"activating"}),o&&await is(this.destination,h),await is(u,this.destination),Le(await this.inspect(this.destination),r,s.team_id),await n()!==!0)throw ot("application_health_failed","Application health check failed");let m={...f,state:"succeeded",completed_at:Date.now()};this.write(m),await St(h,{recursive:!0,force:!0}),i?.id&&/^[a-f0-9-]{36}$/.test(i.id)&&i.id!==l&&await St(ae(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&&Dr(this.destination))try{this.relaunch()}catch{}throw m}}async recover(){let e=ge(ae(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"){!Dr(this.destination)&&Dr(e.stage)&&Dr(e.retired)&&(Le(await this.inspect(e.stage),e.previous.version,e.previous.team_id),await is(e.stage,this.destination));let n=await this.inspect(this.destination);if(n.version===e.previous.version){Le(n,e.previous.version,e.previous.team_id);let s={...e,state:"rolled_back",rolled_back_at:Date.now()};return this.write(s),await St(e.retired,{recursive:!0,force:!0}),await St(e.stage,{recursive:!0,force:!0}),s}Le(n,e.target.version,e.target.team_id),await St(e.stage,{recursive:!0,force:!0});let i={...e,state:"succeeded"};return this.write(i),i}Dr(e.retired)?(Le(await this.inspect(e.retired),e.previous?.version,e.previous?.team_id),Dr(this.destination)&&(Le(await this.inspect(this.destination),e.target.version,e.target.team_id),await St(this.destination,{recursive:!0})),await is(e.retired,this.destination)):!e.previous&&e.state==="activating"&&Dr(this.destination)&&(Le(await this.inspect(this.destination),e.target.version,e.target.team_id),await St(this.destination,{recursive:!0})),await St(e.stage,{recursive:!0,force:!0});let r={...e,state:"failed",recovered_at:Date.now()};return this.write(r),r}async rollback(){let e=ge(ae(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 ot("application_rollback_unavailable","No previous application is retained");if(this.validateReceipt(e),await this.running(this.destination))throw ot("application_busy","Close Interscale before restoring its previous application");let r=e.stage;await Pp(r,{mode:448}),this.run("/usr/bin/tar",["-xf",e.backup,"-C",r]),Le(await this.inspect(r),e.previous.version,e.previous.team_id),this.write({...e,state:"rolling_back"}),await is(this.destination,e.retired);try{await is(r,this.destination),Le(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 St(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=>Dp(s)))){let s;try{s=await U0(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")continue;n.push({path:i,reason:"unreadable"});continue}for(let o of s){let c=ae(i,o.name);if(!(c===this.destination||!o.isDirectory()||!o.name.endsWith(".app")))try{if(this.candidateIdentifier&&await this.candidateIdentifier(c)!==Up)continue;let l=await this.inspect(c);if(l.identifier!==Up||!l.signed||l.team_id!==e.team_id)continue;if(LC(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 $p(c),Le(await this.inspect(c),l.version,e.team_id),await St(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 U0(this.root,{withFileTypes:!0})){if(!r.isDirectory()||r.name===e.id||!/^[a-f0-9-]{36}$/.test(r.name))continue;let n=ae(this.root,r.name);try{let i=JSON.parse(await j0(ae(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 St(n,{recursive:!0})}catch{}}}validateReceipt(e){if(!/^[a-f0-9-]{36}$/.test(e.id)||e.destination!==this.destination||e.stage!==ae(Io(this.destination),`.interscale-stage-${e.id}`)||e.retired!==ae(Io(this.destination),`.interscale-retired-${e.id}`)||e.backup&&e.backup!==ae(this.root,e.id,"previous.tar"))throw ot("application_receipt_invalid","Application transaction paths do not match this installation")}write(e){se(this.statePath,{...e,updated_at:Date.now()})}};a(M0,"inspectMacApplication");a(Le,"assertIdentity");a($p,"assertDirectory");a(LC,"compareVersions");a(CC,"macApplicationRunning");a(ss,"run")});import{closeSync as PC,existsSync as Tt,openSync as DC,readFileSync as $C,realpathSync as jp,renameSync as F0}from"node:fs";import{lstat as UC,mkdir as q0,readdir as vl,realpath as jC,rename as G0,rm as ii}from"node:fs/promises";import{spawnSync as MC}from"node:child_process";import{createHash as BC}from"node:crypto";import{dirname as No,isAbsolute as FC,join as I,relative as J0,resolve as Ao,win32 as qC}from"node:path";import{fileURLToPath as zC}from"node:url";async function V0(t,e=0){if(e>6)return null;for(let r of await vl(t,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=I(t,r.name);if(r.name==="Applications"&&Tt(I(n,"Interscale.app","Contents","Info.plist")))return I(n,"Interscale.app");if(["app","node","node_modules"].includes(r.name)||r.name.endsWith(".app"))continue;let i=await V0(n,e+1);if(i)return i}return null}async function GC(t,e,r,n){let i=JC(t,e,r);return i.removeDestination&&await ii(r,{recursive:!0,force:!0}),n(i.program,i.args)}function JC(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:qC.join(n,"System32","tar.exe"),args:["-xf",e,"-C",r]};throw new N(400,"release_target_unsupported",`Unsupported package format: ${t}`)}function VC(t,e,{inUse:r=a(()=>!1,"inUse")}={}){let n=I(t,"slots"),i=ZC(t,e);if(!r(i))return i;let s=bl.find(c=>e?.app_root&&si(I(n,c),e.app_root));return bl.map(c=>I(n,c)).find(c=>c!==i&&(!s||c!==I(n,s))&&!r(c))||i}function YC(t){if(process.platform!=="win32")return!1;let e=I(t,"runtime");if(!Tt(e))return!1;if(Y0(e))return!0;let r=`${e}.in-use-check`;try{F0(e,r)}catch{return!0}try{F0(r,e)}catch{}return!1}function Y0(t){if(process.platform!=="win32")return!1;try{return PC(DC(I(t,"node","node.exe"),"r+")),!1}catch(e){return e.code!=="ENOENT"}}async function XC(t){let e=I(t,"runtime");Tt(e)&&await G0(e,I(t,`retired-${Date.now()}`)),await ii(`${e}.in-use-check`,{recursive:!0,force:!0})}async function KC(t){for(let e of bl){let r=I(t,e);for(let n of Tt(r)?await vl(r):[])!n.startsWith("retired-")||Y0(I(r,n))||await ii(I(r,n),{recursive:!0,force:!0}).catch(()=>{})}}function ZC(t,e){let r=I(t,"slots"),n=bl.find(l=>e?.app_root&&si(I(r,l),e.app_root));if(n==="a"||n==="b")return I(r,n==="a"?"b":"a");let i=a(l=>{try{return JSON.parse($C(I(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 I(r,s?"b":"a");let c=s.findIndex((l,d)=>l!==o[d]);return I(r,c>=0&&s[c]>o[c]?"b":"a")}async function QC(t,e){let r=I(e,"runtime");await XC(e),await G0(No(t.app_root),r),await ii(I(e,"expanded"),{recursive:!0,force:!0}),await KC(No(e));let n=J0(No(t.app_root),t.node);return{...t,node:I(r,n),cli:I(r,"app","bin","interscale.mjs"),app_root:I(r,"app")}}async function eP(t,e){let r=[];if(await n(t,0),r.length!==1)throw new N(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 vl(i,{withFileTypes:!0})){let c=I(i,o.name);if(o.isSymbolicLink()){let l=await jC(c);if(!si(t,l))throw new N(409,"update_archive_escape","Extracted package contains a symlink outside its private release root");continue}if(o.isDirectory()){if(o.name==="app"&&Tt(I(c,"package.json"))&&Tt(I(c,"bin","interscale.mjs"))){let l=No(c),d=process.platform==="win32"?I(l,"node","node.exe"):I(l,"node","bin","node");if(Tt(d)){let{readFile:u}=await import("node:fs/promises");JSON.parse(await u(I(c,"package.json"),"utf8")).version===e&&r.push({node:d,cli:I(c,"bin","interscale.mjs"),app_root:c,version:e})}}await n(c,s+1)}}}}function z0(){let t=Ao(No(zC(import.meta.url)),"..");return{node:process.execPath,cli:I(t,"bin","interscale.mjs"),app_root:t,version:we}}function tP(t,e,r){let n=jp(Ao(t)),i=I(n,"app"),s={node:process.platform==="win32"?I(n,"node","node.exe"):I(n,"node","bin","node"),cli:I(i,"bin","interscale.mjs"),app_root:i,version:e};for(let c of[s.node,s.cli,I(i,"package.json")])if(!Tt(c)||!si(n,jp(c)))throw new N(409,"rollback_runtime_invalid","The retained previous runtime is incomplete or escapes its retention root");if(Mp(s,r)!==e)throw new N(409,"rollback_build_mismatch","The retained previous runtime does not match the installed version being upgraded");return s}function Mp(t,e){return String(e(t.node,[t.cli,"version"]).stdout||"").trim()}function rP(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}function W0(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()}}}function nP(t,e){let r=MC(t,e,{encoding:"utf8",windowsHide:!0,timeout:HC,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||""}}function si(t,e){let r=J0(Ao(t),Ao(e));return r===""||!r.startsWith("..")&&!FC(r)}function H0(t,e=process.platform){let r=iP(t);return e==="win32"?`r-${BC("sha256").update(r).digest("hex").slice(0,24)}`:r}function iP(t){if(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(t))throw new N(400,"invalid_release_manifest","Unsafe release identity");return t}function yl(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}}var WC,HC,os,bl,Bp=v(()=>{ye();Re();me();Gn();B0();Wn();WC=new Set(["succeeded","failed","rolled_back"]),HC=10*6e4,os=class{static{a(this,"UpdateCoordinator")}constructor(e,r={}){this.root=Ao(e),this.statePath=I(this.root,"update-state.json"),this.run=r.run||nP,this.installService=r.installService||((n,i)=>W0(n,["agent","install","--config",i,"--json"],this.run)),this.serviceStatus=r.serviceStatus||(n=>W0(n,["agent","status","--json"],this.run)),this.processCommand=r.processCommand||Ge,this.slots=r.slots??process.platform==="win32",this.slotInUse=r.slotInUse||YC,this.assertDrained=r.assertDrained||(async()=>{}),this.applicationInstaller=r.applicationInstaller===void 0?process.platform==="darwin"?new wl(I(this.root,"application")):null:r.applicationInstaller}serviceRuns(e,r){let n=rP(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,Tt(r.app_root)?jp(r.app_root):null].some(o=>o&&s(i).includes(s(I(o,"bin","interscale-agent.mjs"))))}async apply(e,{configPath:r,signal:n,previousRuntimeRoot:i}={}){let s=ge(I(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 N(409,"update_preflight_required","Apply requires a fresh verified update preflight");n?.throwIfAborted(),await q0(this.root,{recursive:!0,mode:448});let s=await this.read();if(s&&!WC.has(s.state))throw Object.assign(new N(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?tP(i,e.plan.current_version,this.run):z0(),c=this.slots?VC(this.root,o,{inUse:this.slotInUse}):null,l=c||I(this.root,"releases",H0(e.plan.release_id)),d=I(l,"expanded");await ii(d,{recursive:!0,force:!0}),await q0(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};se(I(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 GC(e.plan.artifact.package_format,e.stage.artifact_path,d,this.run),h=await eP(d,e.plan.target_version),c&&(h=await QC(h,c)),Mp(h,this.run)!==e.plan.target_version)throw new N(409,"update_build_mismatch","Extracted runtime version does not match the signed manifest");this.applicationInstaller&&(h.desktop_bundle=await V0(d))}catch(f){throw this.write({...u,state:"failed",phase:"extract",updated_at:Date.now(),error:yl(f,"update_extraction_failed")}),f}if(await this.assertDrained(n),n?.throwIfAborted(),h.desktop_bundle)try{await this.applicationInstaller.assertReady(h.desktop_bundle,h.version)}catch(f){throw this.write({...u,target:h,state:"failed",phase:"preflight",updated_at:Date.now(),error:yl(f,"application_not_ready")}),f}let p={...u,target:h,state:"running",phase:"activation",activation_started_at:Date.now(),updated_at:Date.now()};this.write(p);try{let f=await this.installService(h,r),m=await this.serviceStatus(h);if(!this.serviceRuns(m,h))throw new N(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 p={...p,state:"succeeded",phase:"health",service:f,health:m,observed_version:h.version,application:_,heartbeat_deadline:Date.now()+12e4,completed_at:Date.now(),updated_at:Date.now(),error:null},this.write(p),se(I(this.root,"active-runtime.json"),h),p}catch(f){throw p={...p,state:"needs_review",phase:"activation",updated_at:Date.now(),error:yl(f,"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(p),Object.assign(new N(409,"update_activation_outcome_unknown","Update activation may have changed the service and requires reconciliation"),{retryable:!1,next_action:p.next_action})}}async status(){let e;try{e=ge(I(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),se(I(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=ge(I(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 N(409,"update_rollback_unavailable","No applied or uncertain update has a retained previous runtime");await this.assertDrained(r);let i=Mp(n.previous,this.run);if(i!==n.previous.version)throw new N(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),se(I(this.root,"active-runtime.json"),n.previous),l}catch(o){let c={...s,state:"needs_review",updated_at:Date.now(),error:yl(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 N(409,"rollback_outcome_unknown","Rollback outcome requires review"),{retryable:!1,next_action:c.next_action})}}async read(){if(!Tt(this.statePath))return null;let e=await UC(this.statePath);if(!e.isFile()||e.size<2||e.size>256*1024)throw new N(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 N(409,"update_state_invalid","Update state receipt is invalid")}}async cleanup(){let e=ge(I(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,z0().app_root].filter(Boolean),i=I(this.root,"releases"),s=[];if(!Tt(i))return{removed:s};for(let c of await vl(i,{withFileTypes:!0})){if(!c.isDirectory())continue;let l=I(i,c.name);if(!n.some(d=>si(l,d)))try{let{readFile:d}=await import("node:fs/promises"),u=JSON.parse(await d(I(l,"release-receipt.json"),"utf8"));if(u.schema!=="interscale.runtime-retention/v1"||c.name!==H0(u.release_id)||!/^[a-f0-9]{64}$/.test(u.sha256))continue;await ii(l,{recursive:!0}),s.push(l)}catch{}}let o=r.target?.desktop_bundle;return o&&si(i,o)&&!n.some(c=>si(c,o))&&await ii(o,{recursive:!0,force:!0}),{removed:s}}finally{e()}}async recoverPreparation(){let e=ge(I(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=ge(I(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){se(this.statePath,e)}};a(V0,"findDesktopBundle");a(GC,"extractPackage");a(JC,"packageExtractionCommand");bl=["a","b","c"];a(VC,"inactiveSlot");a(YC,"slotInUse");a(Y0,"nodeRunning");a(XC,"retireSlotRuntime");a(KC,"removeRetiredRuntimes");a(ZC,"preferredSlot");a(QC,"settleSlotRuntime");a(eP,"locateRuntime");a(z0,"currentRuntime");a(tP,"retainedRuntime");a(Mp,"runtimeVersion");a(rP,"servicePid");a(W0,"runRuntime");a(nP,"runCommand");a(si,"inside");a(H0,"updateReleaseDirectoryName");a(iP,"safeSegment");a(yl,"publicFailure")});import{chmodSync as sP,mkdirSync as oP}from"node:fs";import{dirname as aP}from"node:path";import{DatabaseSync as cP}from"node:sqlite";import{randomUUID as oi}from"node:crypto";function Fp(t,e){if(!Number.isSafeInteger(e)||e<0||e>=t.total_chunks)throw new Error("Transfer chunk index is outside its manifest");return e===t.total_chunks-1?t.size-e*t.chunk_size:t.chunk_size}var lP,El,X0=v(()=>{Hi();lP=720*60*60*1e3,El=class{static{a(this,"AgentLedger")}constructor(e){this.path=e,oP(aP(e),{recursive:!0,mode:448}),this.database=new cP(e,{timeout:5e3});try{sP(e,384)}catch{}this.database.exec(`
|
|
282
|
+
PRAGMA journal_mode = WAL;
|
|
283
|
+
PRAGMA synchronous = NORMAL;
|
|
284
|
+
PRAGMA busy_timeout = 5000;
|
|
285
|
+
CREATE TABLE IF NOT EXISTS jobs (
|
|
286
|
+
id TEXT PRIMARY KEY,
|
|
287
|
+
state TEXT NOT NULL,
|
|
288
|
+
payload_json TEXT NOT NULL,
|
|
289
|
+
pid INTEGER,
|
|
290
|
+
started_at INTEGER,
|
|
291
|
+
updated_at INTEGER NOT NULL,
|
|
292
|
+
completed_at INTEGER
|
|
293
|
+
) STRICT;
|
|
294
|
+
CREATE TABLE IF NOT EXISTS outbound_events (
|
|
295
|
+
event_id TEXT PRIMARY KEY,
|
|
296
|
+
job_id TEXT NOT NULL,
|
|
297
|
+
message_json TEXT NOT NULL,
|
|
298
|
+
created_at INTEGER NOT NULL
|
|
299
|
+
) STRICT;
|
|
300
|
+
CREATE INDEX IF NOT EXISTS outbound_events_created ON outbound_events(created_at);
|
|
301
|
+
CREATE INDEX IF NOT EXISTS outbound_events_job ON outbound_events(job_id);
|
|
302
|
+
DROP TABLE IF EXISTS outbound_event_dispositions;
|
|
303
|
+
CREATE TABLE IF NOT EXISTS transfers (
|
|
304
|
+
id TEXT PRIMARY KEY,
|
|
305
|
+
state TEXT NOT NULL,
|
|
306
|
+
offer_json TEXT NOT NULL,
|
|
307
|
+
chunks_json TEXT NOT NULL,
|
|
308
|
+
received_bytes INTEGER NOT NULL DEFAULT 0,
|
|
309
|
+
relay_received_bytes INTEGER NOT NULL DEFAULT 0,
|
|
310
|
+
relay_attempt INTEGER NOT NULL DEFAULT 0,
|
|
311
|
+
part_path TEXT NOT NULL,
|
|
312
|
+
updated_at INTEGER NOT NULL
|
|
313
|
+
) STRICT;
|
|
314
|
+
CREATE TABLE IF NOT EXISTS artifact_send_cancellations (
|
|
315
|
+
transfer_id TEXT PRIMARY KEY,
|
|
316
|
+
cancelled_at INTEGER NOT NULL
|
|
317
|
+
) STRICT;
|
|
318
|
+
CREATE TABLE IF NOT EXISTS transfer_receive_cancellations (transfer_id TEXT PRIMARY KEY, cancelled_at INTEGER NOT NULL) STRICT;
|
|
319
|
+
CREATE TABLE IF NOT EXISTS transfer_publications (transfer_id TEXT PRIMARY KEY, started_at INTEGER NOT NULL) STRICT;
|
|
320
|
+
CREATE TABLE IF NOT EXISTS download_relay_stops (download_id TEXT NOT NULL, relay_id TEXT NOT NULL, stopped_at INTEGER NOT NULL, PRIMARY KEY(download_id,relay_id)) STRICT;
|
|
321
|
+
CREATE TABLE IF NOT EXISTS outgoing_downloads (
|
|
322
|
+
id TEXT PRIMARY KEY,
|
|
323
|
+
state TEXT NOT NULL,
|
|
324
|
+
offer_json TEXT NOT NULL,
|
|
325
|
+
source_path TEXT,
|
|
326
|
+
prepared_path TEXT,
|
|
327
|
+
kind TEXT,
|
|
328
|
+
temporary INTEGER NOT NULL DEFAULT 0,
|
|
329
|
+
manifest_json TEXT,
|
|
330
|
+
updated_at INTEGER NOT NULL
|
|
331
|
+
) STRICT;
|
|
332
|
+
CREATE TABLE IF NOT EXISTS library_hash_cache (
|
|
333
|
+
library_name TEXT NOT NULL,
|
|
334
|
+
relative_path TEXT NOT NULL,
|
|
335
|
+
file_id TEXT,
|
|
336
|
+
size INTEGER NOT NULL,
|
|
337
|
+
mtime_ms INTEGER NOT NULL,
|
|
338
|
+
sha256 TEXT NOT NULL,
|
|
339
|
+
updated_at INTEGER NOT NULL,
|
|
340
|
+
PRIMARY KEY (library_name, relative_path)
|
|
341
|
+
) STRICT;
|
|
342
|
+
CREATE TABLE IF NOT EXISTS wake_receipts (
|
|
343
|
+
request_id TEXT PRIMARY KEY,
|
|
344
|
+
target_node_id TEXT NOT NULL,
|
|
345
|
+
state TEXT NOT NULL,
|
|
346
|
+
packets_sent INTEGER,
|
|
347
|
+
error_code TEXT,
|
|
348
|
+
created_at INTEGER NOT NULL,
|
|
349
|
+
completed_at INTEGER
|
|
350
|
+
) STRICT;
|
|
351
|
+
CREATE TABLE IF NOT EXISTS received_cleanup_items (
|
|
352
|
+
item_key TEXT PRIMARY KEY,
|
|
353
|
+
owner_id TEXT NOT NULL,
|
|
354
|
+
role TEXT NOT NULL CHECK(role IN ('destination','cache','partial')),
|
|
355
|
+
path TEXT NOT NULL,
|
|
356
|
+
quarantine_path TEXT NOT NULL,
|
|
357
|
+
expected_json TEXT NOT NULL,
|
|
358
|
+
expected_sha256 TEXT,
|
|
359
|
+
state TEXT NOT NULL CHECK(state IN ('planned','quarantined','deleting','deleted','missing','changed','failed')),
|
|
360
|
+
planned_at INTEGER NOT NULL,
|
|
361
|
+
updated_at INTEGER NOT NULL,
|
|
362
|
+
completed_at INTEGER,
|
|
363
|
+
error_code TEXT,
|
|
364
|
+
error_message TEXT
|
|
365
|
+
) STRICT;
|
|
366
|
+
CREATE INDEX IF NOT EXISTS received_cleanup_state ON received_cleanup_items(state, planned_at);
|
|
367
|
+
CREATE TABLE IF NOT EXISTS received_cleanup_lock (
|
|
368
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
|
369
|
+
owner TEXT NOT NULL,
|
|
370
|
+
expires_at INTEGER NOT NULL
|
|
371
|
+
) STRICT;
|
|
372
|
+
`);let r=new Set(this.database.prepare("PRAGMA table_info(outgoing_downloads)").all().map(i=>i.name));if(this.database.prepare("PRAGMA table_info(transfers)").all().some(i=>i.name==="chunk_hashes_json")||this.database.exec("ALTER TABLE transfers ADD COLUMN chunk_hashes_json TEXT NOT NULL DEFAULT '{}'"),!this.database.prepare("PRAGMA table_info(transfers)").all().some(i=>i.name==="received_bytes")){this.database.exec("ALTER TABLE transfers ADD COLUMN received_bytes INTEGER NOT NULL DEFAULT 0");for(let i of this.database.prepare("SELECT id,offer_json,chunks_json FROM transfers").all())try{let s=JSON.parse(i.offer_json),o=JSON.parse(i.chunks_json);if(!Array.isArray(o)||!Number.isSafeInteger(s.size)||!Number.isSafeInteger(s.chunk_size)||!Number.isSafeInteger(s.total_chunks))continue;let c=o.reduce((l,d)=>l+Fp(s,d),0);this.database.prepare("UPDATE transfers SET received_bytes=? WHERE id=?").run(c,i.id)}catch{}}this.database.prepare("PRAGMA table_info(transfers)").all().some(i=>i.name==="relay_attempt")||this.database.exec("ALTER TABLE transfers ADD COLUMN relay_attempt INTEGER NOT NULL DEFAULT 0"),this.database.prepare("PRAGMA table_info(transfers)").all().some(i=>i.name==="relay_received_bytes")||this.database.exec("ALTER TABLE transfers ADD COLUMN relay_received_bytes INTEGER NOT NULL DEFAULT 0"),this.database.prepare("PRAGMA table_info(transfer_publications)").all().some(i=>i.name==="published_at")||this.database.exec("ALTER TABLE transfer_publications ADD COLUMN published_at INTEGER");let n=new Set(this.database.prepare("PRAGMA table_info(transfer_publications)").all().map(i=>i.name));for(let[i,s]of[["kind","TEXT"],["destination_path","TEXT"],["stage_path","TEXT"],["backup_path","TEXT"],["phase","TEXT"],["error_code","TEXT"],["completion_reported_at","INTEGER"]])n.has(i)||this.database.exec(`ALTER TABLE transfer_publications ADD COLUMN ${i} ${s}`);this.database.prepare("PRAGMA table_info(library_hash_cache)").all().some(i=>i.name==="revision")||this.database.exec("ALTER TABLE library_hash_cache ADD COLUMN revision TEXT");for(let i of["failure_code","failure_message"])r.has(i)||this.database.exec(`ALTER TABLE outgoing_downloads ADD COLUMN ${i} TEXT`)}wakeReceipt(e){return this.database.prepare("SELECT request_id,target_node_id,state,packets_sent,error_code,created_at,completed_at FROM wake_receipts WHERE request_id=?").get(e)||null}claimWakeRequest(e,r){if(![e,r].every(s=>typeof s=="string"&&s.length>0&&s.length<=200))throw new Error("Invalid Wake-on-LAN request");let n=this.wakeReceipt(e);if(n){if(n.target_node_id!==r)throw Object.assign(new Error("Wake request identity changed"),{code:"idempotency_conflict"});return{receipt:n,claimed:!1}}let i=Date.now();return this.database.prepare("INSERT INTO wake_receipts(request_id,target_node_id,state,created_at,completed_at) VALUES (?,?,'sending',?,NULL)").run(e,r,i),{receipt:this.wakeReceipt(e),claimed:!0}}saveWakeReceipt({requestId:e,targetNodeId:r,state:n,packetsSent:i=null,errorCode:s=null}){if(![e,r].every(l=>typeof l=="string"&&l.length>0&&l.length<=200)||!["sent","failed"].includes(n))throw new Error("Invalid Wake-on-LAN receipt");let o=this.wakeReceipt(e);if(o&&o.target_node_id!==r)throw Object.assign(new Error("Wake request identity changed"),{code:"idempotency_conflict"});if(o&&o.state!=="sending")return o;let c=Date.now();return o?this.database.prepare("UPDATE wake_receipts SET state=?,packets_sent=?,error_code=?,completed_at=? WHERE request_id=? AND state='sending'").run(n,i,s,c,e):this.database.prepare(`INSERT INTO wake_receipts(request_id,target_node_id,state,packets_sent,error_code,created_at,completed_at)
|
|
373
|
+
VALUES (?,?,?,?,?,?,?)`).run(e,r,n,i,s,c,c),this.wakeReceipt(e)}cancelArtifactSend(e){if(typeof e!="string"||!e.length||e.length>200)throw new Error("Invalid transfer cancellation identity");this.database.prepare("INSERT OR IGNORE INTO artifact_send_cancellations(transfer_id,cancelled_at) VALUES (?,?)").run(e,Date.now())}isArtifactSendCancelled(e){return!!this.database.prepare("SELECT 1 FROM artifact_send_cancellations WHERE transfer_id=?").get(e)}cancelTransferReceive(e){if(typeof e!="string"||!e.length||e.length>200)throw new Error("Invalid transfer cancellation identity");this.database.prepare("INSERT OR IGNORE INTO transfer_receive_cancellations VALUES (?,?)").run(e,Date.now())}isTransferReceiveCancelled(e){return!!this.database.prepare("SELECT 1 FROM transfer_receive_cancellations WHERE transfer_id=?").get(e)}noteTransferPublication(e){this.database.prepare("INSERT OR IGNORE INTO transfer_publications(transfer_id,started_at) VALUES (?,?)").run(e,Date.now())}noteTransferPublished(e){if(!this.database.prepare("UPDATE transfer_publications SET published_at=COALESCE(published_at,?) WHERE transfer_id=?").run(Date.now(),e).changes)throw new Error("Publication start receipt is missing")}noteDirectoryPublication(e,r,n,{errorCode:i}={}){if(!["staged","backed_up","published","cleaned","failed"].includes(n)||!r||[r.destination,r.stage,r.backup].some(l=>typeof l!="string"||!l))throw new Error("Invalid directory publication receipt");let s=this.database.prepare("SELECT * FROM transfer_publications WHERE transfer_id=?").get(e);if(s?.kind&&(s.kind!=="directory-tar"||s.destination_path!==r.destination||s.stage_path!==r.stage||s.backup_path!==r.backup))throw Object.assign(new Error("Directory publication identity changed"),{code:"idempotency_conflict"});let o={staged:1,backed_up:2,published:3,cleaned:4,failed:4};if(s?.phase&&s.phase!==n&&o[n]<o[s.phase])throw new Error("Directory publication phase cannot regress");if(s?.phase==="failed"&&n!=="failed")throw new Error("Failed directory publication is terminal");let c=Date.now();this.database.prepare(`INSERT INTO transfer_publications(transfer_id,started_at,kind,destination_path,stage_path,backup_path,phase,published_at,error_code)
|
|
374
|
+
VALUES (?,?,?,?,?,?,?,?,?)
|
|
375
|
+
ON CONFLICT(transfer_id) DO UPDATE SET kind=excluded.kind,destination_path=excluded.destination_path,stage_path=excluded.stage_path,
|
|
376
|
+
backup_path=excluded.backup_path,phase=excluded.phase,published_at=COALESCE(transfer_publications.published_at,excluded.published_at),error_code=excluded.error_code`).run(e,c,"directory-tar",r.destination,r.stage,r.backup,n,["published","cleaned"].includes(n)?c:null,n==="failed"?i||"directory_recovery_failed":null)}directoryPublication(e){let r=this.database.prepare(`SELECT p.*,t.offer_json,t.state AS transfer_state FROM transfer_publications p
|
|
377
|
+
JOIN transfers t ON t.id=p.transfer_id WHERE p.transfer_id=? AND p.kind='directory-tar'`).get(e);return r?{...r,offer:JSON.parse(r.offer_json)}:null}noteDirectoryCompletionReported(e){if(!this.database.prepare(`UPDATE transfer_publications SET completion_reported_at=COALESCE(completion_reported_at,?)
|
|
378
|
+
WHERE transfer_id=? AND kind='directory-tar' AND phase='cleaned'`).run(Date.now(),e).changes)throw new Error("Cleaned directory publication receipt is missing")}directoryPublications(){return this.database.prepare(`SELECT p.*,t.offer_json,t.state AS transfer_state FROM transfer_publications p
|
|
379
|
+
JOIN transfers t ON t.id=p.transfer_id WHERE p.kind='directory-tar' AND p.phase!='failed'
|
|
380
|
+
AND (p.phase!='cleaned' OR p.completion_reported_at IS NULL OR t.state!='completed') ORDER BY p.started_at`).all().map(e=>({...e,offer:JSON.parse(e.offer_json)}))}isTransferPublished(e){return!!this.database.prepare("SELECT 1 FROM transfer_publications WHERE transfer_id=? AND published_at IS NOT NULL").get(e)}hasTransferPublication(e){return!!this.database.prepare("SELECT 1 FROM transfer_publications WHERE transfer_id=?").get(e)}addJob(e){let r=this.database.prepare(`
|
|
381
|
+
INSERT OR IGNORE INTO jobs(id, state, payload_json, updated_at) VALUES (?, 'offered', ?, ?)
|
|
382
|
+
`).run(e.id,JSON.stringify(e),Date.now());return Number(r.changes)>0}getJob(e){let r=this.database.prepare("SELECT * FROM jobs WHERE id = ?").get(e);return r?{...r,payload:JSON.parse(r.payload_json)}:null}setJobState(e,r,{pid:n=void 0,completed:i=!1}={}){let s=Date.now(),o=["state = ?","updated_at = ?"],c=[r,s];n!==void 0&&(o.push("pid = ?"),c.push(n),n&&(o.push("started_at = COALESCE(started_at, ?)"),c.push(s))),i&&(o.push("completed_at = ?"),c.push(s)),c.push(e),this.database.prepare(`UPDATE jobs SET ${o.join(", ")} WHERE id = ?`).run(...c)}recoverInterruptedJobs(){let e=this.database.prepare(`
|
|
383
|
+
SELECT id FROM jobs WHERE state IN ('accepted', 'running', 'cancel_requested')
|
|
384
|
+
`).all();for(let r of e)this.setJobState(r.id,"needs_review",{pid:null,completed:!0});return e.map(r=>r.id)}queueJobEvent(e,r,n,i={}){let s=oi(),o={type:"job_event",event_id:s,job_id:e,event_type:r,state:n,payload:i,created_at:Date.now()};return this.queueMessage(s,e,o),o}queueTransferEvent(e,r,n={}){let i=oi(),s={type:"transfer_event",event_id:i,transfer_id:e,state:r,payload:n,created_at:Date.now()};return this.queueMessage(i,`transfer:${e}`,s),s}queueDownloadEvent(e,r,n={}){let i=oi(),s={type:"download_event",event_id:i,download_id:e,state:r,payload:n,created_at:Date.now()};return this.queueMessage(i,`download:${e}`,s),s}queueRegistryEvent(e){let r=oi(),n={...e,event_id:r,created_at:Date.now()};return this.queueMessage(r,`registry:${e.name||"unknown"}`,n),n}queueArtifactSourceEvent(e,r,n={}){let i=oi(),s={type:"artifact_source_event",event_id:i,transfer_id:e,state:r,payload:n,created_at:Date.now()};return this.queueMessage(i,`artifact-source:${e}`,s),s}queueTransferCancellation(e,r,n){let i=oi();this.queueMessage(i,`transfer-cancel:${e}:${r}`,{type:"transfer_cancel_result",event_id:i,transfer_id:e,role:r,state:n})}queueTransferPause(e,r,n){let i=oi();this.queueMessage(i,`transfer-pause:${e}:${r}`,{type:"transfer_pause_result",event_id:i,transfer_id:e,role:r,state:n})}queueMessage(e,r,n){this.database.prepare(`
|
|
385
|
+
INSERT OR IGNORE INTO outbound_events(event_id, job_id, message_json, created_at) VALUES (?, ?, ?, ?)
|
|
386
|
+
`).run(e,r,JSON.stringify(n),Date.now())}pendingEvents(e=250){return this.database.prepare(`
|
|
387
|
+
SELECT event_id, message_json FROM outbound_events ORDER BY created_at, rowid LIMIT ?
|
|
388
|
+
`).all(e).map(r=>({event_id:r.event_id,message:JSON.parse(r.message_json)}))}acknowledgeEvent(e){this.database.prepare("DELETE FROM outbound_events WHERE event_id = ?").run(e)}pruneFinishedWork(e=Date.now(),r=lP){let n=e-r;this.database.prepare(`DELETE FROM jobs WHERE completed_at IS NOT NULL AND completed_at < ?
|
|
389
|
+
AND NOT EXISTS (SELECT 1 FROM outbound_events e WHERE e.job_id = jobs.id)`).run(n),this.database.prepare(`DELETE FROM outgoing_downloads WHERE state IN ('completed','failed') AND updated_at < ?
|
|
390
|
+
AND NOT EXISTS (SELECT 1 FROM outbound_events e WHERE e.job_id = 'download:' || outgoing_downloads.id)`).run(n),this.database.prepare("DELETE FROM download_relay_stops WHERE stopped_at < ? AND download_id NOT IN (SELECT id FROM outgoing_downloads)").run(n),this.database.prepare("DELETE FROM wake_receipts WHERE created_at < ?").run(n)}putTransfer(e,r){let n=this.getTransfer(e.id);if(n){let i=a(s=>({kind:s.kind||"file",size:s.size,sha256:s.sha256,chunk_size:s.chunk_size,total_chunks:s.total_chunks,destination_path:s.destination_path,overwrite:!!s.overwrite}),"identity");if(n.part_path!==r||Ee(i(n.offer))!==Ee(i(e)))throw Object.assign(new Error("Transfer ID was already registered with different content or destination"),{code:"idempotency_conflict",terminal:!0})}this.database.prepare(`
|
|
391
|
+
INSERT INTO transfers(id, state, offer_json, chunks_json, part_path, updated_at)
|
|
392
|
+
VALUES (?, 'ready', ?, '[]', ?, ?)
|
|
393
|
+
ON CONFLICT(id) DO UPDATE SET offer_json = excluded.offer_json, updated_at = excluded.updated_at
|
|
394
|
+
`).run(e.id,JSON.stringify(e),r,Date.now())}markAllTransferChunks(e,r){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid transfer chunk count");let n=this.getTransfer(e);if(!n||n.offer.total_chunks!==r)throw new Error("Transfer chunk count changed");let i=Array.from({length:r},(s,o)=>o);return this.database.prepare(`
|
|
395
|
+
UPDATE transfers SET chunks_json = ?, received_bytes = ?, updated_at = ? WHERE id = ?
|
|
396
|
+
`).run(JSON.stringify(i),n.offer.size,Date.now(),e),i}beginRelayAttempt(e){let r=this.database.prepare(`
|
|
397
|
+
UPDATE transfers
|
|
398
|
+
SET relay_attempt = relay_attempt + 1, state = 'receiving', chunks_json = '[]', chunk_hashes_json = '{}',
|
|
399
|
+
received_bytes = relay_received_bytes, updated_at = ?
|
|
400
|
+
WHERE id = ?
|
|
401
|
+
RETURNING relay_attempt
|
|
402
|
+
`).get(Date.now(),e);if(!r)throw new Error("Transfer not found");return r.relay_attempt}setRelayAttemptProgress(e,r,n){let i=this.getTransfer(e);if(!i||i.relay_attempt!==r)throw new Error("Relay progress does not belong to the active transfer attempt");if(!Number.isSafeInteger(n)||n<0||n>i.offer.size)throw new Error("Relay progress is outside the transfer manifest");return this.database.prepare("UPDATE transfers SET received_bytes=?,relay_received_bytes=?,updated_at=? WHERE id=? AND relay_attempt=?").run(n,n,Date.now(),e,r),n}getTransfer(e){let r=this.database.prepare("SELECT * FROM transfers WHERE id = ?").get(e);return r?{...r,offer:JSON.parse(r.offer_json),chunks:JSON.parse(r.chunks_json),chunk_hashes:JSON.parse(r.chunk_hashes_json)}:null}markTransferChunk(e,r,n){let i=this.getTransfer(e);if(!i)throw new Error("Transfer not found");let s=i.chunks.includes(r),o=[...new Set([...i.chunks,r])].sort((l,d)=>l-d),c={...i.chunk_hashes};return n?c[r]=n:delete c[r],this.database.prepare(`
|
|
403
|
+
UPDATE transfers SET state = 'receiving', chunks_json = ?, chunk_hashes_json = ?, received_bytes = ?, updated_at = ? WHERE id = ?
|
|
404
|
+
`).run(JSON.stringify(o),JSON.stringify(c),i.received_bytes+(s?0:Fp(i.offer,r)),Date.now(),e),o}invalidateTransferChunk(e,r,n){let i=this.getTransfer(e);if(!i||i.state==="completed"||i.chunk_hashes[r]!==n)return;delete i.chunk_hashes[r];let s=i.chunks.includes(r);this.database.prepare("UPDATE transfers SET chunks_json=?, chunk_hashes_json=?, received_bytes=?, updated_at=? WHERE id=?").run(JSON.stringify(i.chunks.filter(o=>o!==r)),JSON.stringify(i.chunk_hashes),Math.max(0,i.received_bytes-(s?Fp(i.offer,r):0)),Date.now(),e)}setTransferState(e,r){this.database.prepare("UPDATE transfers SET state = ?, updated_at = ? WHERE id = ?").run(r,Date.now(),e)}transfersForReceivedCleanup(){return this.database.prepare("SELECT id,state,offer_json,part_path,updated_at FROM transfers ORDER BY updated_at,id").all().map(e=>({...e,offer:JSON.parse(e.offer_json)}))}downloadsForReceivedCleanup(){return this.database.prepare("SELECT id,state,source_path,prepared_path,updated_at FROM outgoing_downloads ORDER BY updated_at,id").all()}receivedCleanupItem(e){return this.database.prepare("SELECT * FROM received_cleanup_items WHERE item_key=?").get(e)||null}planReceivedCleanup({itemKey:e,ownerId:r,role:n,path:i,quarantinePath:s,expected:o,expectedSha256:c=null}){let l=Ee(o),d=this.receivedCleanupItem(e);if(d){if(d.owner_id!==r||d.role!==n||d.path!==i||d.quarantine_path!==s||d.expected_json!==l||d.expected_sha256!==c)throw Object.assign(new Error("Received cleanup identity changed"),{code:"idempotency_conflict"});return d}let u=Date.now();return this.database.prepare(`INSERT INTO received_cleanup_items(
|
|
405
|
+
item_key,owner_id,role,path,quarantine_path,expected_json,expected_sha256,state,planned_at,updated_at
|
|
406
|
+
) VALUES (?,?,?,?,?,?,?,'planned',?,?)`).run(e,r,n,i,s,l,c,u,u),this.receivedCleanupItem(e)}setReceivedCleanupState(e,r,n={}){if(!["planned","quarantined","deleting","deleted","missing","changed","failed"].includes(r))throw new Error("Invalid received cleanup state");let i=Date.now();return this.database.prepare("UPDATE received_cleanup_items SET state=?,updated_at=?,completed_at=?,error_code=?,error_message=? WHERE item_key=?").run(r,i,["deleted","missing","changed","failed"].includes(r)?i:null,n.code||null,n.message?String(n.message).slice(0,1e3):null,e),this.receivedCleanupItem(e)}noteReceivedCleanupError(e,r,n){this.database.prepare("UPDATE received_cleanup_items SET updated_at=?,error_code=?,error_message=? WHERE item_key=?").run(Date.now(),String(r||"cleanup_failed").slice(0,100),String(n||"Cleanup failed").slice(0,1e3),e)}pendingReceivedCleanup(e=100){return this.database.prepare(`SELECT * FROM received_cleanup_items WHERE state IN ('planned','quarantined','deleting')
|
|
407
|
+
ORDER BY planned_at,item_key LIMIT ?`).all(Number(e))}receivedCleanupStatus(e=20){let r=Object.fromEntries(this.database.prepare("SELECT state,COUNT(*) AS count FROM received_cleanup_items GROUP BY state").all().map(i=>[i.state,Number(i.count)])),n=this.database.prepare(`SELECT item_key,owner_id,role,path,state,planned_at,updated_at,completed_at,error_code,error_message
|
|
408
|
+
FROM received_cleanup_items ORDER BY updated_at DESC,item_key LIMIT ?`).all(Number(e));return{counts:r,pending:Number(r.planned||0)+Number(r.quarantined||0)+Number(r.deleting||0),recent:n}}claimReceivedCleanupRun(e,r=Date.now(),n=3600*1e3){this.database.exec("BEGIN IMMEDIATE");try{let i=this.database.prepare("SELECT owner,expires_at FROM received_cleanup_lock WHERE singleton=1").get();return i&&i.owner!==e&&i.expires_at>r?(this.database.exec("COMMIT"),!1):(this.database.prepare(`INSERT INTO received_cleanup_lock(singleton,owner,expires_at) VALUES (1,?,?)
|
|
409
|
+
ON CONFLICT(singleton) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at`).run(e,r+n),this.database.exec("COMMIT"),!0)}catch(i){throw this.database.exec("ROLLBACK"),i}}renewReceivedCleanupRun(e,r=Date.now(),n=3600*1e3){return this.database.prepare("UPDATE received_cleanup_lock SET expires_at=? WHERE singleton=1 AND owner=?").run(r+n,e).changes>0}releaseReceivedCleanupRun(e){this.database.prepare("DELETE FROM received_cleanup_lock WHERE singleton=1 AND owner=?").run(e)}putDownload(e){let r=this.getDownload(e.id);if(r){let n=a(i=>{let s=i.artifact_id||null;return{source_path:i.source_path||null,job_id:i.job_id||null,artifact_id:s,source_library:s&&i.source_library||null,source_relative_path:s&&i.source_relative_path||null,sha256:s&&i.sha256||null,size:s?i.size??null:null,relative_path:i.relative_path||".",chunk_size:i.chunk_size}},"identity");if(Ee(n(r.offer))!==Ee(n(e)))throw Object.assign(new Error("Download ID was already registered with a different source or chunk layout"),{code:"idempotency_conflict",terminal:!0})}this.database.prepare(`
|
|
410
|
+
INSERT INTO outgoing_downloads(id, state, offer_json, updated_at)
|
|
411
|
+
VALUES (?, 'preparing', ?, ?)
|
|
412
|
+
ON CONFLICT(id) DO UPDATE SET offer_json = excluded.offer_json, updated_at = excluded.updated_at
|
|
413
|
+
`).run(e.id,JSON.stringify(e),Date.now())}stopDownloadRelay(e,r){if(![e,r].every(n=>typeof n=="string"&&n.length>0&&n.length<=200))throw new Error("Invalid relay stop identity");this.database.prepare("INSERT OR IGNORE INTO download_relay_stops(download_id,relay_id,stopped_at) VALUES (?,?,?)").run(e,r,Date.now())}isDownloadRelayStopped(e,r){return!!this.database.prepare("SELECT 1 FROM download_relay_stops WHERE download_id=? AND relay_id=?").get(e,r)}getDownload(e){let r=this.database.prepare("SELECT * FROM outgoing_downloads WHERE id = ?").get(e);return r?{...r,temporary:!!r.temporary,offer:JSON.parse(r.offer_json),manifest:r.manifest_json?JSON.parse(r.manifest_json):null}:null}readyDownload(e,{sourcePath:r,preparedPath:n,kind:i,temporary:s,manifest:o}){this.database.prepare(`
|
|
414
|
+
UPDATE outgoing_downloads SET state = 'ready', source_path = ?, prepared_path = ?,
|
|
415
|
+
kind = ?, temporary = ?, manifest_json = ?, updated_at = ?, failure_code = NULL, failure_message = NULL WHERE id = ?
|
|
416
|
+
`).run(r,n,i,s?1:0,JSON.stringify(o),Date.now(),e)}setDownloadState(e,r,n={}){this.database.prepare("UPDATE outgoing_downloads SET state = ?, updated_at = ?, failure_code = ?, failure_message = ? WHERE id = ?").run(r,Date.now(),r==="failed"?n.code||"download_preparation_failed":null,r==="failed"?n.message||"Download preparation failed":null,e)}cachedLibraryHash(e,r,{fileId:n,size:i,mtimeMs:s,revision:o}){return o&&this.database.prepare(`
|
|
417
|
+
SELECT sha256 FROM library_hash_cache
|
|
418
|
+
WHERE library_name=? AND relative_path=? AND file_id IS ? AND size=? AND mtime_ms=? AND revision=?
|
|
419
|
+
`).get(e,r,n||null,i,Math.floor(s),o)?.sha256||null}cacheLibraryHash(e,r,{fileId:n,size:i,mtimeMs:s,sha256:o,revision:c}){this.database.prepare(`
|
|
420
|
+
INSERT INTO library_hash_cache(library_name, relative_path, file_id, size, mtime_ms, sha256, updated_at, revision)
|
|
421
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
422
|
+
ON CONFLICT(library_name, relative_path) DO UPDATE SET
|
|
423
|
+
file_id=excluded.file_id, size=excluded.size, mtime_ms=excluded.mtime_ms,
|
|
424
|
+
sha256=excluded.sha256, updated_at=excluded.updated_at, revision=excluded.revision
|
|
425
|
+
`).run(e,r,n||null,i,Math.floor(s),o,Date.now(),c||null)}pruneLibraryHashCache(e,r){if(r.length===0){this.database.prepare("DELETE FROM library_hash_cache WHERE library_name=?").run(e);return}let n=new Set(r),i=this.database.prepare("SELECT relative_path FROM library_hash_cache WHERE library_name=?").all(e),s=this.database.prepare("DELETE FROM library_hash_cache WHERE library_name=? AND relative_path=?");for(let o of i)n.has(o.relative_path)||s.run(e,o.relative_path)}close(){this.database.close()}};a(Fp,"transferChunkLength")});var Q0={};K(Q0,{UPDATE_NOTICE_INTERVAL_MS:()=>qp,compareVersions:()=>K0,maybePrintUpdateNotice:()=>pP,updateNotice:()=>Z0});import{readFileSync as dP}from"node:fs";import{join as uP}from"node:path";function K0(t,e){let r=String(t).split(".").map(Number),n=String(e).split(".").map(Number);for(let i=0;i<3;i+=1)if((r[i]||0)!==(n[i]||0))return(r[i]||0)-(n[i]||0);return 0}function Z0({current:t,latest:e,lastShownAt:r=0,now:n=Date.now()}){return!e||K0(e,t)<=0||n-r<qp?null:`Update available: npm i -g interscale@latest (${t} \u2192 ${e})`}async function pP({client:t,current:e,env:r=process.env,now:n=Date.now(),write:i=a(s=>process.stderr.write(`${s}
|
|
426
|
+
`),"write")}){let s=uP(x(r),"npm-update-check.json"),o={};try{o=JSON.parse(dP(s,"utf8"))}catch{o={}}if(n-(o.checked_at||0)<qp)return null;try{let c=await Promise.race([t.latestRelease(),new Promise(d=>setTimeout(d,hP,null).unref())]),l=Z0({current:e,latest:c?.manifest?.version,lastShownAt:o.shown_at||0,now:n});return l&&i(l),xe(x(r)),Rt(s,{checked_at:n,shown_at:l?n:o.shown_at||0}),l}catch{return null}}var qp,hP,ev=v(()=>{Re();Z();qp=864e5,hP=2e3;a(K0,"compareVersions");a(Z0,"updateNotice");a(pP,"maybePrintUpdateNotice")});var Wp={};K(Wp,{JOIN_ONLINE_WAIT_MS:()=>nv,installedCliCommand:()=>iv,joinThisComputer:()=>zp});import{spawnSync as fP}from"node:child_process";import{createHash as mP}from"node:crypto";import{createReadStream as _P,createWriteStream as gP,existsSync as tv,mkdtempSync as wP,rmSync as yP}from"node:fs";import{tmpdir as bP,userInfo as vP}from"node:os";import{join as rr}from"node:path";import{Readable as EP}from"node:stream";import{pipeline as rv}from"node:stream/promises";import{setTimeout as SP}from"node:timers/promises";function iv({platform:t=process.platform,env:e=process.env}={}){return t==="win32"?`& "${rr(e.LOCALAPPDATA||"","Programs","Interscale","interscale.cmd")}"`:t==="darwin"?ai:cn}async function zp({client:t,releaseKey:e,name:r,platform:n=process.platform,arch:i=process.arch,env:s=process.env,run:o=xP,download:c=RP,waitOnline:l=null,log:d=a(()=>{},"log"),user:u=vP().username,isRoot:h=process.getuid?.()===0,hasSystemd:p=tv("/run/systemd/system"),temporaryRoot:f=bP()}={}){if(tv(L(s)))return{joined:!1,reason:"already_enrolled"};if(n==="linux"&&h)return{joined:!1,reason:"run_as_user"};let m=await t.latestRelease();if(!m)return{joined:!1,reason:"no_release"};let _,w;try{let y=bo(m,e),E=y.manifest.artifacts.filter(S=>S.platform===n&&S.arch===i);if(E.length!==1)return{joined:!1,reason:"release_artifact_missing"};[_]=E,w=y.manifest.version}catch(y){return{joined:!1,reason:y.code||"release_signature_invalid"}}let g=wP(rr(f,"interscale-join-"));try{let y=rr(g,_.file_name);if(d(`Downloading Interscale ${w}...`),await c(_.url,y),await OP(y)!==_.sha256)return{joined:!1,reason:"download_mismatch"};let{steps:E,boot:S}=kP({platform:n,arch:i,version:w,file:y,work:g,name:r,env:s,user:u,isRoot:h,hasSystemd:p});for(let q of E)if(d(q.say),o(q.argv,{interactive:q.interactive}).status!==0)return{joined:!1,reason:"install_failed",step:q.say};let k=null;for(let q of S)if(d(q.say),o(q.argv,{interactive:q.interactive}).status!==0){k=q.retry;break}if(n==="linux"&&(k||!p))return{joined:!0,kind:Pr(n),online:!1,running:!1,start:k||`${cn} agent foreground`};let $=l?await l(r):await IP(t,r);return{joined:!0,kind:Pr(n),online:$,...k?{boot_retry:k}:{}}}finally{yP(g,{recursive:!0,force:!0})}}function kP({platform:t,arch:e,version:r,file:n,work:i,name:s,env:o,user:c,isRoot:l,hasSystemd:d}){let u=a(h=>l?h:["sudo",...h],"sudo");if(t==="linux"){let h=rr(i,`Interscale-${r}-linux-${e==="x64"?"amd64":e}`),p=d?[{say:"Preparing the agent to start at boot...",argv:[cn,"agent","prepare-boot"],interactive:!1,retry:`${cn} agent prepare-boot && sudo ${cn} agent enable-boot --owner ${c}`},{say:"Starting the agent at boot (sudo)...",argv:u([cn,"agent","enable-boot","--owner",c]),interactive:!0,retry:`sudo ${cn} agent enable-boot --owner ${c}`}]:[];return{steps:[{say:"Unpacking...",argv:["tar","-xzf",n,"-C",i],interactive:!1},{say:"Installing in /opt/interscale (sudo)...",argv:u([rr(h,"install.sh")]),interactive:!0},{say:`Connecting this computer as ${s}...`,argv:[cn,"agent","install","--name",s,"--no-service"],interactive:!1}],boot:p}}if(t==="win32"){let h=rr(o.LOCALAPPDATA,"Programs","Interscale");return{steps:[{say:"Unpacking...",argv:[rr(o.SystemRoot||"C:\\Windows","System32","tar.exe"),"-xf",n,"-C",i],interactive:!1},{say:`Installing and connecting this computer as ${s}...`,argv:["powershell.exe","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",rr(i,`Interscale-${r}-windows-x64`,"install.ps1"),"-Name",s],interactive:!1}],boot:[{say:"To stay reachable after a restart, before anyone signs in, Windows needs this account's password once.",argv:[rr(h,"node","node.exe"),rr(h,"app","bin","interscale.mjs"),"agent","enable-boot"],interactive:!0,retry:`${iv({platform:t,env:o})} agent enable-boot`}]}}if(t==="darwin")return{steps:[{say:"Installing Interscale (sudo)...",argv:["sudo","installer","-pkg",n,"-target","/"],interactive:!0},{say:`Connecting this computer as ${s}...`,argv:[ai,"agent","install","--name",s],interactive:!1}],boot:[{say:"Preparing the agent to start at boot...",argv:[ai,"agent","prepare-boot"],interactive:!1,retry:`${ai} agent prepare-boot && sudo ${ai} agent enable-boot`},{say:"Starting the agent at boot (sudo)...",argv:["sudo",ai,"agent","enable-boot"],interactive:!0,retry:`sudo ${ai} agent enable-boot`}]};throw Object.assign(new Error(`Interscale has no package for ${t}`),{code:"release_target_unsupported"})}function xP(t,{interactive:e}){let r=fP(t[0],t.slice(1),{stdio:e?"inherit":["ignore","pipe","pipe"],windowsHide:!0,shell:!1,encoding:"utf8"});return r.status!==0&&!e&&process.stderr.write(`${r.stderr||r.error?.message||""}`.slice(-4e3)),{status:r.status??1}}async function RP(t,e){if(new URL(t).protocol!=="https:")throw new Error("Release downloads must use HTTPS");let r=await fetch(t,{signal:AbortSignal.timeout(30*6e4)});if(!r.ok||!r.body)throw new Error(`The download failed (HTTP ${r.status})`);await rv(EP.fromWeb(r.body),gP(e,{mode:384}))}async function OP(t){let e=mP("sha256");return await rv(_P(t),e),e.digest("hex")}async function IP(t,e){let r=Date.now()+nv;for(;Date.now()<r;){try{let{nodes:n=[]}=await t.nodes({view:"summary",limit:1e3});if(n.some(i=>i.name===e&&i.status==="online"))return!0}catch{}await SP(TP)}return!1}var nv,TP,cn,ai,Sl=v(()=>{Oo();Z();Xn();nv=12e4,TP=2e3,cn="/opt/interscale/bin/interscale",ai="/usr/local/bin/interscale";a(iv,"installedCliCommand");a(zp,"joinThisComputer");a(kP,"installSteps");a(xP,"runStep");a(RP,"downloadFile");a(OP,"sha256File");a(IP,"waitUntilOnline")});import{setTimeout as NP}from"node:timers/promises";async function sv({serverUrl:t,name:e,platform:r,arch:n,onCode:i=a(()=>{},"onCode"),sleep:s=a((c,l)=>NP(c,void 0,{signal:l}),"sleep"),signal:o}={}){let c=await ne(t,"/v1/auth/device",{method:"POST",json:{name:e,platform:r,arch:n},signal:o});await i(c);let l=c.interval*1e3;for(;;){await s(l,o);try{return await ne(t,"/v1/auth/device/token",{method:"POST",json:{device_code:c.device_code},signal:o})}catch(d){if(d.code==="authorization_pending")continue;if(d.code==="slow_down"){l+=AP;continue}throw d}}}var AP,ov=v(()=>{cr();AP=5e3;a(sv,"deviceLogin")});import{spawn as LP}from"node:child_process";function av(t,{platform:e=process.platform,env:r=process.env,spawn:n=LP}={}){let i;try{i=new URL(t)}catch{return!1}if(!(i.protocol==="https:"||i.protocol==="http:"&&CP.has(i.hostname))||r.SSH_CONNECTION||r.SSH_TTY)return!1;let[s,o]=e==="win32"?["rundll32",["url.dll,FileProtocolHandler",i.toString()]]:e==="darwin"?["open",[i.toString()]]:r.DISPLAY||r.WAYLAND_DISPLAY?["xdg-open",[i.toString()]]:[];if(!s)return!1;try{let c=n(s,o,{stdio:"ignore",windowsHide:!0,shell:!1});return c.on("error",()=>{}),c.unref(),!0}catch{return!1}}var CP,cv=v(()=>{CP=new Set(["127.0.0.1","localhost","[::1]"]);a(av,"openBrowser")});var dv={};K(dv,{OFFICIAL_RELEASE_PUBLIC_KEY:()=>lv,releaseKeyOverride:()=>Hp,trustedReleaseKey:()=>Lo});import{readFileSync as PP}from"node:fs";function Lo({hubKey:t=null,override:e=null}={}){let r=nt(e||lv),n=!1;if(t)try{n=nt(t).key_id===r.key_id}catch{n=!1}return{pem:r.pem,key_id:r.key_id,matches_hub:n}}function Hp({file:t=null,env:e=process.env}={}){if(t)return PP(t,"utf8");let r=e.INTERSCALE_RELEASE_PUBLIC_KEY;return r?r.replaceAll("\\n",`
|
|
427
|
+
`):null}var lv,Gp=v(()=>{Xn();lv=`-----BEGIN PUBLIC KEY-----
|
|
428
|
+
MCowBQYDK2VwAyEAeZf6hnFRdCp/rz8gdOaYBKut4CTvB4Gn6b466XpeTcM=
|
|
429
|
+
-----END PUBLIC KEY-----
|
|
430
|
+
`;a(Lo,"trustedReleaseKey");a(Hp,"releaseKeyOverride")});var Jp={};K(Jp,{describeJoin:()=>pv,loginCommand:()=>UP,shouldOfferJoin:()=>hv});import{hostname as DP}from"node:os";import{createInterface as $P}from"node:readline/promises";async function UP(t,e={}){let r=e.env||process.env,n=e.say||(h=>process.stderr.write(`${h}
|
|
431
|
+
`)),i=ua(t.hub||t.server||Am),s=Hp({file:t["release-key"]||null,env:r}),o=t.name||DP();if(t["token-stdin"]){let h=String(await e.readSecret()).trim();if(h.length<32)throw new Error("The sign-in token on standard input is missing or too short");let p=await ne(i,"/v1/account",{token:h}),f=await ne(i,"/v1/account/sessions",{token:h}),m=Lo({override:s});return ha({token:h,token_id:f.current_token_id,server_url:i,user:p.user,release_public_key:m.pem},r),n(`Signed in as ${p.user.email} on ${i}.`),Tl({server_url:i,token_id:f.current_token_id,user:p.user},e)}if(t.email||t["password-stdin"]){let h=t["password-stdin"]?await e.readSecret():await e.readHiddenLine("Interscale password: "),p=await gd({serverUrl:i,email:t.email,password:h,name:o},r),f=await Tl({server_url:p.server_url,token_id:p.token_id,...p.user?{user:p.user}:{}},t.email?e:{}),m=t.email?await uv(t,e,{hub:i,token:p.token,releaseKey:Lo({override:s}).pem,name:o,env:r,say:n}):null;return{...f,...m?{join:m}:{}}}let c;try{c=await sv({serverUrl:i,name:o,platform:e.platform||process.platform,arch:e.arch||process.arch,sleep:e.sleep,onCode:a(async h=>{n(`Open ${h.verification_uri} and enter ${h.user_code}`),(e.openBrowser||av)(h.verification_uri_complete,{env:r})&&n("Opening your browser\u2026"),n("Waiting for approval\u2026"),await e.onCode?.(h)},"onCode")})}catch(h){if(h.code!=="account_required")throw h;let p=await e.readHiddenLine("Interscale fleet password: "),f=await gd({serverUrl:i,password:p,name:o},r);return Tl({server_url:f.server_url,token_id:f.token_id},{})}let l=Lo({hubKey:c.release_public_key,override:s});ha({...c,server_url:i,release_public_key:l.pem},r),n(`Signed in as ${c.user.email} on ${i}.`),l.matches_hub||n("This hub signs its releases with another key, so adding computers from here is off. If you run this hub, sign in again with --release-key <its public key file>.");let d=await Tl({server_url:i,token_id:c.token_id,user:c.user},e),u=l.matches_hub?await uv(t,e,{hub:i,token:c.token,releaseKey:l.pem,name:o,env:r,say:n}):null;return{...d,...u?{join:u}:{}}}function hv({tty:t,options:e}){return e["token-stdin"]||e["no-join"]?!1:!!e.join||!!t}async function uv(t,e,{hub:r,token:n,releaseKey:i,name:s,env:o,say:c}){let l=e.tty??!!(process.stdin.isTTY&&process.stderr.isTTY);if(!hv({tty:l,options:t}))return t["no-join"]||c("To add this computer to your fleet later, run: interscale join"),null;let d=e.platform||process.platform;if(!t.join&&!await(e.confirm||MP)(`Add this computer to your fleet as a ${Pr(d)}? [Y/n] `))return c("Skipped. Run interscale join any time."),{joined:!1,reason:"declined"};let u=await(e.join||zp)({client:new Je(r,n),releaseKey:i,name:s,platform:d,env:o,log:c});return c(pv(u,s)),u}function pv(t,e){if(t.joined&&t.running===!1)return`Added ${e} as a ${t.kind}, but its agent is not running yet. Run: ${t.start}`;if(t.joined){let r=`Added ${e} as a ${t.kind}.`;return t.online||(r+=` It is still starting: check with interscale ${t.kind}s.`),t.boot_retry&&(r+=` To keep it reachable after a restart, run: ${t.boot_retry}`),r}return t.reason==="install_failed"?`Installing stopped at "${t.step}". Run interscale join to try again.`:jP[t.reason]||`Nothing was installed (${t.reason}).`}async function MP(t){let e=$P({input:process.stdin,output:process.stderr});try{return/^(|y|yes)$/i.test((await e.question(t)).trim())}finally{e.close()}}async function Tl(t,e){let r=await e.installMcp?.();return{activated:!0,...t,...r?{mcp:r}:{}}}var jP,Vp=v(()=>{me();pa();ov();cr();cv();Gp();md();ol();Sl();Oo();a(UP,"loginCommand");a(hv,"shouldOfferJoin");a(uv,"offerJoin");jP={already_enrolled:"This computer is already in your fleet.",run_as_user:"Nothing was installed: run interscale join as the account that will own the agent, not as root (it asks for sudo when it needs it).",declined:"Skipped. Run interscale join any time.",no_release:"Nothing was installed: no release is published yet. Run interscale join later.",release_artifact_missing:"Nothing was installed: there is no Interscale package for this system yet.",release_key_mismatch:"Nothing was installed: the hub's release is not signed with the Interscale release key.",release_signature_invalid:"Nothing was installed: the release signature is not valid.",download_mismatch:"Nothing was installed: the download did not match its signed checksum. Run interscale join to try again.",release_target_unsupported:"Nothing was installed: Interscale has no package for this system."};a(pv,"describeJoin");a(MP,"confirm");a(Tl,"finish")});var gv={};K(gv,{runApiBenchmark:()=>BP});import{performance as fv}from"node:perf_hooks";async function BP(t,e={}){let r=_v(e.samples??200,1,1e4,"samples"),n=_v(e.warmup??Math.min(10,r),0,1e3,"warmup"),i=e.endpoint||"summary",s=i==="health"?()=>t.request("/health"):i==="nodes"?()=>t.nodes():i==="summary"?()=>t.fleetSummary():null;if(!s)throw new Error("benchmark endpoint must be health, summary or nodes");for(let l=0;l<n;l+=1)await s();let o=[],c=[];for(let l=0;l<r;l+=1){let d=fv.now();try{await s(),o.push(fv.now()-d)}catch(u){c.push({index:l,code:u.code||"request_failed",message:u.message})}}return o.sort((l,d)=>l-d),{schema:"interscale.benchmark/v1",revision:we,endpoint:i,samples:r,warmup:n,completed:o.length,errors:c.slice(0,100),error_count:c.length,milliseconds:o.length?{min:o[0],p50:mv(o,.5),p95:mv(o,.95),max:o.at(-1),mean:o.reduce((l,d)=>l+d,0)/o.length}:null}}function mv(t,e){return t[Math.min(t.length-1,Math.max(0,Math.ceil(t.length*e)-1))]}function _v(t,e,r,n){let i=Number(t);if(!Number.isSafeInteger(i)||i<e||i>r)throw new Error(`${n} must be between ${e} and ${r}`);return i}var wv=v(()=>{me();a(BP,"runApiBenchmark");a(mv,"percentile");a(_v,"bounded")});function yv({limit:t=100,cursor:e=null}={}){if(!Number.isSafeInteger(t)||t<1||t>1e3||e!==null&&(typeof e!="string"||!e.length||e.length>16e3))throw new N(400,"invalid_workspace_page","Use a limit from 1 to 1000 and a valid workspace cursor");return{limit:t,cursor:e}}function bv(t,e=100){let r=a(()=>{throw new N(502,"invalid_workspace_page","Worker returned an invalid workspace page")},"fail"),n=a((o,c)=>typeof o=="string"&&o.length>0&&o.length<=c,"text");(!t||!n(t.revision,64)||!/^[a-f0-9]{64}$/.test(t.revision)||!Number.isSafeInteger(t.observed_at)||!Number.isSafeInteger(t.total_count)||t.total_count<0||t.total_count>1e3||!Array.isArray(t.workspaces)||t.workspaces.length>e||t.workspaces.length>t.total_count||t.next_cursor!==null&&!n(t.next_cursor,16e3))&&r();let i=t.workspaces.map(o=>((!o||!n(o.name,200)||!n(o.path,32768)||o.name.includes("\0")||o.path.includes("\0")||o.canonical_path!==null&&!n(o.canonical_path,32768)||!["verified","missing","inaccessible","not_directory"].includes(o.status)||o.status==="verified"&&!o.canonical_path||o.workspace_revision!==go(o.name,o.path))&&r(),{name:o.name,path:o.path,canonical_path:o.canonical_path,status:o.status,workspace_revision:o.workspace_revision}));new Set(i.map(o=>o.name)).size!==i.length&&r();let s={revision:t.revision,observed_at:t.observed_at,total_count:t.total_count,workspaces:i,next_cursor:t.next_cursor};return Buffer.byteLength(JSON.stringify(s))>512*1024&&r(),s}var vv=v(()=>{wo();ye();a(yv,"workspacePageOptions");a(bv,"publicWorkspacePage")});var Sv={};K(Sv,{listLocalWorkspaces:()=>JP,listWorkspacePage:()=>GP});import{realpathSync as FP,statSync as qP}from"node:fs";import{realpath as zP,stat as WP}from"node:fs/promises";import{createHash as HP}from"node:crypto";async function GP(t,{signal:e,...r}={}){e?.throwIfAborted();let{limit:n,cursor:i}=yv(r);Xc(t.path_aliases);let s=Yp(t),o=Ev(t,s),c="";if(i!==null){let h;try{if(h=JSON.parse(Buffer.from(i,"base64url").toString("utf8")),h.v!==1||h.node_id!==t.node_id||typeof h.after!="string"||!h.after.length||h.after.length>200||typeof h.revision!="string"||!/^[a-f0-9]{64}$/.test(h.revision))throw new Error}catch{throw new N(400,"invalid_cursor","Workspace cursor belongs to another node or is invalid")}if(h.revision!==o)throw new N(409,"workspace_list_changed","Workspace configuration changed; restart listing from the first page");c=h.after}let l={revision:o,observed_at:Date.now(),total_count:s.length,workspaces:[],next_cursor:null},d=Buffer.byteLength(JSON.stringify(l))+16e3;for(let[h,p]of s){if(h<=c)continue;if(e?.throwIfAborted(),l.workspaces.length>=n)break;let f=null,m;try{f=await zP(p),e?.throwIfAborted(),m=(await WP(f)).isDirectory()?"verified":"not_directory"}catch(g){e?.throwIfAborted(),m=["ENOENT","ENOTDIR"].includes(g.code)?"missing":"inaccessible",f=null}e?.throwIfAborted();let _={name:h,path:p,canonical_path:f,status:m,workspace_revision:go(h,p)},w=Buffer.byteLength(JSON.stringify(_))+1;if(d+w>512*1024)break;d+=w,l.workspaces.push(_)}if(e?.throwIfAborted(),Ev(t,Yp(t))!==o)throw new N(409,"workspace_list_changed","Workspace configuration changed during inspection; restart listing");let u=l.workspaces.at(-1)?.name;return u!==void 0&&s.some(([h])=>h>u)&&(l.next_cursor=Buffer.from(JSON.stringify({v:1,node_id:t.node_id,revision:o,after:u})).toString("base64url")),bv(l,n)}function JP(t){let e=X(t);return{node_id:e.node_id,workspaces:Yp(e).map(([r,n])=>({name:r,path:n,workspace_revision:go(r,n),...VP(n)}))}}function VP(t){try{let e=FP(t);return{canonical_path:e,status:qP(e).isDirectory()?"verified":"not_directory"}}catch(e){return{canonical_path:null,status:["ENOENT","ENOTDIR"].includes(e.code)?"missing":"inaccessible"}}}var Yp,Ev,Tv=v(()=>{wo();vv();ye();So();Yp=a(t=>Object.entries(t.path_aliases||{}).sort(([e],[r])=>e<r?-1:e>r?1:0),"aliases"),Ev=a((t,e)=>HP("sha256").update(JSON.stringify(["workspace-list.v1",t.node_id,e])).digest("hex"),"revisionOf");a(GP,"listWorkspacePage");a(JP,"listLocalWorkspaces");a(VP,"inspectRoot")});var kv,T3,Xp,Kp,k3,Zp=v(()=>{kv=200,T3=16*1024,Xp=32*1024,Kp=512*1024,k3=15*6e4});var xv={};K(xv,{termCommand:()=>XP});async function XP(t,e,r,n,i,s){let[o,...c]=r;if(!e||!o)throw new Error("Usage: interscale term <machine> list|send|capture|start|kill ...");if(o==="list"){let l=await t.runTerminal(e,{op:"list"});if(i.json)return s({sessions:l.sessions},i);if(l.sessions.length===0)return console.log("No terminal sessions.");console.table(l.sessions.flatMap(d=>d.panes.map(u=>({target:u.target,pane:u.pane_id??"",command:u.command,size:`${u.width}x${u.height}`,active:u.active?"yes":"",clients:d.attached_clients}))));return}if(o==="send"){let l=c[0],d=KP(i),u=i.text??(n.length?n.join(" "):void 0);if(!l||u===void 0&&d.length===0)throw new Error('Usage: interscale term <machine> send <target> --text "..." [--enter] | --key C-c[,Escape,...]');let h={op:"send",target:l};d.length>0?h.keys=d:(h.text=u,A(i.enter,!1)&&(h.enter=!0));let p=await t.runTerminal(e,h);if(i.json)return s({sent:p.sent,target:l},i);console.error(`sent to ${l}`);return}if(o==="capture"){let l=c[0];if(!l)throw new Error("Usage: interscale term <machine> capture <target> [--lines 200] [--ansi]");let d=await t.runTerminal(e,{op:"capture",target:l,lines:Number(i.lines||kv)});if(i.json)return s({target:l,text:d.text},i);process.stdout.write(A(i.ansi,!1)?d.text:d.text.replace(YP,""));return}if(o==="start"){let l=c[0];if(!l)throw new Error("Usage: interscale term <machine> start <session> [--cwd-alias A] [--cols N --rows N] [-- command args]");let d={op:"start",session:l};i["cwd-alias"]&&(d.cwd_alias=i["cwd-alias"]),i.cols&&(d.cols=Number(i.cols)),i.rows&&(d.rows=Number(i.rows)),n.length&&(d.command=n);let u=await t.runTerminal(e,d);if(i.json)return s({session:u.session,created:u.created},i);console.log(`${l} created`);return}if(o==="kill"){let l=c[0];if(!l)throw new Error("Usage: interscale term <machine> kill <session>");let d=await t.runTerminal(e,{op:"kill",session:l});if(i.json)return s({session:d.session,killed:d.killed},i);console.log(`${l} killed`);return}throw new Error("Usage: interscale term <machine> list|send|capture|start|kill ...")}function KP(t){return t.key===void 0?[]:String(t.key).split(",").filter(Boolean)}var YP,Rv=v(()=>{zo();Zp();YP=/\x1b\[[0-9;:]*m/g;a(XP,"termCommand");a(KP,"collectKeys")});var Ov={};K(Ov,{shellCommand:()=>QP});async function QP(t,e,r,n,i){if(!r)throw new Error("Usage: interscale shell <machine> [--session NAME] [--no-create] [--cwd-alias A] [-- command args]");if(!process.stdin.isTTY||!process.stdout.isTTY)throw new Error("interscale shell needs an interactive terminal; use `interscale term` for scripted control");let s=n.session||"interscale",o=!tD(n["no-create"]),c=0,l=!0,d=!1;for(;!d;){let u=Date.now(),h=await eD(t,e,{node:r,sessionName:s,create:l?o:!1,command:i.length?i:void 0,cwdAlias:n["cwd-alias"]});if(l=!1,d=h.detached,d)break;if(Date.now()-u>=3e4&&(c=0),c+=1,!h.retryable){h.message&&process.stderr.write(`${h.message}
|
|
432
|
+
`),process.exitCode=h.clean?0:2;return}let p=Math.min(3e4,1e3*2**(c-1));process.stderr.write(`connection lost (${h.message||"unknown"}); re-attaching in ${p/1e3}s...
|
|
433
|
+
`),await new Promise(f=>setTimeout(f,p))}}function eD(t,e,{node:r,sessionName:n,create:i,command:s,cwdAlias:o}){return new Promise(c=>{let l=new URL("/v1/shell/connect",`${t}/`);l.protocol=l.protocol==="https:"?"wss:":"ws:";let d=new ut.default(l,{headers:{authorization:`Bearer ${e}`},perMessageDeflate:!1,handshakeTimeout:1e4}),u=null,h=!1,p=!1,f=0,m=[],_=0,w=0,g=null,y=a(()=>{p&&(process.stdin.setRawMode(!1),p=!1),process.stdin.pause(),process.stdin.removeListener("data",$),process.stdout.removeListener("resize",q),process.removeListener("exit",y)},"restoreTty"),E=a(V=>{if(!h){h=!0,y(),g&&clearTimeout(g);try{d.close()}catch{}c(V)}},"settle"),S=a(V=>{d.readyState===ut.default.OPEN&&d.send(JSON.stringify(V))},"sendFrame"),k=a(()=>{g||(g=setTimeout(()=>{g=null,S({type:"shell_ack",session_id:u,ack_seq:w})},20))},"scheduleOutputAck"),$=a(V=>{let j=V.indexOf(ZP),C=j>=0?V.subarray(0,j):V;for(let ee=0;ee<C.length;ee+=Xp){let lt=C.subarray(ee,ee+Xp);f+=1,m.push({seq:f,bytes:lt.length}),_+=lt.length,S({type:"shell_input",session_id:u,seq:f,data:lt.toString("base64")})}_>=Kp&&process.stdin.pause(),j>=0&&(S({type:"shell_close",session_id:u,reason:"detach"}),process.stderr.write(`\r
|
|
434
|
+
detached \u2014 the tmux session keeps running\r
|
|
435
|
+
`),E({detached:!0}))},"onStdin"),q=a(()=>{S({type:"shell_resize",session_id:u,cols:process.stdout.columns,rows:process.stdout.rows})},"onResize");d.on("open",()=>{S({type:"shell_open",node:r,tmux_session:n,cols:process.stdout.columns||80,rows:process.stdout.rows||24,create:i,...s?{command:s}:{},...o?{cwd_alias:o}:{}})}),d.on("message",(V,j)=>{if(j)return;let C;try{C=JSON.parse(V.toString("utf8"))}catch{return}if(C.type==="shell_open_ok"){u=C.session_id,process.stderr.write(`attached to ${r}:${n}${C.created?" (new)":""} \u2014 detach: Ctrl-]\r
|
|
436
|
+
`),process.stdin.setRawMode(!0),p=!0,process.stdin.resume(),process.stdin.on("data",$),process.stdout.on("resize",q),process.on("exit",y);return}if(C.type==="shell_output"){w=Math.max(w,Number(C.seq)||0),process.stdout.write(Buffer.from(String(C.data||""),"base64"))?k():process.stdout.once("drain",k);return}if(C.type==="shell_ack"){let ee=Number(C.ack_seq)||0;for(;m.length&&m[0].seq<=ee;)_-=m.shift().bytes;_<Kp/2&&p&&process.stdin.resume();return}if(C.type==="shell_closed"){E({detached:!1,clean:C.reason==="session_ended"||C.reason==="controller_closed",retryable:!!C.error?.retryable,message:C.error?.message||C.reason});return}C.type==="shell_error"&&E({detached:!1,clean:!1,retryable:!!C.error?.retryable,message:`${C.error?.code}: ${C.error?.message}${C.error?.next_action?` \u2014 ${C.error.next_action}`:""}`})}),d.on("close",()=>E({detached:!1,clean:!1,retryable:!0,message:"hub connection closed"})),d.on("error",V=>E({detached:!1,clean:!1,retryable:!0,message:V.message}))})}function tD(t){return t===!0||t==="true"||t==="1"||t==="yes"}var ZP,Iv=v(()=>{ia();Zp();ZP=29;a(QP,"shellCommand");a(eD,"attach");a(tD,"booleanFlag")});import{constants as Nv,openSync as rD,closeSync as nD,fstatSync as iD,readFileSync as sD,lstatSync as oD,existsSync as aD,mkdirSync as cD}from"node:fs";import{dirname as ln,resolve as lD}from"node:path";function ce(t,{uid:e=0}={}){t=lD(t),t!==ln(t)&&ce(ln(t),{uid:e});let r=oD(t);if(!r.isDirectory()||r.uid!==e||r.mode&18)throw new Error(`System updater paths require administrator-owned, non-writable directory parents: ${t}`)}function Av(t){let e;try{e=new URL(t?.server_url)}catch{throw new Error("Invalid system updater hub URL")}let r=t?.platform||"darwin",n=r==="linux"?t.publisher==="interscale":r==="darwin"&&/^[A-Z0-9]{10}$/.test(t.publisher||"");if(t?.schema!=="interscale.system-update-policy/v1"||e.protocol!=="https:"||e.username||e.password||e.search||e.hash||typeof t.node_id!="string"||!t.node_id||t.node_id.length>200||typeof t.agent_token!="string"||Buffer.from(t.agent_token,"base64url").length!==gs||!n||!Number.isInteger(t.config_version)||t.config_version<1||t.config_version>1e3||typeof t.automatic_updates!="boolean")throw new Error("Invalid administrator-owned update policy");return{schema:t.schema,server_url:e.toString(),node_id:t.node_id,agent_token:t.agent_token,...t.platform?{platform:r}:{},publisher:t.publisher,config_version:t.config_version,automatic_updates:t.automatic_updates,release_public_key:nt(t.release_public_key).pem}}function Lv(t){ce(ln(t));let e=rD(t,Nv.O_RDONLY|(Nv.O_NOFOLLOW||0));try{let r=iD(e);if(!r.isFile()||r.uid!==0||r.mode&63||r.size>32*1024)throw new Error("System updater policy must be a private administrator-owned file");return Av(JSON.parse(sD(e,"utf8")))}finally{nD(e)}}function Cv(t,e){if(process.getuid?.()!==0)throw new Error("System update policy changes require administrator authorization");aD(ln(t))||(ce(ln(ln(t))),cD(ln(t),{mode:448})),ce(ln(t)),se(t,Av(e))}var Qp=v(()=>{Xn();me();Re();a(ce,"assertAdministratorDirectory");a(Av,"validateSystemUpdatePolicy");a(Lv,"readSystemUpdatePolicy");a(Cv,"saveSystemUpdatePolicy")});var W3,Pv=v(()=>{Hi();Re();Wn();W3=60*6e4});import{createHash as dD}from"node:crypto";import{createReadStream as uD}from"node:fs";import{lstat as hD,readdir as pD,readlink as fD}from"node:fs/promises";import{dirname as mD,isAbsolute as Dv,join as _D,relative as $v,resolve as Uv,sep as jv}from"node:path";async function as(t){let e=Uv(t),r=dD("sha256"),n=a(s=>{let o=Buffer.from(String(s));r.update(`${o.length}:`),r.update(o)},"field");async function i(s){let o=await hD(s),c=$v(e,s).split(jv).join("/");if(n(c),o.isSymbolicLink()){let l=await fD(s),d=Uv(mD(s),l),u=$v(e,d);if(Dv(l)||u===".."||u.startsWith(`..${jv}`)||Dv(u))throw new Error("Code symlink escapes its component");n("link"),n(l)}else if(o.isDirectory()){n("directory");for(let l of(await pD(s)).sort())await i(_D(s,l))}else if(o.isFile()){n("file"),n(o.mode&73),n(o.size);for await(let l of uD(s))r.update(l)}else throw new Error("Code component contains a special file")}return a(i,"walk"),await i(e),r.digest("hex")}var ef=v(()=>{a(as,"codeTreeDigest")});import{existsSync as Mv,readFileSync as gD,statSync as wD}from"node:fs";import{isAbsolute as Bv,join as yD,relative as bD,resolve as tf,sep as vD}from"node:path";function rf(t,e=null,{requiredBranding:r=null,requiredFeatures:n=[]}={}){if(!t||!Bv(t))return null;let i=yD(t,"interscale-runtime.json");if(!Mv(i))return null;try{let s=JSON.parse(gD(i,"utf8"));if(s?.schema!=="interscale.desktop-runtime-receipt/v1"||typeof s.executable!="string"||e&&s.component!==e||r&&s.branding!==r||n.some(c=>!Array.isArray(s.features)||!s.features.includes(c)))return null;let o=tf(t,s.executable);return!ED(t,o)||!Mv(o)||!wD(o).isFile()?null:o}catch{return null}}function ED(t,e){let r=bD(tf(t),tf(e));return r===""||!r.startsWith(`..${vD}`)&&r!==".."&&!Bv(r)}var Fv=v(()=>{a(rf,"bundledDesktopExecutable");a(ED,"inside")});import{readFile as qv,open as SD,lstat as nf,readdir as TD,realpath as zv}from"node:fs/promises";import{existsSync as Wv}from"node:fs";import{join as at,relative as Hv,isAbsolute as kD}from"node:path";async function Gv(t,{version:e,arch:r=process.arch,requireDesktop:n=!1}={}){await xD(t);let i=JSON.parse(await qv(at(t,"app","package.json"),"utf8"));if(i.name!=="@interscale/cli"||!/^\d+\.\d+\.\d+$/.test(i.version||"")||e&&i.version!==e)throw ct("Runtime version does not match the release");for(let c of["bin/interscale.mjs","bin/interscale-agent.mjs","bin/interscale-graphical-worker.mjs","bin/interscale-system-updater.mjs","linux/enable-machine.mjs"])if(!(await nf(at(t,"app",c))).isFile())throw ct("Runtime component is missing or is a symlink");await Co(at(t,"node","bin","node"),r);let s=rf(at(t,"app","desktop-runtime","host"),"host");if(!s)throw ct("The bundled video host is missing");await Co(s,r);let o=Wv(at(t,"desktop"));if(n&&!o)throw ct("An update cannot remove the installed desktop application");if(o){let c=JSON.parse(await qv(at(t,"desktop","interscale-desktop.json"),"utf8"));if(c.schema!=="interscale.linux-desktop/v1"||c.version!==i.version||c.arch!==r)throw ct("Desktop component does not match the machine runtime");if(await Co(at(t,"desktop","interscale"),r),Wv(at(t,"desktop","chrome-sandbox"))&&await Co(at(t,"desktop","chrome-sandbox"),r),!(await nf(at(t,"desktop","resources","app.asar"))).isFile())throw ct("Desktop application code is missing");let l=rf(at(t,"desktop","resources","desktop-runtime","controller"),"controller",{requiredBranding:"integrated_headless_cli",requiredFeatures:["dynamic_proxy_ports.v1"]});if(!l)throw ct("Integrated streaming controller is missing");await Co(l,r)}return{version:i.version,publisher:"interscale",arch:r,desktop:o,sha256:await as(t)}}async function xD(t){let e=await zv(t),r=process.getuid?.();async function n(i){let s=await nf(i),o=Hv(t,i);if(r!==void 0&&s.uid!==r)throw ct("Runtime code belongs to another account");if(s.isSymbolicLink()){let l=Hv(e,await zv(i));if(l===".."||l.startsWith("../")||kD(l))throw ct("Runtime code link escapes its component");return}let c=o==="desktop/chrome-sandbox"&&s.isFile()&&(s.mode&4095)===2541;if(s.mode&3602&&!c)throw ct("Runtime code permissions are not protected");if(s.isDirectory())for(let l of await TD(i))await n(at(i,l));else if(!s.isFile())throw ct("Runtime contains a special file")}a(n,"walk"),await n(t)}async function Co(t,e){let r=await SD(t,"r");try{let n=await r.stat(),i=Buffer.alloc(20),s=await r.read(i,0,i.length,0);if(!n.isFile()||!(n.mode&73)||s.bytesRead!==20||i.subarray(0,4).toString("hex")!=="7f454c46"||i[4]!==2||i[5]!==1||i.readUInt16LE(18)!=={x64:62,arm64:183}[e])throw ct("Executable architecture does not match its Linux release")}finally{await r.close()}}function ct(t){return Object.assign(new Error(t),{code:"linux_package_invalid"})}var kl,$r,cs,sf=v(()=>{Pv();ef();Fv();kl="/opt/interscale",$r="/var/lib/interscale-system-updater",cs="/opt/interscale-updater";a(Gv,"inspectLinuxRuntime");a(xD,"protectedCodeTree");a(Co,"elf");a(ct,"invalid")});import{cp as xl,mkdir as Rl,readlink as RD,readdir as Kv,rename as OD,rm as of,symlink as ID,writeFile as ND,readFile as Jv,chmod as af}from"node:fs/promises";import{existsSync as Vv,realpathSync as AD}from"node:fs";import{join as H,dirname as Yv}from"node:path";import{randomUUID as Xv}from"node:crypto";async function Zv(t){await af(t,493);for(let e of await Kv(t,{withFileTypes:!0}))e.isDirectory()&&await Zv(H(t,e.name))}function Qv(t){return`#!/bin/sh
|
|
437
|
+
# Administrator-owned launcher; no user shell configuration is evaluated.
|
|
438
|
+
unset NODE_OPTIONS ELECTRON_RUN_AS_NODE NODE_PATH DYLD_LIBRARY_PATH DYLD_INSERT_LIBRARIES LD_LIBRARY_PATH LD_PRELOAD
|
|
439
|
+
PATH=/usr/bin:/bin:/usr/sbin:/sbin
|
|
440
|
+
export PATH
|
|
441
|
+
cd /
|
|
442
|
+
root=${a(r=>`'${String(r).replaceAll("'","'\\''")}'`,"q")(t)}
|
|
443
|
+
stopping=
|
|
444
|
+
child=
|
|
445
|
+
trap 'stopping=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT HUP
|
|
446
|
+
for slot in current previous; do
|
|
447
|
+
runtime="$root/$slot/code"
|
|
448
|
+
if [ -x "$runtime/node/bin/node" ]; then
|
|
449
|
+
"$runtime/node/bin/node" "$runtime/app/bin/interscale-system-updater.mjs" "$runtime" "$slot" &
|
|
450
|
+
child=$!
|
|
451
|
+
wait "$child"; status=$?
|
|
452
|
+
# A trapped signal interrupts wait; keep waiting for the updater itself.
|
|
453
|
+
while kill -0 "$child" 2>/dev/null; do wait "$child"; status=$?; done
|
|
454
|
+
# Above 128 the updater was killed, usually by itself after a stuck check:
|
|
455
|
+
# restart this slot. Only an updater that fails on its own falls back.
|
|
456
|
+
if [ -n "$stopping" ] || [ "$status" -eq 0 ] || [ "$status" -gt 128 ]; then exit 0; fi
|
|
457
|
+
fi
|
|
458
|
+
[ -n "$stopping" ] && exit 0
|
|
459
|
+
done
|
|
460
|
+
exit 1
|
|
461
|
+
`}var Ol,eE=v(()=>{ef();Ol=class{static{a(this,"UpdaterBootstrap")}constructor(e,{validate:r=a(async()=>{},"validate"),runningRoot:n=null}={}){this.root=e,this.validate=r,this.runningRoot=n}async current(){try{return await this.slot("current")}catch(e){if(e.code==="ENOENT")return null;throw e}}async slot(e){let r=await RD(H(this.root,e));if(!/^slots\/[a-f0-9-]{36}$/.test(r))throw new Error("Invalid updater bootstrap pointer");let n=H(this.root,r),i=JSON.parse(await Jv(H(n,"bootstrap.json"),"utf8"));if(i.schema!=="interscale.updater-bootstrap/v1"||!/^\d+\.\d+\.\d+$/.test(i.version||""))throw new Error("Invalid updater bootstrap receipt");return{path:n,target:r,...i}}async publish(e,r){await Rl(H(this.root,"slots"),{recursive:!0,mode:493}),await af(this.root,493),await af(H(this.root,"slots"),493);let n=await this.current();if(n?.version===r){if(await as(H(n.path,"code"))!==n.sha256)throw new Error("Active updater bootstrap has changed");return n}let i=Xv(),s=H(this.root,"slots",i),o=H(s,"code");await Rl(H(o,"node","bin"),{recursive:!0,mode:493}),await Rl(H(o,"app"),{recursive:!0,mode:493});try{await xl(H(e,"node","bin","node"),H(o,"node","bin","node"));for(let l of["agent","bin","cli","shared","macos","linux","windows"])await xl(H(e,"app",l),H(o,"app",l),{recursive:!0,verbatimSymlinks:!0});await xl(H(e,"app","package.json"),H(o,"app","package.json"));for(let l of["ws","tar","@isaacs/fs-minipass","chownr","minipass","minizlib","yallist"])Vv(H(e,"app","node_modules",l))&&(await Rl(Yv(H(o,"app","node_modules",l)),{recursive:!0,mode:493}),await xl(H(e,"app","node_modules",l),H(o,"app","node_modules",l),{recursive:!0}));await Zv(s),await this.validate(o);let c={schema:"interscale.updater-bootstrap/v1",version:r,sha256:await as(o)};return await ND(H(s,"bootstrap.json"),JSON.stringify(c)+`
|
|
462
|
+
`,{flag:"wx",mode:420}),n&&await this.point("previous",n.target),await this.point("current",`slots/${i}`),await this.cleanup(),{...c,path:s,target:`slots/${i}`}}catch(c){throw(await this.current().catch(()=>null))?.path!==s&&await of(s,{recursive:!0,force:!0}),c}}async point(e,r){let n=H(this.root,`.${e}-${Xv()}`);try{await ID(r,n),await OD(n,H(this.root,e))}finally{await of(n,{force:!0})}}async restorePrevious(){let e=await this.slot("previous"),r=await this.current();if(await as(H(e.path,"code"))!==e.sha256)throw new Error("Previous updater bootstrap is corrupt");return await this.point("current",e.target),r&&r.target!==e.target&&await this.point("previous",r.target),e}async cleanup(){let e=new Set;for(let r of["current","previous"])try{e.add((await this.slot(r)).path)}catch(n){if(n.code!=="ENOENT")throw n}this.runningRoot&&Vv(this.runningRoot)&&e.add(Yv(AD(this.runningRoot)));for(let r of await Kv(H(this.root,"slots"),{withFileTypes:!0})){let n=H(this.root,"slots",r.name);r.isDirectory()&&/^[a-f0-9-]{36}$/.test(r.name)&&!e.has(n)&&JSON.parse(await Jv(H(n,"bootstrap.json"),"utf8").catch(()=>"null"))?.schema==="interscale.updater-bootstrap/v1"&&await of(n,{recursive:!0})}}};a(Zv,"readableCode");a(Qv,"bootstrapLauncher")});import{spawn as LD}from"node:child_process";function Po(t,e,{allowFailure:r=!1,timeoutMs:n=12e4}={}){let i=LD(t,e,{stdio:["ignore","pipe","ignore"],env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:"/root"}});return new Promise((s,o)=>{let c="",l=!1,d=setTimeout(()=>{l=!0,i.kill("SIGKILL")},n);i.stdout.on("data",u=>{c+=u,c.length>4*1024*1024&&(l=!0,i.kill("SIGKILL"))}),i.once("error",u=>{clearTimeout(d),o(u)}),i.once("exit",u=>{clearTimeout(d),!l&&(u===0||r)?s({status:u,stdout:c}):o(Object.assign(new Error("Linux package service command failed"),{code:"linux_service_failed"}))})})}var tE=v(()=>{a(Po,"runLinuxCommand")});var oE={};K(oE,{SYSTEM_UPDATER_POLICY:()=>Do,SYSTEM_UPDATER_UNIT:()=>nE,installLinuxSystemUpdater:()=>jD,linuxSystemBootstrap:()=>sE,linuxSystemUpdaterUnit:()=>iE});import{join as $o}from"node:path";import{mkdir as cf,readFile as CD,writeFile as PD,rename as DD,rm as $D}from"node:fs/promises";import{existsSync as lf}from"node:fs";import{randomUUID as UD}from"node:crypto";function iE(t){return`[Unit]
|
|
463
|
+
Description=InterScale independent system updater
|
|
464
|
+
After=network-online.target
|
|
465
|
+
Wants=network-online.target
|
|
466
|
+
[Service]
|
|
467
|
+
Type=simple
|
|
468
|
+
ExecStart=/bin/sh ${Gt(t)}
|
|
469
|
+
Restart=always
|
|
470
|
+
RestartSec=30
|
|
471
|
+
UMask=0077
|
|
472
|
+
NoNewPrivileges=true
|
|
473
|
+
PrivateTmp=true
|
|
474
|
+
ProtectSystem=full
|
|
475
|
+
ReadWritePaths=/etc/interscale /etc/systemd/system /usr/share/applications
|
|
476
|
+
[Install]
|
|
477
|
+
WantedBy=multi-user.target
|
|
478
|
+
`}function sE({runningRoot:t,root:e=cs}={}){return new Ol(e,{runningRoot:t,validate:a(async r=>{await Po($o(r,"node","bin","node"),[$o(r,"app","bin","interscale-system-updater.mjs"),"--check-bootstrap"])},"validate")})}async function jD(t,{runtime:e=kl}={}){if(process.platform!=="linux"||process.getuid()!==0)throw new Error("System updater registration requires Linux administrator authorization");ce(e);let r=JSON.parse(await CD(t.configPath||t.config_path,"utf8"));if(!r.release_public_key&&!lf(Do))return{installed:!1,reason:"release_key_required"};ce("/var/lib"),await cf($r,{mode:448,recursive:!0}),ce($r);let n;if(lf(Do)){if(n=Lv(Do),n.platform!=="linux"||n.node_id!==r.node_id||n.server_url!==new URL(r.server_url).toString())throw new Error("Protected update identity differs from machine configuration")}else n={schema:"interscale.system-update-policy/v1",platform:"linux",publisher:"interscale",node_id:r.node_id,server_url:r.server_url,agent_token:Ze(Me(t.root),r.node_id),release_public_key:r.release_public_key,config_version:r.version,automatic_updates:r.automatic_updates!==!1},Cv(Do,n);let i=await Gv(e),s=$o($r,"installed-runtime.json");lf(s)||se(s,i),ce("/opt"),await cf(cs,{recursive:!0,mode:493}),ce(cs);let o=sE();await o.current()||await o.publish(e,i.version);let c=$o(cs,"launch.sh");await rE(c,Qv(cs),493),ce("/usr/share"),await cf("/usr/share/applications",{recursive:!0,mode:493});for(let l of["/etc/interscale","/etc/systemd/system","/usr/share/applications"])ce(l);return await rE(nE,iE(c),420),await Po("systemctl",["daemon-reload"]),await Po("systemctl",["enable","--now","interscale-system-updater.service"]),await Po("runuser",["-u",t.owner.name,"--","/usr/bin/env",`XDG_RUNTIME_DIR=/run/user/${t.owner.uid}`,`DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${t.owner.uid}/bus`,"systemctl","--user","disable","--now","interscale-updater.service"],{allowFailure:!0}),{installed:!0,scope:"boot"}}async function rE(t,e,r){let n=`${t}.${UD()}.tmp`;try{await PD(n,e,{flag:"wx",mode:r}),await DD(n,t)}finally{await $D(n,{force:!0})}}var Do,nE,aE=v(()=>{Qp();bi();eE();Re();Cc();sf();tE();Do=$o($r,"policy.json"),nE="/etc/systemd/system/interscale-system-updater.service";a(iE,"linuxSystemUpdaterUnit");a(sE,"linuxSystemBootstrap");a(jD,"installLinuxSystemUpdater");a(rE,"atomicText")});var mE={};K(mE,{LINUX_MACHINE_RUNTIME:()=>Il,completeLinuxMachineSetup:()=>pE,enableLinuxMachineFromArguments:()=>VD,inspectLinuxMachineSetup:()=>hE,linuxMachineAuthorizationArgs:()=>uE,withLinuxMachineMaintenance:()=>fE});import{constants as cE,closeSync as MD,fstatSync as BD,lstatSync as df,mkdirSync as lE,openSync as FD,readFileSync as qD}from"node:fs";import{dirname as zD,isAbsolute as WD,join as ls,resolve as dE}from"node:path";import{setTimeout as HD}from"node:timers/promises";import{randomUUID as GD}from"node:crypto";function uE({owner:t,root:e,config:r=ls(e,"agent.json")}){if(!/^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/.test(t||"")||t==="root")throw new Error("Select a non-root local account");for(let n of[e,r])if(typeof n!="string"||!WD(n)||/[\0\r\n]/.test(n))throw new Error("Machine data paths must be absolute and contain no control characters");return["--disable-internal-agent",`${Il}/node/bin/node`,`${Il}/app/linux/enable-machine.mjs`,t,dE(e),dE(r)]}function JD(t,e){let r=FD(t,cE.O_RDONLY|cE.O_NOFOLLOW);try{let n=BD(r);if(!n.isFile()||n.uid!==e||n.mode&63||n.size>1024*1024)throw new Error("Activate InterScale under its original local account first");return JSON.parse(qD(r,"utf8"))}finally{MD(r)}}function hE({ownerName:t,root:e,configPath:r,invokerUid:n,runtime:i=Il}){let s=Uc(t,{platform:"linux"});if(n!==void 0&&(!/^\d+$/.test(String(n))||Number(n)!==s.uid))throw new Error("Only the original account can complete its machine activation");uE({owner:s.name,root:e,config:r}),ce(i);for(let u of[ls(i,"node","bin","node"),ls(i,"app","linux","enable-machine.mjs"),ls(i,"app","bin","interscale-agent.mjs")]){ce(zD(u));let h=df(u);if(!h.isFile()||h.uid!==0||h.mode&18)throw new Error("Install the administrator-owned system package before enabling startup")}let o=df(e);if(!o.isDirectory()||o.uid!==s.uid||o.mode&63)throw new Error("Machine data must remain private to its service account");let c=JD(r,s.uid),l=Me(e);if(df(l).uid!==s.uid)throw new Error("Machine credential belongs to a different account");if(Ze(l,c.node_id),c.graphical_worker!==!0)throw new Error("Prepare the graphical worker separately before enabling boot");let d=Ir("linux");if(d&&(d.owner.uid!==s.uid||d.data_root!==e||d.config_path!==r))throw new Error("Preserve the existing machine identity and data paths when repairing its installation");return{owner:s,root:e,configPath:r,runtime:i,nodeId:c.node_id,serverUrl:c.server_url}}async function pE(t,{install:e=fo,status:r=a(()=>tn({platform:"linux"}),"status"),commandLine:n=Ge,health:i=a(()=>ne(t.serverUrl,"/v1/agent-updates/health",{token:Ze(Me(t.root),t.nodeId),signal:AbortSignal.timeout(3e3)}),"health"),timeoutMs:s=15e3,now:o=Date.now,wait:c=HD}={}){e({owner:t.owner,runtimeRoot:t.runtime,root:t.root,config:t.configPath,platform:"linux"});let l=o()+s;for(;;){let d=r(),u=Number(String(d?.detail||"").match(/(?:^|\n)MainPID=(\d+)/)?.[1]);if(d?.loaded&&u&&n(u)?.includes(ls(t.runtime,"app","bin","interscale-agent.mjs"))){let h=await i().catch(()=>null);if(h?.node?.id===t.nodeId&&h.node.status==="online"&&h.node.agent_version===we&&Number.isFinite(h.node.last_seen)&&h.server_time>=h.node.last_seen&&h.server_time-h.node.last_seen<=3e4)return{installed:!0,scope:"boot",node_id:t.nodeId,user:t.owner.name}}if(o()>=l)throw Object.assign(new Error("Activation is saved, but the boot service has not started. Retry setup after checking the agent log."),{code:"machine_start_failed"});await c(100)}}async function VD(t,e=process.env){if(process.platform!=="linux"||process.getuid()!==0)throw new Error("Machine setup requires Linux administrator authorization");if(t.length!==3)throw new Error("Usage: enable-machine.mjs <owner> <data-root> <config-path>");let[r,n,i]=t,s=hE({ownerName:r,root:n,configPath:i,invokerUid:e.PKEXEC_UID??e.SUDO_UID});ce("/etc"),lE("/etc/interscale",{recursive:!0,mode:493}),ce("/etc/interscale"),ce("/var/lib"),lE($r,{recursive:!0,mode:448}),ce($r);let o=ge(ls($r,"system-updater.lock"));try{return await fE(s,async()=>{let c=await pE(s),{installLinuxSystemUpdater:l}=await Promise.resolve().then(()=>(aE(),oE));return{...c,updater:await l(s)}})}finally{o()}}async function fE(t,e,{request:r=a((i,s)=>ne(t.serverUrl,`/v1/agent-updates/${i}`,{token:Ze(Me(t.root),t.nodeId),method:"POST",json:s,timeoutMs:1e4}),"request"),operationId:n=`package_${GD()}`}={}){try{if(!(await r("maintenance",{operation_id:n})).drained)throw Object.assign(new Error("Machine setup is deferred until its jobs, transfers and desktop sessions finish."),{code:"update_node_busy"});return await e()}finally{await r("resume",{operation_id:n}).catch(()=>{})}}var Il,_E=v(()=>{Qp();Xi();Wn();bi();Gn();cr();me();sf();Il=kl;a(uE,"linuxMachineAuthorizationArgs");a(JD,"readOwnedJson");a(hE,"inspectLinuxMachineSetup");a(pE,"completeLinuxMachineSetup");a(VD,"enableLinuxMachineFromArguments");a(fE,"withLinuxMachineMaintenance")});var gE={};K(gE,{fleetStatus:()=>YD,formatFleetStatus:()=>XD});function YD({nodes:t=[]}={},{release:e=null,machines:r=[]}={},n=Date.now()){let i=new Map(r.map(o=>[o.node_id,o])),s=e?.version||null;return{release:s,at:n,machines:t.filter(o=>!o.archived_at).map(o=>{let c=i.get(o.id),l=o.status==="online",d=!!s&&o.agent_version===s;return{name:o.name,online:l,version:o.agent_version||null,current:d,update:d?"current":c?.state||(l?"waiting":"offline"),detail:d?null:c?.detail||null,report_age_s:c?.reported_at?Math.round((n-c.reported_at)/1e3):null,last_seen_age_s:o.last_seen?Math.round((n-o.last_seen)/1e3):null}}).sort((o,c)=>o.name.localeCompare(c.name))}}function XD(t){let e=a(c=>c===null?"-":c<90?`${c}s`:c<5400?`${Math.round(c/60)}m`:`${Math.round(c/3600)}h`,"age"),r=t.machines.map(c=>[c.name,c.online?"online":`offline ${e(c.last_seen_age_s)}`,c.version||"-",c.update,c.current?"":`${c.report_age_s===null?"-":`${e(c.report_age_s)} ago`}${c.detail?` ${String(c.detail).slice(0,60)}`:""}`]),n=["MACHINE","STATE","VERSION","UPDATE","LAST REPORT"],i=n.map((c,l)=>Math.max(c.length,...r.map(d=>String(d[l]).length))),s=a(c=>c.map((l,d)=>String(l).padEnd(i[d])).join(" ").trimEnd(),"line"),o=t.machines.filter(c=>c.online&&!c.current).length;return[`release ${t.release||"none"}: ${t.machines.filter(c=>c.current).length}/${t.machines.length} current${o?`, ${o} online behind`:""}`,s(n),...r.map(s)].join(`
|
|
479
|
+
`)}var wE=v(()=>{a(YD,"fleetStatus");a(XD,"formatFleetStatus")});var EE={};K(EE,{refreshSshSetup:()=>n$,setupDefaults:()=>vE,sshHostEntries:()=>yE,writeSshSetup:()=>bE});import{copyFileSync as KD,existsSync as hf,mkdirSync as ZD,readFileSync as pf,renameSync as QD,writeFileSync as e$}from"node:fs";import{homedir as ff,platform as t$}from"node:os";import{join as Ce}from"node:path";function yE(t,{launcher:e,localNodeId:r=null,platform:n=process.platform,home:i=ff(),quoteLauncher:s=!0}){let o=Ce(i,".ssh","interscale"),c=a(f=>/[\s"]/.test(f)?`"${f.replace(/"/g,'\\"')}"`:f,"quote"),l=[],d=[],u=[];for(let f of t){if(f.id===r)continue;let m=f.capabilities?.ssh;if(!(f.capabilities?.protocol_features||[]).includes("tunnel.ssh.v1")||!m?.host_key){u.push({name:f.name,reason:"update_pending"});continue}let _=`interscale-${f.id}`;d.push(`${_} ${m.host_key}`),l.push([`Host ${f.name} ${f.name}.interscale`,` HostName ${f.name}`,` User ${c(m.user||"owner")}`,` ProxyCommand ${s?c(e):e} ssh-proxy ${f.id}`,` HostKeyAlias ${_}`,` UserKnownHostsFile ${c(Ce(o,"known_hosts"))}`," StrictHostKeyChecking yes"," ServerAliveInterval 15"," WarnWeakCrypto no",...n==="win32"?[]:[" ControlMaster auto",` ControlPath ${c(Ce(o,"cm-%C"))}`," ControlPersist 10m"],""].join(`
|
|
480
|
+
`))}return{config:`# Managed by Interscale (interscale vscode setup). Changes here are overwritten.
|
|
481
|
+
|
|
482
|
+
IgnoreUnknown ${[...new Set(["WarnWeakCrypto",...r$(i)])].join(",")}
|
|
483
|
+
|
|
484
|
+
${l.join(`
|
|
485
|
+
`)}`,knownHosts:`${d.join(`
|
|
486
|
+
`)}
|
|
487
|
+
`,hosts:l.length,skipped:u}}function bE({config:t,knownHosts:e},{home:r=ff()}={}){let n=Ce(r,".ssh"),i=Ce(n,"interscale");ZD(i,{recursive:!0,mode:448}),uf(Ce(i,"config"),t),uf(Ce(i,"known_hosts"),e);let s=Ce(n,"config"),o="Include ~/.ssh/interscale/config",c=hf(s)?pf(s,"utf8"):"";return c.split(/\r?\n/).some(l=>l.trim()===o)||(c&&!hf(`${s}.interscale-backup`)&&KD(s,`${s}.interscale-backup`),uf(s,`${o}
|
|
488
|
+
${c?`
|
|
489
|
+
${c}`:""}`)),{config:Ce(i,"config"),known_hosts:Ce(i,"known_hosts"),main:s}}function r$(t){let e;try{e=pf(Ce(t,".ssh","config"),"utf8")}catch{return[]}return e.split(/\r?\n/).flatMap(r=>{let n=r.match(/^\s*IgnoreUnknown(?:\s*=\s*|\s+)(.+?)\s*$/i);return n?n[1].split(/[\s,]+/).filter(Boolean):[]})}function uf(t,e){let r=`${t}.${process.pid}.tmp`;e$(r,e,{mode:384}),QD(r,t)}function vE({platform:t=t$(),configPath:e=L()}={}){let r=null;try{r=X(e).node_id}catch{}let n=Ce(x(),"bin",t==="win32"?"interscale.cmd":"interscale");return{launcher:t==="win32"?`cmd.exe /d /c "${n}"`:n,localNodeId:r,platform:t,quoteLauncher:t!=="win32"}}function n$(t,{home:e=ff(),...r}={}){let n=Ce(e,".ssh","interscale");if(!hf(Ce(n,"config")))return{changed:!1,reason:"not_set_up"};let i=yE(t,{...vE(r),...r,home:e});if(!i.hosts)return{changed:!1,reason:"no_hosts"};let s=a(o=>{try{return pf(Ce(n,o),"utf8")}catch{return null}},"read");return s("config")===i.config&&s("known_hosts")===i.knownHosts?{changed:!1,hosts:i.hosts}:(bE(i,{home:e}),{changed:!0,hosts:i.hosts})}var SE=v(()=>{So();Z();a(yE,"sshHostEntries");a(bE,"writeSshSetup");a(r$,"userIgnoreUnknown");a(uf,"atomic");a(vE,"setupDefaults");a(n$,"refreshSshSetup")});var AE={};K(AE,{parsePreflight:()=>IE,preflightReport:()=>NE,preflightScript:()=>OE,prepareWorktree:()=>_f,repoPreflight:()=>gf,workerReadiness:()=>c$,worktreePlan:()=>RE});import{createHash as i$}from"node:crypto";async function Nl(t,e,r,{script:n=!1,idempotencyKey:i,signal:s,timeoutMs:o=s$}={}){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",p=>{for(let f of p||[])f.stream==="stderr"?h+=f.text:u+=f.text},{signal:s}),{job_id:c.id,state:d.state,exit_code:d.result?.exit_code,stdout:u,stderr:h}}function xE(t){return/^[A-Za-z]:[\\/]/.test(t)||t.includes("\\")&&!t.includes("/")}function RE(t,e){let r=t.replace(/[\\/]+$/,"")||t,n=`rc-${i$("sha256").update(String(e)).digest("hex").slice(0,8)}`;return{base:r,name:n,branch:`interscale/${n}`,path:`${r}-worktrees${xE(t)?"\\":"/"}${n}`}}function mf(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"})}async function _f(t,e,r,{requestId:n,signal:i}={}){let s=await Nl(t,e,["git","-C",r,"rev-parse","--show-toplevel","--show-prefix"],{signal:i});if(s.state!=="succeeded")throw mf(e,s);let[o="",c=""]=s.stdout.split(/\r?\n/).map(_=>_.trim());if(!o)throw mf(e,s);let l=xE(r),d=a(_=>l?_.replace(/\//g,"\\"):_,"native"),u=RE(d(o),n),h=d(c.replace(/\/+$/,"")),p={path:u.path,cwd:h?`${u.path}${l?"\\":"/"}${h}`:u.path,branch:u.branch,base:u.base},f=await Nl(t,e,["git","-C",u.base,"worktree","add","-b",u.branch,u.path],{signal:i});if(f.state==="succeeded")return{...p,created:!0};let m=await Nl(t,e,["git","-C",u.path,"rev-parse","--abbrev-ref","HEAD"],{signal:i});if(m.state==="succeeded"&&m.stdout.trim()===u.branch)return{...p,created:!1};throw mf(e,f)}function a$(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 ${TE}`:`${e} | head -n ${TE}`],["ignored_count",t?`(${e} | Measure-Object -Line).Lines`:`${e} | wc -l`],["remotes","git remote -v"]]}function OE(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 a$(r))i.push(`echo '@@${s}'`,o);return i.push("echo '@@end'"),`${i.join(`
|
|
490
|
+
`)}
|
|
491
|
+
`}function IE(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}function NE(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(re=>re.startsWith("?? ")).length,l=o.filter(re=>/^(DD|AU|UD|UA|DU|AA|UU) /.test(re)).length,d=o.length-c,u=t.upstream?.[0]?.trim()||null,h=u?Number(t.unpushed?.[0])||0:null,p=Number(t.local_only?.[0])||0,f=(t.local_refs||[]).map(re=>re.trim()).filter(Boolean),m=(t.stash||[]).length,_=a(re=>re.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase(),"same"),w=t.toplevel?.[0]?.trim()||r,g=(t.worktrees||[]).filter(re=>re.startsWith("worktree ")).map(re=>re.slice(9)).filter(re=>_(re)!==_(w)),y=(t.submodules||[]).length,E=(t.lfs||[]).length,S=E>0||(t.lfsattr||[]).length>0,k=t.ignored||[],$=Math.max(k.length,Number(t.ignored_count?.[0])||0),q=[...new Set((t.remotes||[]).map(re=>re.split(/\s+/)[0]))],V=k.filter(re=>kE.test(re)),j=k.filter(re=>!kE.test(re)),C=$-k.length,ee=[];d&&ee.push(`${d} uncommitted change(s)${l?`, ${l} in conflict`:""}`),c&&ee.push(`${c} untracked path(s)`),q.length?p&&ee.push(`${p} commit(s) on no remote${f.length?` (${f.slice(0,5).join("; ")})`:""}`):ee.push("no git remote: the history exists only on this machine"),m&&ee.push(`${m} stash(es): a stash never leaves its machine`),g.length&&ee.push(`${g.length} other worktree(s): ${g.slice(0,5).join(", ")}`),j.length&&ee.push(`${j.length} ignored path(s) a clone will not bring: ${j.slice(0,10).join(", ")}${j.length>10?", ...":""}`),C>0&&ee.push(`${C} more ignored path(s) not listed: check them before retiring this copy`);let lt=[];return y&<.push(`${y} submodule(s): clone with --recurse-submodules`),S&<.push(`Git LFS in use${E?` (${E} files)`:""}: install git-lfs on the destination`),V.length&<.push(`rebuild or regenerate on the destination, for its OS: ${V.slice(0,10).join(", ")}`),{node:e,path:r,top:w,branch:s,upstream:u,unpushed:h,local_only:p,uncommitted:d,conflicted:l,untracked:c,stashes:m,other_worktrees:g,submodules:y,lfs_files:E,remotes:q,ignored_count:$,verdict:ee.length?"copy_needed":"git_sync",carry:ee,notes:lt,next_action:ee.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"}}async function gf(t,e,r,{signal:n}={}){let i=(await t.node(e)).node.platform,s=await Nl(t,e,OE(r,i),{script:!0,signal:n}),o=IE(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{...NE(o,{node:e,path:r}),job_id:s.job_id}}function c$(t){return t.map(e=>{let r=e.capabilities||{},n=r.protocol_features||[],i=(r.tools||[]).map(l=>String(l?.name??l)),s=a(l=>i.some(d=>d===l||d.startsWith(`${l} `)),"has"),o={name:e.name,status:e.status,platform:e.platform,agent_version:e.agent_version,per_job_env:n.includes(Pm),ssh:n.includes(o$),claude:s("Claude Code"),codex:s("Codex"),git:s("Git")},c=[];return e.status!=="online"&&c.push("online"),o.per_job_env||c.push("agent update (per-job env: lineage and parent questions)"),o.ssh||c.push("agent update (SSH tunnel for VS Code)"),o.git||c.push("Git"),!o.claude&&!o.codex&&c.push("Claude Code or Codex"),{...o,ready:!c.length,missing:c}})}var s$,o$,TE,kE,wf=v(()=>{me();s$=12e4,o$="tunnel.ssh.v1",TE=200,kE=/(^|\/)(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;a(Nl,"runToEnd");a(xE,"looksWindows");a(RE,"worktreePlan");a(mf,"worktreeError");a(_f,"prepareWorktree");a(a$,"preflightCommands");a(OE,"preflightScript");a(IE,"parsePreflight");a(NE,"preflightReport");a(gf,"repoPreflight");a(c$,"workerReadiness")});var dn,l$,LE,CE,PE,DE,$E,UE=v(()=>{me();dn={limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string",maxLength:16e3}},l$=[...new Set([...Object.keys(Dm),...ws])],LE={query:{type:"string",maxLength:1e3},node:{type:"string"},library:{type:"string",maxLength:4e3},relative_path:{type:"string",maxLength:4e3},...dn},CE={artifact:{type:"string",minLength:1,maxLength:1e3},...dn},PE={node:{type:"string"},kind:{type:"string",enum:["all","user","job"]},...dn},DE={node:{type:"string"},state:{type:"string",enum:l$},...dn},$E={node:{type:"string"},query:{type:"string",maxLength:200},...dn}});var d$,jE,ME=v(()=>{ye();d$=["hardware","gpus","runtimes","frameworks","tools","network","protocol_features"],jE={section:{type:"string",enum:d$},limit:{type:"integer",minimum:1,maximum:1e3},cursor:{type:"string",maxLength:16e3}}});var BE,FE=v(()=>{BE={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}}});var KE={};K(KE,{runMcpServer:()=>f$});import{randomUUID as Uo}from"node:crypto";import{readFile as qE}from"node:fs/promises";import{arch as u$,platform as h$}from"node:os";import{join as p$,resolve as Al}from"node:path";async function f$(t={}){let e=t.input||process.stdin,r=t.output||process.stdout,n=t.client||null;if(!n)try{let g=(t.loadProfile||be)();n=new Je(g.server_url,g.fleet_key)}catch(g){n=I$(g)}e.setEncoding("utf8");let i={client:n,env:t.env||process.env,mailbox:{},workerServerUrl:a(()=>t.workerServerUrl||X(L()).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(g=>{for(let y of s.values())y.abort.abort(g)},"abortPending"),p=a(g=>{u=!0,h(g),e.destroy?.(g)},"outputError");r.on?.("error",p);let f=a(g=>{g&&!u&&!r.destroyed&&!r.writableEnded&&r.write(`${JSON.stringify(g)}
|
|
492
|
+
`)},"write"),m=a(g=>{for(;c[g]<l[g]&&o[g].length;){let y=o[g].shift();c[g]+=1;let E=(async()=>{let S=y.request.params?._meta?.progressToken;try{y.abort.signal.throwIfAborted(),S!==void 0&&f({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:S,progress:0,total:1}}),f(await zE(y.request,{...i,signal:y.abort.signal})),S!==void 0&&f({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:S,progress:1,total:1}})}catch(k){f(Ll(y.request,k))}finally{s.delete(y.request.id),c[g]-=1,m(g)}})();d.add(E),E.then(()=>d.delete(E),()=>d.delete(E))}},"drain"),_=a(g=>{if(!g||Array.isArray(g)||g.jsonrpc!=="2.0"||typeof g.method!="string"){f({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Invalid JSON-RPC request"}});return}if(g.method==="notifications/cancelled"){let S=s.get(g.params?.requestId);if(!S)return;let k=Object.assign(new Error("Request cancelled; reconcile any submitted operation before retrying"),{code:"request_cancelled"});S.abort.abort(k);let $=o[S.lane].indexOf(S);$!==-1&&(o[S.lane].splice($,1),s.delete(S.request.id),f(Ll(S.request,k)));return}if(g.id===void 0||g.method.startsWith("notifications/"))return;if(!(typeof g.id=="string"||typeof g.id=="number"&&Number.isFinite(g.id))){f({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request ID must be a string or finite number"}});return}if(s.has(g.id)){f({jsonrpc:"2.0",id:g.id,error:{code:-32600,message:"Request ID already active"}});return}if(g.method!=="tools/call"){let S=zE(g,i).then(f).catch(k=>f(Ll(g,k)));d.add(S),S.then(()=>d.delete(S),()=>d.delete(S));return}let y=/_(status|cancel)$/.test(g.params?.name||"")?"control":"work";if(o[y].length>=64){f(Ll(g,new Error("MCP request queue is full; retry later")));return}let E={request:g,lane:y,abort:new AbortController};s.set(g.id,E),o[y].push(E),m(y)},"dispatch"),w="";try{for await(let g of e){for(w+=g;w.includes(`
|
|
493
|
+
`);){let y=w.indexOf(`
|
|
494
|
+
`),E=w.slice(0,y).trim();if(w=w.slice(y+1),!E)continue;let S;if(Buffer.byteLength(E)>1024*1024)throw new Error("MCP request exceeds 1 MiB");try{S=JSON.parse(E)}catch{f({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Invalid JSON"}});continue}_(S)}if(Buffer.byteLength(w)>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",p)}}function Ll(t,e){return t.method!=="tools/call"?{jsonrpc:"2.0",id:t.id??null,error:{code:-32e3,message:e.message}}:jo(t.id,{isError:!0,content:[{type:"text",text:e.message}],structuredContent:{error:{code:e.code||"tool_failed",message:e.message,...oa(e)}}})}async function zE(t,e){if(t.method==="notifications/initialized"||t.method?.startsWith("notifications/"))return null;if(t.method==="initialize")return jo(t.id,{protocolVersion:t.params?.protocolVersion||"2025-06-18",capabilities:{tools:{}},serverInfo:{name:"interscale",version:we},instructions:T$});if(t.method==="ping")return jo(t.id,{});if(t.method==="tools/list")return jo(t.id,{tools:m$().filter(r=>process.env.INTERSCALE_MCP_ALL_TOOLS==="1"||w$.has(r.function.name)||e.env?.INTERSCALE_RC_SESSION_ID&&y$.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 _$(i,r,n,e);return jo(t.id,{content:[{type:"text",text:JSON.stringify(s)}],structuredContent:s,...s?.[YE]?{isError:!0}:{}})}return{jsonrpc:"2.0",id:t.id??null,error:{code:-32601,message:`Method not found: ${t.method}`}}}function m$(){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({...dn,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(DE)),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"},...dn},["node"])),e("interscale_inventory","Read one bounded stored inventory section; follow next_cursor, restarting if inventory_changed",t({node:{type:"string"},...jE},["node","section"])),e("interscale_files_find","Search registered indexes (default); source live needs an explicit path and reports incomplete scans",t({node:{type:"string"},...BE},["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($E)),e("interscale_libraries","List a bounded library page; kind user excludes job outputs. Follow next_cursor with the same filters",t(PE)),e("interscale_artifacts","Find registered files and locations; follow next_cursor using the same filters",t(LE)),e("interscale_artifact","Inspect an artifact and its locations; follow next_locations_cursor with the same artifact",t(CE,["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"},...dy,...ib,...ob,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"]))]}async function _$(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(O$)}}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 g$(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:ac(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 JE(t,i.job.id,r.wait_seconds??Cl,n.signal),o=r.result_directory&&s.state==="succeeded"?await lo(t,s,r.result_directory,{signal:n.signal}):void 0;return{...await VE(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 R$(t,r.job_id,r.since_seq||0,n.signal);let s=i==="wait"?await JE(t,r.job_id,r.wait_seconds??Cl,n.signal):(await t.job(r.job_id,{signal:n.signal})).job;return VE(t,s,n.signal)}if(e==="interscale_rc_start"){let i=r.request_id||`mcp-${Uo()}`,s=r.parent_session_id||n.env?.INTERSCALE_RC_SESSION_ID||await HE(t,n)||void 0,o=r.worktree?await _f(t,r.node,r.cwd,{requestId:i,signal:n.signal}):null,c=await Pl(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-${Uo()}`,s=yf(t,n),o=s===t?GE(n):void 0;return{...await Pl(i,()=>Dl(()=>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||GE(n)||await HE(t,n,{required:!0}),s=Math.min(600,Math.max(0,Number(r.wait_seconds??Cl)||0)),o=i===n.env?.INTERSCALE_RC_SESSION_ID?yf(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 Dl(()=>o.waitMailbox(i,{sinceSeq:l,timeoutMs:Math.max(0,d-Date.now()),signal:n.signal})),l=u.next_since_seq,h=u.messages.filter(f=>f.state!=="handled");while(!h.length&&u.messages.length&&Date.now()<d);c[i]=l;let p=h.map(x$);return{address:i,next_since_seq:l,timed_out:!p.length,has_more:!!u.has_more,messages:p,...p.some(f=>f.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-${Uo()}`,o=yf(t,n),{message:c}=await Pl(s,()=>Dl(()=>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)||b$)),d;try{d=await Dl(()=>o.waitMailbox(i,{sinceSeq:c.seq,replyTo:c.id,timeoutMs:l*1e3,signal:n.signal}))}catch(h){throw Object.assign(bf(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-${Uo()}`,s={...await Pl(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)||Cl));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 gf(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}`)}async function g$(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=Al(r.staging_root||p$(x(),"updates")),o=Al(r.config||L()),c=new os(s,{assertDrained:a(async()=>{n.signal?.throwIfAborted();let m=X(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 qE(Al(r.signed_release),"utf8")),d=X(o),u=r.public_key?await qE(Al(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||we,configVersion:1,platform:h$(),arch:u$(),allowDowngrade:r.allow_downgrade===!0,signal:n.signal},p=new ns(s);await p.stage(l,u,h);let f=await p.preflight(l,u,h);return f.state==="no_change"?f:c.apply(f,{configPath:o,signal:n.signal})}function jo(t,e){return{jsonrpc:"2.0",id:t,result:e}}async function Pl(t,e){try{return await e()}catch(r){if(r?.code!=="outcome_unknown")throw bf(r,t);await new Promise(n=>setTimeout(n,k$));try{return await e()}catch(n){throw bf(n,t)}}}async function HE(t,e,{required:r=!1}={}){if(!e.env?.INTERSCALE_RC_SESSION_ID)try{return e.mailbox.requestId??=`mcp-inbox-${Uo()}`,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 XE(n)||n}}function GE(t){return t.env?.INTERSCALE_RC_SESSION_ID||t.mailbox.address}function yf(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 Je(n,r)}return e.mailbox.workerClient}async function Dl(t){try{return await t()}catch(e){throw XE(e)||e}}function XE(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"})}function x$(t){let e=typeof t.body=="string"&&t.body.length>WE;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,WE):t.body,...e?{body_truncated:!0}:{}}}function bf(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}async function JE(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}async function VE(t,e,r,n){let i=S$.has(e.state),s=await t.logTail(e.id,v$,{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[YE]=!0),l}async function R$(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)>E$){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}}function O$(t){let e=t.capabilities||{},r=a(n=>Number.isFinite(n)?Math.round(n/1e9):null,"gigabytes");return{name:t.name,kind:t.kind||Pr(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}}function I$(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")})}var w$,y$,YE,Cl,b$,WE,v$,E$,S$,T$,k$,ZE=v(()=>{Oo();Ic();wf();UE();Oc();ME();Hh();wo();FE();fa();ol();cc();me();ye();Z();So();Bp();Cp();a(f$,"runMcpServer");a(Ll,"toolError");a(zE,"handleRequest");a(m$,"controllerToolDefinitions");a(_$,"callControllerTool");a(g$,"localUpdateTool");a(jo,"result");w$=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"]),y$=new Set(["interscale_parent_ask"]),YE=Symbol("tool result failed"),Cl=45,b$=300,WE=2e3,v$=8*1024,E$=32*1024,S$=new Set(["succeeded","failed","cancelled","rejected","expired","needs_review"]),T$=`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.
|
|
495
|
+
- See the computers: interscale_nodes (kind, online, OS, GPUs; kind filters machines or servers) or interscale_fleet_summary.
|
|
496
|
+
- 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.
|
|
497
|
+
- 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.
|
|
498
|
+
- Prefer these tools over the interscale command line: a sandboxed shell cannot read its credentials.
|
|
499
|
+
- interscale_run waits up to wait_seconds (default 45). Long jobs keep running: use interscale_job {job_id, action: "wait" | "status" | "logs" | "cancel"}.
|
|
500
|
+
- ok is false when the job failed; read exit_code, error.code, error.message and error.next_action before retrying.
|
|
501
|
+
- An offline computer fails at once with machine_offline; interscale_node_wake can wake one, or pass if_offline: "queue".
|
|
502
|
+
- Files: interscale_files_list / interscale_files_stat on a computer; interscale_transfer_start copies between computers.
|
|
503
|
+
- 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.
|
|
504
|
+
- interscale_nodes lists each computer's tools (Claude Code, Codex, Python, Git, FFmpeg...) and GPUs.`,k$=500;a(Pl,"withRequestRetry");a(HE,"ensureInbox");a(GE,"selfAddress");a(yf,"mailboxClient");a(Dl,"withMailbox");a(XE,"missingMailbox");a(x$,"compactMessage");a(bf,"withRequestId");a(JE,"waitForJob");a(VE,"jobSummary");a(R$,"jobLogs");a(O$,"agentNodeView");a(I$,"notActivated")});var cS={};K(cS,{MCP_RECHECK_MS:()=>L$,approveCodexTools:()=>oS,codexConfigPath:()=>sS,codexWorkerSettings:()=>aS,ensureMcpIntegrations:()=>P$});import{execFile as N$}from"node:child_process";import{existsSync as tS,readFileSync as rS,renameSync as nS,writeFileSync as iS}from"node:fs";import{homedir as A$}from"node:os";import{join as QE}from"node:path";async function P$({launchers:t,run:e=$$,platform:r=process.platform,env:n=process.env,codexConfig:i=sS(n),approveTools:s=!1}={}){let o={},c=a(d=>String(d||"").toLowerCase().replace(/\\/g,"/"),"normalize"),l=c((t.mcp_args.at(-1)||t.mcp_command).replace(/^"|"$/g,""));for(let[d,u]of C$){if((await e(d,["--version"],{platform:r,env:n})).code!==0){o[d]="not_installed";continue}let h=await e(d,["mcp","get","interscale"],{platform:r,env:n}),p=r==="win32"&&/\/s\s+\/c\s+"/i.test(String(h.output||""));if(h.code===0&&c(h.output).includes(l)&&!p){o[d]="present";continue}h.code===0&&await e(d,["mcp","remove",...u,"interscale"],{platform:r,env:n});let f=await e(d,["mcp","add",...u,"interscale","--",t.mcp_command,...t.mcp_args],{platform:r,env:n});o[d]=f.code===0?h.code===0?"updated":"added":`failed: ${String(f.output||"").trim().slice(0,200)}`}return s&&i&&["present","added","updated"].includes(o.codex)&&oS(i)&&(o.codex_approval="set"),i&&["present","added","updated"].includes(o.codex)&&aS(i)&&(o.codex_worker_env="set"),o}function sS(t=process.env){return QE(t.CODEX_HOME||QE(t.HOME||t.USERPROFILE||A$(),".codex"),"config.toml")}function oS(t){if(!tS(t))return!1;let e=rS(t,"utf8"),r=e.split(/\r?\n/),n=r.findIndex(o=>o.trim()==="[mcp_servers.interscale]");if(n<0)return!1;let i=r.findIndex((o,c)=>c>n&&/^\s*\[/.test(o));if(i<0&&(i=r.length),r.slice(n+1,i).some(o=>/^\s*default_tools_approval_mode\s*=/.test(o)))return!1;r.splice(n+1,0,'default_tools_approval_mode = "approve"');let s=`${t}.${process.pid}.tmp`;return iS(s,r.join(e.includes(`\r
|
|
505
|
+
`)?`\r
|
|
506
|
+
`:`
|
|
507
|
+
`)),nS(s,t),!0}function aS(t){if(!tS(t))return!1;let e=rS(t,"utf8"),r=e.split(/\r?\n/),n=r.findIndex(u=>u.trim()==="[mcp_servers.interscale]");if(n<0)return!1;let i=a(()=>{let u=r.findIndex((h,p)=>p>n&&/^\s*\[/.test(h));return u<0?r.length:u},"tableEnd"),s=a(u=>r.findIndex((h,p)=>p>n&&p<i()&&u.test(h)),"find"),o=a(u=>JSON.stringify(u),"quote"),c=!1,l=s(/^\s*env_vars\s*=/);if(l<0)r.splice(n+1,0,`env_vars = [${eS.map(o).join(", ")}]`),l=n+1,c=!0;else{let u=r[l].match(/^(\s*env_vars\s*=\s*)\[(.*)\]\s*$/),h=u?[...u[2].matchAll(/"([^"]*)"/g)].map(f=>f[1]):null,p=h?eS.filter(f=>!h.includes(f)):[];p.length&&(r[l]=`${u[1]}[${[...h,...p].map(o).join(", ")}]`,c=!0)}if(s(/^\s*tool_timeout_sec\s*=/)<0&&(r.splice(l+1,0,`tool_timeout_sec = ${D$}`),c=!0),!c)return!1;let d=`${t}.${process.pid}.tmp`;return iS(d,r.join(e.includes(`\r
|
|
508
|
+
`)?`\r
|
|
509
|
+
`:`
|
|
510
|
+
`)),nS(d,t),!0}function $$(t,e,{platform:r,env:n}){return new Promise(i=>{let s;try{s=Gc(t,e,{platform:r,env:n})}catch(o){i({code:-1,output:o.message});return}N$(s.command,s.args,{env:n,timeout:6e4,windowsHide:!0,maxBuffer:1024*1024,windowsVerbatimArguments:s.windowsVerbatimArguments===!0},(o,c,l)=>{i({code:o?Number.isInteger(o.code)?o.code:-1:0,output:`${c||""}${l||""}`})})})}var L$,C$,eS,D$,lS=v(()=>{Fh();L$=360*6e4,C$=[["claude",["--scope","user"]],["codex",[]]];a(P$,"ensureMcpIntegrations");a(sS,"codexConfigPath");a(oS,"approveCodexTools");eS=["INTERSCALE_RC_SESSION_ID","INTERSCALE_ROOT_TASK_ID","INTERSCALE_RC_TOKEN"],D$=660;a(aS,"codexWorkerSettings");a($$,"runTool")});var TS={};K(TS,{main:()=>W$,recordActiveRuntime:()=>Ef});import{existsSync as Ur,mkdirSync as U$}from"node:fs";import{createHash as j$,randomUUID as Sf}from"node:crypto";import{lstat as Bl,readFile as ci,writeFile as M$}from"node:fs/promises";import{arch as B$,hostname as vf,platform as Ve}from"node:os";import{basename as pS,dirname as Mo,isAbsolute as fS,join as li,relative as F$,resolve as Q}from"node:path";import{fileURLToPath as Ul}from"node:url";async function z$(){let t;try{t=gn()}catch{return}if(!t?.token)return;let{maybePrintUpdateNotice:e}=await Promise.resolve().then(()=>(ev(),Q0));await e({client:new Je(t.server_url,t.token),current:we})}async function mS(){let[t,e,r]=await Promise.all([import("../server/config.mjs"),import("../server/server.mjs"),import("../server/backup.mjs")]);return{...t,...e,...r}}async function W$(t=process.argv.slice(2)){try{let e=await H$(t);return Tf&&process.stderr.isTTY&&await z$(),e}finally{for(let e of jl)e.close();jl.clear()}}async function H$(t){let e=qo(t),[r,n,...i]=e.positional,s=e.options;if(r==="version"||s.version)return console.log(we);if(!r||r==="help"||s.help)return NU();if(Tf&&q$.has(r)){let{installedCliCommand:o}=await Promise.resolve().then(()=>(Sl(),Wp)),c=o(),l=Ur(Ve()==="win32"?c.slice(3,-1):c);throw new Error(`interscale ${r} is not part of the npm package: use the installed Interscale for this ${l?`(${c} ${r} ...)`:"(interscale join installs it on this computer)"}`)}if(r==="hub"||r==="server")return G$(n,i,s);if(r==="agent")return J$(n,i,s);if(r==="account")return eU(n,i,s);if(r==="logout"){let o=gn();return o&&await ne(o.server_url,"/v1/account/logout",{method:"POST",token:o.token,json:{}}),t_(),b({signed_out:!0},s)}if(r==="join"){let o=gn();if(!o)throw new Error("Sign in first: interscale login");let[{joinThisComputer:c},{describeJoin:l},{releaseKeyOverride:d,trustedReleaseKey:u}]=await Promise.all([Promise.resolve().then(()=>(Sl(),Wp)),Promise.resolve().then(()=>(Vp(),Jp)),Promise.resolve().then(()=>(Gp(),dv))]),h=s.name||vf(),p=await c({client:new Je(o.server_url,o.token),releaseKey:u({override:d({})}).pem,name:h,log:a(f=>process.stderr.write(`${f}
|
|
511
|
+
`),"log")});return process.stderr.write(`${l(p,h)}
|
|
512
|
+
`),!p.joined&&p.reason!=="already_enrolled"&&(process.exitCode=2),b(p,s)}if(r==="login"){let{loginCommand:o}=await Promise.resolve().then(()=>(Vp(),Jp));return b(await o(s,{readSecret:Bo,readHiddenLine:xf,installMcp:Ml}),s)}if(r==="nodes")return uS(n,i,s);if(r==="machines"||r==="servers"){if(n)throw new Error(`Usage: interscale ${r} [--json]`);return uS(void 0,[],{...s,kind:r.slice(0,-1)})}if(r==="activity")return mU(s);if(r==="release")return Z$(n,i,s);if(r==="fleet")return K$(n,s);if(r==="update")return Q$(n,i,s);if(r==="benchmark"){if(n!=="api")throw new Error("Usage: interscale benchmark api [--endpoint summary|nodes|health] [--samples 200] [--warmup 10]");let{client:o}=U(),{runApiBenchmark:c}=await Promise.resolve().then(()=>(wv(),gv));return b(await c(o,{endpoint:s.endpoint,samples:s.samples,warmup:s.warmup}),s)}if(r==="inspect"||r==="node")return nU(n,s);if(r==="run")return pU(n,e.passthrough,s);if(r==="jobs")return fU(s);if(r==="job"){if(!n)throw new Error("Usage: interscale job <job-id> [--json]");let{client:o}=U();return b(await o.job(n),s)}if(r==="operation"||r==="operations"){let{client:o}=U();if(!n||n==="list")return b(await o.operations({before:s.before||0,limit:s.limit||100}),s);let c=i[0];if(!c||!["status","events"].includes(n))throw new Error("Usage: interscale operation list | status <id> | events <id> [--since <cursor>]");return b(n==="status"?await o.operation(c):await o.operationEvents(c,{since:s.since||0,limit:s.limit||100}),s)}if(r==="logs")return _U(n,s);if(r==="cancel")return gU(n,s);if(r==="cp")return _S(n,s);if(r==="get")return xU(n,s);if(r==="pull")return gS(n,s);if(r==="context"){if(!s.node)throw new Error("Usage: interscale context --node <machine> [--json]");let{client:o}=U();return b(await o.nodeContext(s.node),s)}if(r==="files"){if(n==="find"){if(!s.node||!i[0])throw new Error("Usage: interscale files find <query> --node <machine> [--source live --path <absolute-root>] [--library <name>] [--limit 100] [--cursor <cursor>] [--json]");let{client:c}=U();return b(await c.fileFind(s.node,{query:i[0],source:s.source,path:s.path,library:s.library,limit:s.limit===void 0?void 0:Number(s.limit),cursor:s.cursor}),s)}if(!["stat","list"].includes(n)||!s.node||!i[0])throw new Error("Usage: interscale files stat|list <absolute-path> --node <machine> [--limit 100] [--cursor <cursor>] [--json]");let{client:o}=U();return b(await(n==="list"?o.fileList(s.node,i[0],{limit:s.limit===void 0?void 0:Number(s.limit),cursor:s.cursor}):o.fileStat(s.node,i[0])),s)}if(r==="revoke")return wU(n,s);if(r==="token"||r==="tokens")return yU(n,i,s);if(r==="desktop")return bU(n,i,s);if(r==="doctor")return RU(n,s);if(r==="capabilities"||r==="find")return iU(r==="find"?n:null,s);if(r==="recipes")return sU(n,s);if(r==="ensure")return oU(n,i,s);if(r==="library"||r==="libraries")return aU(n,i,s);if(r==="workspace"){if(n!=="list")throw new Error("Usage: interscale workspace list [--node <machine>] [--config <agent.json>] [--json]");if(s.node){if(s.config)throw new Error("Remote workspace listing cannot use a local --config path");let{client:c}=U();return b(await c.listWorkspaces(s.node,{limit:s.limit,cursor:s.cursor}),s)}let{listLocalWorkspaces:o}=await Promise.resolve().then(()=>(Tv(),Sv));return b(o(s.config||L()),s)}if(r==="artifact"||r==="artifacts")return cU(n,i,s);if(r==="rc")return dU(n,i,e.passthrough,s);if(r==="workers"||r==="repo")return OU(r,n,i,s);if(r==="term"){let{termCommand:o}=await Promise.resolve().then(()=>(Rv(),xv)),{client:c}=U();return o(c,n,i,e.passthrough,s,b)}if(r==="transfer"||r==="transfers"){if(["plan","start"].includes(n))return TU(n,i,s);let{client:o}=U();try{if(!n||n==="list")return b(await o.transfers({node:s.node,state:s.state,limit:s.limit===void 0?void 0:Number(s.limit)}),s);if(!i[0]||!["status","events","cancel","pause","resume"].includes(n))throw new Error("Usage: interscale transfer plan|start <source> <destination> | list [--node MACHINE] [--state STATE] [--limit 50] | status <transfer-id> [--follow] [--timeout SEC] | events <transfer-id> [--since-seq N] [--limit 100] | pause|resume|cancel <transfer-id> [--json]");if(n==="status"&&A(s.follow,!1)){let c,l=await Gi(o,`transfer ${i[0]}`,d=>o.followTransfer(i[0],u=>{let h=ES(u);h!==c&&(c=h,process.stderr.write(`${h}
|
|
513
|
+
`))},{signal:d,timeoutMs:vS(s.timeout)}));return l.state!=="completed"&&(process.exitCode=2),b({transfer:l},s)}return b(await(n==="status"?o.transfer(i[0]):n==="events"?o.transferEvents(i[0],{sinceSeq:Number(s["since-seq"]||0),limit:Number(s.limit||100)}):n==="resume"?o.resumeTransfer(i[0],{token:ac(i[0])}):n==="pause"?o.pauseTransfer(i[0]):o.cancelTransfer(i[0])),s)}finally{o.close()}}if(r==="shell"){let{shellCommand:o}=await Promise.resolve().then(()=>(Iv(),Ov)),c=be();return o(c.server_url,c.fleet_key,n,s,e.passthrough)}if(r==="mcp")return hU(n,s);if(r==="ssh-proxy"){let{sshProxyCommand:o}=await Promise.resolve().then(()=>(Od(),Rd));process.exit(await o(e.positional,s))}if(r==="vscode")return rU(n,s);throw new Error(`Commande inconnue: ${r}. Lancez: interscale help`)}async function G$(t,e,r){let{createServerConfig:n,loadServerConfig:i,saveServerConfig:s,InterscaleServer:o,createServerBackup:c,restoreServerBackup:l}=await mS();if(t==="password"){if(!r["password-stdin"])throw new Error("Usage: interscale hub password --password-stdin [--config <path> | --print-hash]");if(r["print-hash"])return b({join_password_hash:await Rh(await Bo())},r);let d=r.config||je(),u=i(d);return u.join_password_hash=await Rh(await Bo()),s(u,d),b({configured:!0,restart_required:!0},r)}if(t==="setup")return dS(r);if(t==="start"){let d=be(),u=r.config||je(),h=i(u,{fleetKey:d.fleet_key}),p=new o(h,{configPath:u});await p.listen(),await SS(()=>p.close());return}if(t==="install"){let d=be();if(Ve()!=="linux")throw new Error("Le control plane de production s'installe sur un VPS Linux");Ur(r.config||je())||await dS(r);let u=r.config||je(),h=i(u,{fleetKey:d.fleet_key}),p=A(r.caddy,new URL(h.public_url).protocol==="https:");if(p&&!new Set(["127.0.0.1","::1","localhost"]).has(String(h.listen.host).toLowerCase()))throw new Error("Automatic Caddy mode requires --host 127.0.0.1");p&&!h.trust_proxy&&(h.trust_proxy=!0,s(h,u));let f=await an();b(await f.installServerService({config:h,configPath:u,configureCaddy:p}),r);return}if(t==="status"){let d=be(),u=i(r.config||je(),{fleetKey:d.fleet_key}),h=await ne(u.public_url,"/health");b({config:r.config||je(),health:h},r);return}if(t==="backup"){let d=be(),u=i(r.config||je(),{fleetKey:d.fleet_key});return b(await c(u,e[0]||r.output,{overwrite:A(r.overwrite,!1)}),r)}if(t==="restore"){if(!e[0])throw new Error("Usage: interscale hub restore <backup.sqlite3>");let d=be(),u=i(r.config||je(),{fleetKey:d.fleet_key});return b(await l(u,e[0]),r)}throw new Error("Usage: interscale hub setup|start|install|status|backup|restore")}async function dS(t){let{createServerConfig:e,saveServerConfig:r}=await mS(),n=be(),i=Ke(t["public-url"]||n.server_url),s=new URL(i),o=e({fleetKey:n.fleet_key,publicUrl:i,host:t.host||"127.0.0.1",port:Number(t.port||s.port||8787),dataDir:t["data-dir"],tlsCertFile:t["tls-cert"],tlsKeyFile:t["tls-key"],trustProxy:A(t["trust-proxy"],!1),r2:IU(t)}),c=r(o,t.config||je());b({configured:!0,config_path:c,public_url:o.public_url,listen:o.listen},t)}async function J$(t,e,r){if(t==="install")return tU(r);if(["prepare-boot","repair-services"].includes(t)){if(process.getuid?.()===0)throw new Error("Prepare the machine under its original unprivileged account");let n=X(r.config||L()),i=Me(),s=Ur(i)?Ze(i,n.node_id):vs("agent",n.node_id);if(ca(n.node_id,s),t==="prepare-boot"){let d;return Ve()==="linux"&&(n.graphical_worker=!0,it(n,r.config||L()),d=await po()),b({prepared:!0,node_id:n.node_id,...d?{graphical:d}:{}},r)}Lc()&&(n.graphical_worker=!0,it(n,r.config||L()),await po());let o=await(await an()).installAgentService(),c=Mh({runtimeRoot:Q(Mo(Ul(import.meta.url)),"..")}),l=Hc();return b({installed:!0,service:o,launchers:c,updater:l},r)}if(t==="enable-boot"&&Ve()==="win32"){let{registerWindowsBootTask:n}=await Promise.resolve().then(()=>(Ep(),vp)),i=process.stdin.isTTY?await xf("Windows password for this account (a Microsoft account uses its online password, not the PIN): "):await Bo();if(!i)throw new Error("Windows accounts without a password sign in by themselves after a reboot; no boot task is needed");return b({enabled:!0,...n({password:i})},r)}if((t==="enable-admin-control"||t==="disable-admin-control")&&Ve()==="win32"){let{enableAdminControl:n,disableAdminControl:i}=await Promise.resolve().then(()=>(fp(),Hb));return b(t==="enable-admin-control"?n():i(),r)}if(t==="enable-admin-control"||t==="disable-admin-control")throw new Error("Admin control applies to Windows; macOS and Linux desktop control already reach admin windows");if(t==="enable-boot"){if(!["darwin","linux"].includes(Ve())||process.getuid?.()!==0)throw new Error("Use the platform's elevated installer to enable the boot service");let n=Uc(r.owner||process.env.SUDO_USER),i=r["data-root"]||(Ve()==="darwin"?li(n.home,"Library","Application Support","Interscale"):li(n.home,".local","state","interscale"));if(Ve()==="linux"){let{enableLinuxMachineFromArguments:o}=await Promise.resolve().then(()=>(_E(),mE));return b(await o([n.name,i,r.config||li(i,"agent.json")]),r)}let s=Q(Mo(Ul(import.meta.url)),"..","..");return b(fo({owner:n,runtimeRoot:s,root:i,config:r.config}),r)}if(t==="received-cleanup")return V$(e,r);if(t==="foreground"||t==="start"){let n=X(r.config||L()),{InterscaleAgent:i}=await import("../agent/agent.mjs"),s=new i(n,{configPath:r.config||L()});await s.start(),await SS(()=>s.stop());return}if(t==="status"){let n=await an(),i=Ur(L())?X():null;b({config:i,service:n.agentServiceStatus()},r);return}if(t==="restart"){let n=await an();if(typeof n.restartAgentService!="function")throw new Error("Agent restart is not supported on this platform");b(await n.restartAgentService(),r);return}if(t==="wake-target")return X$(e,r);if(t==="release-key")return Y$(e,r);if(t==="uninstall"){await Iy();let n=await an();zy();let i=await n.uninstallAgentService();if(A(r.purge,!1)&&Ur(L())){let s=X();da("agent",s.node_id)}b(i,r);return}throw new Error("Usage: interscale agent install|foreground|status|restart|uninstall|wake-target|release-key|received-cleanup")}async function V$(t,e){let r=t[0]||"status";if(!["status","preview","run"].includes(r))throw new Error("Usage: interscale agent received-cleanup status|preview|run --confirm [--config agent.json] [--database agent.sqlite3]");if(r==="run"&&!A(e.confirm,!1))throw new Error("received-cleanup run requires --confirm after reviewing the preview");let n=X(e.config||L()),i=new El(e.database||Mm());try{let s=new tl(n,i),o=r==="status"?s.status():r==="preview"?await s.preview():await s.run();return b(o,e)}finally{i.close()}}async function Y$(t,e){let[r,n]=t,i=e.config||L(),s=X(i);if(!r||r==="show"){let o=s.release_public_key?nt(s.release_public_key):null;return b({configured:!!o,key_id:o?.key_id||null},e)}if(r==="pin"){if(!n)throw new Error("Usage: interscale agent release-key pin <ed25519-public.pem> [--config agent.json]");let o=nt(await ci(Q(n),"utf8"));return s.release_public_key=o.pem,it(s,i),b({configured:!0,key_id:o.key_id,config_path:Q(i)},e)}if(r==="remove")return s.release_public_key=null,it(s,i),b({configured:!1,key_id:null,config_path:Q(i)},e);throw new Error("Usage: interscale agent release-key show|pin <ed25519-public.pem>|remove [--config agent.json]")}async function X$(t,e){let[r,n]=t,i=e.config||L(),s=X(i);if(s.wake_targets||={},r==="list")return b({wake_targets:Object.entries(s.wake_targets).sort(([l],[d])=>l.localeCompare(d)).map(([l,d])=>({node_id:l,mac_suffix:d.mac.slice(-5),broadcast_addresses:d.broadcast_addresses,port:d.port}))},e);if(!n||!["add","remove"].includes(r))throw new Error("Usage: interscale agent wake-target list | add <machine> --mac <address> --broadcast <IPv4[,IPv4]> [--port 9] | remove <machine>");let o=Object.hasOwn(s.wake_targets,n)?n:null;if(!o){let{client:l}=U();try{o=(await l.node(n)).node.id}finally{l.close()}}if(o===s.node_id)throw new Error("A Wake-on-LAN relay cannot target itself");if(r==="remove")delete s.wake_targets[o];else{if(typeof e.mac!="string"||typeof e.broadcast!="string")throw new Error("Adding a wake target requires --mac and --broadcast");s.wake_targets[o]={mac:e.mac,broadcast_addresses:e.broadcast.split(",").map(l=>l.trim()).filter(Boolean),port:e.port===void 0?9:Number(e.port)}}it(s,i);let c=s.wake_targets[o];return b({updated:!0,action:r,node_id:o,...c?{mac_suffix:c.mac.slice(-5),broadcast_addresses:c.broadcast_addresses,port:c.port}:{},hot_reload:!0},e)}async function K$(t,e){if(t!=="status")throw new Error("Usage: interscale fleet status [--watch] [--json]");let{client:r}=U(),{fleetStatus:n,formatFleetStatus:i}=await Promise.resolve().then(()=>(wE(),gE));for(;;){let s=n(await r.nodes(),await r.releases());if(!A(e.watch,!1))return e.json?b(s,e):console.log(i(s));if(process.stdout.write(`\x1B[2J\x1B[H${i(s)}
|
|
514
|
+
`),s.machines.every(o=>!o.online||o.current))return;await new Promise(o=>setTimeout(o,1e4))}}async function Z$(t,e,r){if(t==="status"||t==="publish"){let{client:c}=U();if(t==="publish"&&!e[0])throw new Error("Usage: interscale release publish <signed-release.json>");return b(t==="status"?await c.releases():await c.publishRelease(JSON.parse(await ci(Q(e[0]),"utf8"))),r)}if(t!=="sign"||!e[0]||!r["private-key"]||!r.out)throw new Error("Usage: interscale release sign <manifest.json> --private-key <ed25519.pem> --out <signed-release.json> [--force]");let n=Q(r.out);if(Ur(n)&&!A(r.force,!1))throw new Error(`Signed release already exists: ${n} (use --force to replace it)`);let i=JSON.parse(await ci(Q(e[0]),"utf8")),s=await ci(Q(r["private-key"]),"utf8"),o=fb(i,s);return await M$(n,`${JSON.stringify(o,null,2)}
|
|
515
|
+
`,{mode:384}),b({signed:!0,release_id:o.manifest.release_id,version:o.manifest.version,key_id:o.key_id,output:n},r)}async function Q$(t,e,r){let n=Q(r["staging-root"]||li(x(),"updates")),i=r.config||L(),s=new os(n,{assertDrained:a(async()=>{let h=X(i),{client:p}=U();try{let f=await p.activity({node:h.node_id,status:"open",limit:10});if(f.summary.open>0)throw Object.assign(new Error(`Node has ${f.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."})}finally{p.close()}},"assertDrained")});if(t==="status")return b(await s.status(),r);if(Ve()==="darwin"&&["apply","rollback"].includes(t))throw Object.assign(new Error("Macs update through the signed Interscale package and its system updater, which keep fixed paths so macOS permissions survive updates"),{code:"mac_package_required"});if(t==="rollback"){if(!A(r.yes,!1))throw new Error("update rollback requires --yes after reviewing update status");return b(await s.rollback({configPath:i}),r)}if(!["verify","plan","stage","preflight","apply"].includes(t)||!e[0])throw new Error("Usage: interscale update verify|plan|stage|preflight|apply <signed-release.json> | status | rollback --yes [--public-key <ed25519-public.pem>] [--config agent.json] [--current-version X.Y.Z] [--platform darwin|linux|win32] [--arch arm64|x64] [--staging-root PATH] [--previous-runtime-root PATH]");let o=JSON.parse(await ci(Q(e[0]),"utf8")),c;if(r["public-key"])c=await ci(Q(r["public-key"]),"utf8");else{let h=X(r.config||L());if(!h.release_public_key)throw new Error("No release verification key is pinned; run agent release-key pin or pass --public-key");c=h.release_public_key}if(t==="verify"){let h=bo(o,c);return b({verified:!0,key_id:h.key_id,manifest:h.manifest},r)}let l={currentVersion:r["current-version"]||we,configVersion:r["config-version"]===void 0?1:Number(r["config-version"]),platform:r.platform||Ve(),arch:r.arch||B$(),allowDowngrade:A(r["allow-downgrade"],!1)};if(t==="plan")return b(vo(o,c,l),r);let d=new ns(n);if(t==="stage")return b(await d.stage(o,c,l),r);if(t==="preflight")return b(await d.preflight(o,c,l),r);if(!A(r.yes,!1))throw new Error("update apply requires --yes after reviewing update plan and rollback compatibility");await d.stage(o,c,l);let u=await d.preflight(o,c,l);return u.state==="no_change"?b(u,r):b(await s.apply(u,{configPath:i,previousRuntimeRoot:r["previous-runtime-root"]}),r)}async function eU(t,e,r){let n;if(t==="setup"&&r["owner-profile"]){let i=wd(JSON.parse(await ci(Q(r["owner-profile"]),"utf8")));n=new Je(i.server_url,i.fleet_key),jl.add(n)}else({client:n}=U());if(t==="setup"){if(!r.email)throw new Error("Usage: interscale account setup --email <owner-email> [--owner-profile <private-owner-profile>] [--password-stdin]");let i=r["password-stdin"]?await Bo():await xf("Choose your Interscale password (12+ characters): ");return b(await n.request("/v1/account/bootstrap",{method:"POST",json:{email:r.email,password:i}}),r)}if(["invite","reset-password"].includes(t)){if(!r.email)throw new Error("Pass --email <teammate-email>");return b(await n.request(`/v1/team/${t==="invite"?"invitations":"password-reset"}`,{method:"POST",json:{email:r.email}}),r)}if(t==="members")return b(await n.request("/v1/team/members"),r);if(t==="share"||t==="unshare"){if(!e[0]||!r.email)throw new Error("Usage: interscale account share|unshare <machine> --email <teammate-email>");return b(await n.request(`/v1/nodes/${encodeURIComponent(e[0])}/shares`,{method:"POST",json:{email:r.email,remove:t==="unshare"}}),r)}return b(await n.request("/v1/account"),r)}async function tU(t){let e=t.config||L(),r=Ur(e)?X(e):null,n={};try{n=be()}catch(g){if(!r?.node_id)throw g}let i=Ke(t.hub||t.server||r?.server_url||n.server_url);if(r?.node_id&&n.source==="installation"&&n.fleet_key){let g;try{g=await ne(i,"/v1/whoami",{token:n.fleet_key})}catch(y){if(y.status!==401)throw y}if(g?.session.user_id&&(await ne(i,`/v1/nodes/${encodeURIComponent(r.node_id)}`,{token:n.fleet_key})).node.owner_user_id!==g.session.user_id)throw new Error("This computer belongs to another Interscale account. Its enrollment has been kept.")}let s=t.name||r?.node_name||vf(),o=Number(t["data-port"]??r?.data_port??47821),c={};if(!r?.release_public_key&&n.release_public_key&&(c.release_public_key=n.release_public_key),["sunshine-path","sunshine-config","sunshine-managed","sunshine-private-bind-verified","desktop-displays","desktop-encoders"].some(g=>t[g]!==void 0))throw new Error("The desktop runtime is integrated into Interscale and cannot be selected separately");let d=["desktop-permission-state","desktop-consent-mode","desktop-host-port"],u={...r?.desktop_control||{}};if(delete u.executable,delete u.config_path,d.some(g=>t[g]!==void 0)&&(t["desktop-permission-state"]!==void 0&&(u.permission_state=t["desktop-permission-state"]),t["desktop-consent-mode"]!==void 0&&(u.consent_mode=t["desktop-consent-mode"]),t["desktop-host-port"]!==void 0&&(u.host_port=Number(t["desktop-host-port"]))),c.desktop_control=u,!A(t["no-service"],!1)&&Lc()&&(c.graphical_worker=!0),t["data-port"]!==void 0&&(c.data_port=o),t["receive-root"]!==void 0&&(c.receive_root=Q(t["receive-root"])),t["receive-retention-days"]!==void 0&&(c.receive_retention_days=Number(t["receive-retention-days"])),t["receive-cleanup-limit"]!==void 0&&(c.receive_cleanup_max_entries_per_run=Number(t["receive-cleanup-limit"])),t["max-log-mb"]!==void 0&&(c.max_job_log_bytes=Math.floor(Number(t["max-log-mb"])*1024*1024)),rp(r,{serverUrl:i,node:{id:r?.node_id||"pending-enrollment",name:s},overrides:c}),r&&r.server_url===i&&r.node_name===s&&!A(t.replace,!1))try{ca(r.node_id,vs("agent",r.node_id)),Object.keys(c).length&&(Object.assign(r,c),it(r,e));let g={skipped:!0};A(t["no-service"],!1)||(r.graphical_worker&&await po(),g=await(await an()).installAgentService()),A(t["no-service"],!1)||Ef();let y=await Ml(),E=A(t["no-service"],!1)?{skipped:!0}:Hc();b({installed:!0,reused:!0,node:{id:r.node_id,name:r.node_name},config_path:e,service:g,updater:E,mcp:y},t);return}catch(g){if(!/Secret .* not found/.test(g.message))throw g}n.fleet_key||be();let h=await ne(i,"/v1/agents/enroll",{method:"POST",token:n.fleet_key,headers:{"x-interscale-client":`${vf()}-installer`},json:{name:s,platform:Ve(),agent_version:we,capabilities:eb(),addresses:tb(),data_port:o,replace:A(t.replace,!1)}});la("agent",h.node.id,h.token),ca(h.node.id,h.token);let p=rp(r,{serverUrl:i,node:h.node,overrides:c}),f=it(p,e),m={skipped:!0};A(t["no-service"],!1)||(p.graphical_worker&&await po(),m=await(await an()).installAgentService()),A(t["no-service"],!1)||Ef();let _=await Ml(),w=A(t["no-service"],!1)?{skipped:!0}:Hc();b({installed:!0,node:h.node,config_path:f,service:m,updater:w,mcp:_},t)}async function rU(t,e){if(t!=="setup")throw new Error("Usage: interscale vscode setup");let{setupDefaults:r,sshHostEntries:n,writeSshSetup:i}=await Promise.resolve().then(()=>(SE(),EE)),{client:s}=U(),o=[],c;do{let u=await s.nodes({cursor:c,limit:200});o.push(...u.nodes||[]),c=u.next_cursor}while(c);let l=n(o,r({configPath:e.config||L()})),d=i(l);return b({hosts:l.hosts,skipped:l.skipped,...d,next_action:l.hosts?"In VS Code: Remote-SSH: Connect to Host\u2026 and pick a machine, or run: code --remote ssh-remote+<machine> <folder>":"No machine supports tunnels yet; they update automatically"},e)}async function uS(t,e,r){let{client:n}=U();if(t==="archive-candidates")return b(await n.nodeArchiveCandidates({staleDays:r["stale-days"],limit:r.limit}),r);if(t==="archived")return b(await n.archivedNodes({limit:r.limit}),r);if(t==="wake"){let o=e[0];if(!o)throw new Error("Usage: interscale nodes wake <machine> [--request-id <id>] [--timeout-seconds 120] [--wait true|false]");let c=Number(r["timeout-seconds"]??120);if(!Number.isSafeInteger(c)||c<15||c>600)throw new Error("--timeout-seconds must be from 15 through 600");let l=await n.wakeNode(o,{requestId:r["request-id"]||`cli-${Sf()}`,timeoutSeconds:c});if(A(r.wait,!0)&&!["succeeded","failed","cancelled","needs_review"].includes(l.wake.state)){let d;for(;!["succeeded","failed","cancelled","needs_review"].includes(l.wake.state);)l.wake.state!==d&&(process.stderr.write(`wake ${l.wake.target.name}: ${l.wake.state}${l.wake.relay?` via ${l.wake.relay.name}`:" (waiting for relay)"}
|
|
516
|
+
`),d=l.wake.state),await new Promise(u=>setTimeout(u,1e3)),l=await n.wakeStatus(l.wake.operation_id)}return["failed","cancelled","needs_review"].includes(l.wake.state)&&(process.exitCode=2),b(l,r)}if(t==="wake-status"){if(!e[0])throw new Error("Usage: interscale nodes wake-status <operation-id> [--json]");return b(await n.wakeStatus(e[0]),r)}if(t==="archive"){let o=e[0];if(!o||!A(r.confirm,!1)||r.reason===void 0||r["if-last-seen"]===void 0)throw new Error("Usage: interscale nodes archive <machine> --if-last-seen <timestamp|never> --reason <text> --confirm [--stale-days 30]");let c=r["if-last-seen"]==="never"?null:Number(r["if-last-seen"]);if(c!==null&&(!Number.isSafeInteger(c)||c<0))throw new Error("--if-last-seen must be an exact nonnegative millisecond timestamp or never");return b(await n.archiveNode(o,{expectedLastSeen:c,staleDays:r["stale-days"]===void 0?void 0:Number(r["stale-days"]),reason:r.reason,confirm:!0}),r)}if(t)throw new Error("Usage: interscale nodes [--compact] | nodes wake <machine> | nodes wake-status <operation-id> | nodes archive-candidates | nodes archived | nodes archive <machine> --if-last-seen <timestamp|never> --reason <text> --confirm");let i=O0(r.kind),s=A(r.compact,!1)?await n.fleetSummary():await n.nodes({view:"summary",limit:r.limit,cursor:r.cursor,kind:i});if(r.json)return b(s,r);if(s.nodes.length===0)return console.log(i?`No ${i}s.`:"No enrolled computers.");for(let[o,c]of[["machine","Machines"],["server","Servers"]]){let l=s.nodes.filter(d=>Pr(d.platform)===o);l.length&&(console.log(c),console.table(l.map(T0)))}s.next_cursor&&console.error(`More computers: repeat with --cursor ${s.next_cursor}.`)}async function nU(t,e){if(!t)throw new Error("Usage: interscale inspect <machine>");if(t==="self"){if(!Ur(L()))throw new Error("This machine has no installed Interscale agent");t=X().node_name}let{client:r}=U();if(e.section){let i=await r.nodeInventory(t,{section:e.section,limit:e.limit,cursor:e.cursor});if(e.json)return b(i,e);console.log(`${i.section}: ${i.status} (${i.total_entries} entries)`),console.table(i.entries),i.truncated&&console.error("Some oversized inventory fields were omitted."),i.next_cursor&&console.error(`More inventory: repeat with the same --section and --cursor ${i.next_cursor}.`);return}let n=await r.node(t);if(e.json)return b(n,e);console.log(k0(n.node))}async function iU(t,e){let{client:r}=U(),n=await r.capabilities({node:e.node,query:t||e.query,limit:e.limit,cursor:e.cursor});if(e.json)return b(n,e);if(n.capabilities.length===0)return console.log("No matching capabilities.");console.table(n.capabilities.map(i=>({capability:i.id,version:i.version||"",machine:i.node_name,state:i.state}))),n.next_cursor&&console.error(`More capabilities: repeat with --cursor ${n.next_cursor} and the same filters.`)}async function sU(t,e){let{client:r}=U(),n=await r.recipes(t||e.node||null);if(e.json)return b(n,e);console.table(n.recipes.map(i=>({recipe:i.id,version:i.version,machine:i.node_name||"all",state:i.state||"catalogued",requires:(i.requires||[]).join(", ")})))}async function oU(t,e,r){if(!t||typeof r.on!="string")throw new Error("Usage: interscale ensure <capability-or-recipe> --on <machine>");let{client:n}=U(),i=t.includes(".")&&t.split(".")[0]!=="tool"&&t.split(".")[0]!=="framework"&&t.split(".")[0]!=="runtime"&&t.split(".")[0]!=="hardware"?await n.ensureRecipe(t,r.on):await n.ensureCapability(t,r.on,{requestId:r["request-id"]});b(i,r)}async function aU(t,e,r){if(t==="add"){let[s,o]=e;if(!s||!o)throw new Error("Usage: interscale library add <name> <path>");let c=r.config||L(),l=X(c),d=Q(o);if(!(await Bl(d)).isDirectory())throw new Error(`Library root is not a directory: ${d}`);return l.libraries={...l.libraries||{},[s]:d},it(l,c),b({added:!0,name:s,root:d,reload:"pending",config_path:c},r)}if(t==="remove"){let[s]=e;if(!s)throw new Error("Usage: interscale library remove <name>");let o=r.config||L(),c=X(o),l=!!(c.libraries?.[s]||c.file_libraries?.[s]);return c.libraries&&delete c.libraries[s],c.file_libraries&&delete c.file_libraries[s],it(c,o),b({removed:l,name:s,reload:"pending",config_path:o},r)}if(t==="scan"){let s=r.config||L(),o=X(s);return o.library_scan_request=Sf(),it(o,s),b({scan_requested:!0,request_id:o.library_scan_request,reload:"pending"},r)}let{client:n}=U(),i=await n.libraries(r.node||null,{limit:r.limit,cursor:r.cursor,kind:r.kind});if(r.json)return b(i,r);if(i.libraries.length===0)return console.log("No indexed libraries.");console.table(i.libraries.map(s=>({name:s.name,machine:s.node_name,state:s.state,files:s.file_count,bytes:s.total_bytes,scanned:s.last_scanned_at?new Date(s.last_scanned_at).toISOString():""}))),i.next_cursor&&console.error(`More libraries: repeat with --cursor ${i.next_cursor} and the same filters.`)}async function cU(t,e,r){let{client:n}=U();if(t==="register"){let o=e[0];if(!o)throw new Error("Usage: interscale artifact register <path>");return b({artifact:await lU(n,o,r)},r)}if(t==="where"){let o=e[0];if(!o)throw new Error("Usage: interscale artifact where <id-or-name>");let c=await n.artifact(o,{limit:r.limit,cursor:r.cursor});if(r.json)return b(c,r);console.log(`${c.artifact.id} ${c.artifact.original_name} ${c.artifact.size} bytes`),console.table(c.artifact.locations),c.artifact.next_locations_cursor&&console.error(`More locations available. Continue with --cursor ${c.artifact.next_locations_cursor}`);return}if(t==="stage"){let[o]=e;if(!o||typeof r.to!="string")throw new Error("Usage: interscale artifact stage <id-or-name> --to <machine>");return b(await n.stageArtifact(o,r.to),r)}let i=t&&t!=="list"?t:r.query,s=await n.artifacts({query:i,node:r.node,limit:r.limit,cursor:r.cursor,library:r.library,relativePath:r["relative-path"]});if(s.next_cursor&&!r.json&&console.error(`More artifacts available. Continue with --cursor ${s.next_cursor}`),r.json)return b(s,r);if(s.artifacts.length===0)return console.log("No matching artifacts.");console.table(s.artifacts.map(o=>({id:o.id,name:o.original_name,size:o.size,machine:o.node_name,library:o.library_name,path:o.relative_path})))}async function lU(t,e,r){let n=Q(e);if(!(await Bl(n)).isFile())throw new Error("Artifact registration currently accepts regular files");if(!Ur(L()))throw new Error("Registering a local artifact requires the Interscale agent on this machine");let s=X(),o,c;for(let[d,u]of Object.entries(s.libraries||{})){let h=F$(Q(u),n);if(h===""||!h.startsWith("..")&&!fS(h)){o=d,c=h.replace(/\\/g,"/");break}}o||(o=`file-${j$("sha256").update(n).digest("hex").slice(0,24)}`,s.file_libraries={...s.file_libraries||{},[o]:n},c=pS(n)),s.library_scan_request=Sf(),it(s);let l=Date.now()+Number(r["register-timeout"]||1800*1e3);for(;Date.now()<l;){let u=(await t.artifacts({node:s.node_name,library:o,relativePath:c,limit:1})).artifacts.find(h=>h.library_name===o&&h.relative_path===c);if(u)return u;await new Promise(h=>setTimeout(h,1e3))}throw new Error(`Timed out while hashing and publishing ${n}`)}async function dU(t,e,r,n){let{client:i}=U();if(t==="start"){let o=e[0],c=n.provider,l=n.cwd;if(!o||!l)throw new Error("Usage: interscale rc start <machine> --cwd <absolute-path> [--provider claude|codex (default claude)] [--permission-mode full|workspace|read-only]");let d=await i.createRcSession(o,{provider:c,cwd:l,permissionProfile:n["permission-mode"]||n.profile,model:n.model,title:n.title,turnTimeoutSeconds:n.timeout,maxBudgetUsd:n.budget,requestId:n["request-id"]});if(n.json)return b(d,n);console.log(`${d.session.id} ${d.session.state} node=${d.session.node_id} provider=${d.session.provider} profile=${d.session.permission_profile}`),console.error(`cwd=${d.session.cwd}`);return}if(t==="history"||t==="turn"){let[o,c]=e;if(!o||t==="turn"&&!c)throw new Error("Usage: interscale rc history <session> [--limit 100] [--cursor CURSOR] | turn <session> <turn-id>");return b(t==="history"?await i.rcTurns(o,{limit:n.limit===void 0?void 0:Number(n.limit),cursor:n.cursor}):await i.rcTurn(o,c),n)}if(t==="send"){let[o,...c]=e,l=n.message||c.join(" ")||r.join(" ");if(!o||!l)throw new Error("Usage: interscale rc send <session-id> <message> [--follow] (ou: rc send <session-id> -- <message>)");let d=await i.messageRcSession(o,l,{requestId:n["request-id"]});if(n.json&&!A(n.follow,!1))return b(d,n);if(n.json||console.error(`${d.turn.id} ${d.turn.state} seq=${d.turn.seq}`),A(n.follow,!1)){let u=await uU(i,o,d.turn.id,n);if(n.json)return b({turn:u},n)}return}if(t==="log"||t==="logs"){let o=e[0];if(!o)throw new Error("Usage: interscale rc log <session-id> [--follow] [--since <seq>]");if(!A(n.follow,!1)){let{session:l}=await i.rcSession(o);if(n.json)return b({session:l},n);for(let d of l.turns)console.log(`> ${d.message}`),d.result_text&&console.log(d.result_text),d.error?console.error(`[${d.state}] ${d.error.code}: ${d.error.message}`):d.result_text||console.error(`[${d.state}]`);return}let c=await Gi(i,`RC session ${o}`,l=>i.followRcSession(o,{signal:l,sinceSeq:n.since??0,onEvent:a(d=>{d.type==="turn_state"&&d.payload?.result?(n.json?process.stderr:process.stdout).write(`${d.payload.result}
|
|
517
|
+
`):d.type==="turn_state"?process.stderr.write(`${d.payload?.turn_id||""} ${d.payload?.state||""}
|
|
518
|
+
`):d.type==="state"&&process.stderr.write(`${o}: ${d.payload?.state||""}
|
|
519
|
+
`)},"onEvent")}));return c.state!=="succeeded"&&(process.exitCode=2),n.json&&b({session:c},n),c}if(t==="status"){let o=e[0];if(!o)throw new Error("Usage: interscale rc status <session-id>");return b(await i.rcSession(o),n)}if(t==="cancel"){let o=e[0];if(!o)throw new Error("Usage: interscale rc cancel <session-id>");return b(await i.cancelRcSession(o),n)}if(t==="end"){let o=e[0];if(!o)throw new Error("Usage: interscale rc end <session-id>");return b(await i.endRcSession(o),n)}if(t&&t!=="list")throw new Error("Usage: interscale rc start|send|log|status|list|cancel|end");let s=await i.rcSessions({node:n.node,limit:n.limit});if(n.json)return b(s,n);if(s.sessions.length===0)return console.log("No rc sessions.");console.table(s.sessions.map(o=>({id:o.id,state:o.state,provider:o.provider,node:o.node_id,profile:o.permission_profile,title:o.title||"",updated:new Date(o.updated_at).toISOString()})))}async function uU(t,e,r,n={}){let i=await Gi(t,`RC turn ${e}/${r}`,s=>t.followRcTurn(e,r,{signal:s,onState:a(o=>process.stderr.write(`${r}: ${o.state}
|
|
520
|
+
`),"onState")}));return i.result_text&&(n.json?process.stderr:process.stdout).write(`${i.result_text}
|
|
521
|
+
`),i.error?.message&&(process.stderr.write(`${i.error.code}: ${i.error.message}
|
|
522
|
+
`),i.error.next_action&&process.stderr.write(`next: ${i.error.next_action}
|
|
523
|
+
`)),i.state!=="succeeded"&&(process.exitCode=2),i}async function hU(t,e){if(t==="serve"||!t){let{runMcpServer:r}=await Promise.resolve().then(()=>(ZE(),KE));return r()}if(t==="install")return b(await Ml(),e);throw new Error("Usage: interscale mcp install|serve")}async function Ml(){let t=Q(Mo(Ul(import.meta.url)),".."),e=Tf&&Hy()||Mh({runtimeRoot:t}),{ensureMcpIntegrations:r}=await Promise.resolve().then(()=>(lS(),cS));return{launchers:e,...await r({launchers:e})}}async function pU(t,e,r){if(!t||e.length===0)throw new Error("Usage: interscale run <machine> [options] -- <executable> [arguments]");let{client:n}=U();if(r["result-dir"]&&r["outputs-json"]===void 0)throw new Error("--result-dir requires --outputs-json with the files to retrieve");let i=await n.run(t,e,{timeoutSeconds:r.timeout,inputs:r["inputs-json"]===void 0?void 0:JSON.parse(r["inputs-json"]),cwdAlias:r.cwd,outputs:r["outputs-json"]===void 0?void 0:JSON.parse(r["outputs-json"]),environmentProfile:r["environment-profile"],workspace:r.workspace,workspaceRevision:r["workspace-revision"],cwdRelative:r["cwd-relative"],gpu:r.gpu,exclusive:A(r.exclusive,!1),idempotencyKey:r.idempotency});if(r["result-dir"]){let s=await $l(n,i.job.id,r),o=await lo(n,s,r["result-dir"]);return b({...i,job:s,results:o},r)}if(r.json){if(!A(r.follow,!1))return b(i,r);let s=await $l(n,i.job.id,r);return b({...i,job:s},r)}console.log(`${i.job.id} ${i.job.state}${i.deduplicated?" (deduplicated)":""}`),A(r.follow,!1)&&await $l(n,i.job.id)}async function fU(t){let{client:e}=U(),r=await e.jobs(t.limit??100,{node:t.node,state:t.state,cursor:t.cursor});if(t.json)return b(r,t);console.table(r.jobs.map(n=>({id:n.id,state:n.state,node:n.target_node_id,command:n.payload.task?.argv?.join(" ")||n.payload.task?.type,created:new Date(n.created_at).toISOString()}))),r.next_cursor&&console.error(`More jobs: repeat with --cursor ${r.next_cursor} and the same filters.`)}async function mU(t){let{client:e}=U();try{let r=await e.activity({node:t.node,workspace:t.workspace,operation:t.operation,parent:t.parent,kind:t.kind,status:t.status,limit:t.limit,cursor:t.cursor});if(t.json)return b(r,t);console.table(r.items.map(n=>({kind:n.kind,id:n.id,state:n.state,phase:n.phase,node:n.node?.name||n.node?.id||"",route:n.route||"",waiting:n.queue_reason||"",expires:n.expires_at?new Date(n.expires_at).toISOString():"",updated:new Date(n.updated_at).toISOString()}))),console.error(`Open ${r.summary.open}; offline ${r.summary.offline}; stalled ${r.summary.stalled}; conflicts ${r.summary.conflicts}.`),r.next_cursor&&console.error(`More activity: repeat with --cursor ${r.next_cursor} and the same filters.`)}finally{e.close()}}async function _U(t,e){if(!t)throw new Error("Usage: interscale logs <job-id> [--follow]");let{client:r}=U();if(A(e.follow,!1)){let i=await $l(r,t,e);return e.json&&b({job:i},e),i}let n=[];await r.eachJobPage(t,"logs",i=>{if(e.json)n.push(...i);else for(let s of i)process.stdout.write(`[${s.stream}] ${s.text}`)}),e.json&&b({logs:n,next_since_seq:n.at(-1)?.seq??0},e)}async function gU(t,e){if(!t)throw new Error("Usage: interscale cancel <job-id>");let{client:r}=U();b(await r.cancel(t),e)}async function wU(t,e){if(!t)throw new Error("Usage: interscale revoke <machine>");let{client:r}=U();b(await r.revokeNode(t),e)}async function yU(t,e,r){let{client:n}=U();if(!t||t==="list"){let i=await n.controllerTokens();if(r.json)return b(i,r);console.table(i.tokens.map(s=>({id:s.id,name:s.name,created:new Date(s.created_at).toISOString(),last_used:s.last_used_at?new Date(s.last_used_at).toISOString():"never",state:s.revoked_at?"revoked":"active"})));return}if(t==="create"){if(typeof r.name!="string"||!r.name.trim())throw new Error("Usage: interscale token create --name <controller>");let i=await n.createControllerToken(r.name.trim());if(r.json)return b(i,r);console.log(`Controller token ${i.token.id} created for "${i.token.name}".
|
|
524
|
+
|
|
525
|
+
Setup link - open it once on the phone, then add Interscale to the Home Screen:
|
|
526
|
+
${i.setup_url}
|
|
527
|
+
|
|
528
|
+
Secret - paste it in the app if the link cannot be opened:
|
|
529
|
+
${i.secret}
|
|
530
|
+
|
|
531
|
+
This secret is shown once and never stored by the hub. Revoke it with:
|
|
532
|
+
interscale token revoke ${i.token.id}`);return}if(t==="revoke"){let i=e[0];if(!i)throw new Error("Usage: interscale token revoke <token-id>");return b(await n.revokeControllerToken(i),r)}throw new Error("Usage: interscale token create --name <controller> | token list | token revoke <token-id>")}async function bU(t,e,r){let{client:n}=U();try{if(!t||t==="list")return b(await n.desktopSessions({node:r.node,limit:r.limit===void 0?100:Number(r.limit)}),r);if(t==="doctor"){if(!e[0])throw new Error("Usage: interscale desktop doctor <machine> [--json]");let i=await n.desktopDoctor(e[0]);return i.ready||(process.exitCode=2),b(i,r)}if(t==="open"){if(!e[0])throw new Error("Usage: interscale desktop open <machine> [--request-id <id>] [--json]");if(["display","quality","audio","input"].some(i=>r[i]!==void 0))throw new Error("Interscale selects the active display and low-latency desktop settings automatically");return b(await n.createDesktopSession(e[0],{quality:"latency",requestId:r["request-id"],audio:!0,input:!0}),r)}if(!e[0])throw new Error("Usage: interscale desktop status|events|close|reconcile|ticket <session-id>");if(t==="status")return b(await n.desktopSession(e[0]),r);if(t==="events")return b(await n.desktopSessionEvents(e[0],{since:Number(r.since||0),limit:Number(r.limit||100)}),r);if(t==="close")return b(await n.closeDesktopSession(e[0]),r);if(t==="reconcile")return b(await n.reconcileDesktopSession(e[0]),r);if(t==="ticket"){if(!r.fingerprint)throw new Error("Usage: interscale desktop ticket <session-id> --fingerprint <controller-id> [--json]");return b(await n.issueDesktopTicket(e[0],r.fingerprint),r)}throw new Error("Usage: interscale desktop doctor|open|list|status|events|close|reconcile|ticket")}finally{n.close()}}async function _S(t,e){let r=new Pn;try{if(A(e.list,!1))return b({transfers:r.active()},e);if(A(e.pending,!1))return b({requests:r.pendingRequests()},e);if(e.forget!==void 0){if(typeof e.forget!="string"||!e.forget)throw new Error("Usage: interscale cp --forget <transfer-id>");let p=r.get(e.forget);return r.fail(e.forget),p.temporary&&await An(p.source_path),b({forgotten:e.forget},e)}if(e.resume!==void 0)return await vU(r,e);if(!t||typeof e.to!="string")throw new Error("Usage: interscale cp <file> --to <machine>:<destination> or interscale cp --resume <transfer-id>");let n=e.to.indexOf(":");if(n<1)throw new Error("--to must use <machine>:<destination>");let i=e.to.slice(0,n),s=e.to.slice(n+1),o=Q(t),{session:c,client:l}=U(),d=r.prepareRequest({serverUrl:c.server_url,input:{source_path:o,target:i,destination_path:s,overwrite:A(e.overwrite,!1)},requestId:e["request-id"]}),u=await Mi(o,e),h;try{let p=await l.copyFile(u.path,i,s,{...kf(e),kind:u.kind,sourceName:u.source_name,overwrite:A(e.overwrite,!1),requestId:d,onCreated:a(({transfer:f,token:m})=>{h=f.id,r.save({serverUrl:c.server_url,token:m,sourcePath:u.path,target:i,destinationPath:s,transfer:f,temporary:u.temporary,requestId:d}),e.json||process.stderr.write(`Transfer ${f.id} created. Resume with: interscale cp --resume ${f.id}
|
|
533
|
+
`)},"onCreated"),onRouteChange:a(({route:f,reason:m})=>{e.json||process.stderr.write(`
|
|
534
|
+
Direct route unavailable (${m}); switching to ${f}.
|
|
535
|
+
`)},"onRouteChange"),onProgress:yS(e)});h&&r.complete(h),u.temporary&&await An(u.path),e.json||process.stderr.write(`
|
|
536
|
+
`),b(p,e)}catch(p){throw h&&p?.terminal&&r.fail(h),u.temporary&&(!h||p?.terminal)&&await An(u.path),p}}finally{r.close()}}async function vU(t,e){if(typeof e.resume!="string"||!e.resume)throw new Error("Usage: interscale cp --resume <transfer-id>");let r=t.get(e.resume),{session:n,client:i}=U();if(n.server_url!==r.server_url)throw new Error(`Transfer ${r.id} belongs to another Interscale hub/package`);e.json||process.stderr.write(`Resuming ${r.id} from ${r.source_path}
|
|
537
|
+
`);try{let s=await i.resumeCopy(r.source_path,r.id,r.token,{onRouteChange:a(({route:o,reason:c})=>{e.json||process.stderr.write(`
|
|
538
|
+
Direct route unavailable (${c}); switching to ${o}.
|
|
539
|
+
`)},"onRouteChange"),onProgress:yS(e)});t.complete(r.id),r.temporary&&await An(r.source_path),e.json||process.stderr.write(`
|
|
540
|
+
`),b(s,e)}catch(s){throw s?.terminal&&(t.fail(r.id),r.temporary&&await An(r.source_path)),s}}function EU(t,e){if(t==null||t==="")return e;let r=String(t).trim().match(/^(\d+)\s*(b|k|kib|kb|m|mib|mb|g|gib|gb)?$/i);if(!r)throw new Error(`Invalid size: ${t}`);let n={b:1,k:1024,kib:1024,kb:1024,m:1024**2,mib:1024**2,mb:1024**2,g:1024**3,gib:1024**3,gb:1024**3},i=Number(r[1])*(r[2]?n[r[2].toLowerCase()]:1);if(!Number.isSafeInteger(i)||i<1)throw new Error(`Invalid size: ${t}`);return i}function SU(t,e){if(t==null||t==="")return e;let r=Number(t);if(!Number.isInteger(r)||r<1||r>64)throw new Error("--concurrency must be between 1 and 64");return r}function kf(t){return{directConcurrency:SU(t.concurrency,4),...t["chunk-size"]===void 0?{}:{chunkSize:EU(t["chunk-size"])}}}async function TU(t,e,r){if(!e[0]||!e[1])throw new Error(`Usage: interscale transfer ${t} <source> <destination> [--request-id <stable-key>] [--overwrite]`);let n=hS(e[0]),i=hS(e[1]);if(n.local&&i.local)throw new Error("At least one transfer endpoint must name an enrolled node");if(t==="start"){if(n.local)return _S(n.path,{...r,to:`${i.node}:${i.path}`});if(i.local)return gS(`${n.node}:${n.path}`,{...r,output:i.path});let{client:c}=U();try{let l=await c.startTransfer({node:n.node,path:n.path},{node:i.node,path:i.path},{overwrite:A(r.overwrite,!1),requestId:r["request-id"]});if(!A(r.follow,!1))return b(l,r);let d=await Gi(c,`transfer ${l.transfer.id}`,u=>c.followTransfer(l.transfer.id,h=>{r.json||process.stderr.write(`${ES(h)}
|
|
541
|
+
`)},{signal:u,timeoutMs:vS(r.timeout)}));return d.durable_state!=="succeeded"&&(process.exitCode=2),b({...l,transfer:d},r)}finally{c.close()}}let{client:s}=U(),o;try{if(!n.local&&!i.local)return b(await s.planTransfer({node:n.node,path:n.path},{node:i.node,path:i.path},{overwrite:A(r.overwrite,!1)}),r);if(n.local){o=await Mi(Q(n.path),r);let l=await Bl(o.path),{FileHasher:d}=await Promise.resolve().then(()=>(ic(),Xg)),u=new d,h;try{h=await u.hash(o.path,{expected:l})}finally{await u.close()}let p=await s.planUploadTransfer({kind:o.kind,source_name:o.source_name,size:l.size,sha256:h},{node:i.node,path:i.path},{overwrite:A(r.overwrite,!1)});return b(p,r)}let c=await s.planDownloadTransfer({node:n.node,path:n.path});return c.destination=await kU(i.path,c.source,A(r.overwrite,!1)),c.target="local",b(c,r)}finally{o?.temporary&&await An(o.path),s.close()}}function hS(t){if(typeof t!="string"||!t||t.includes("\0"))throw new Error("Transfer references must be nonempty paths");if(t.startsWith("local:"))return{local:!0,path:t.slice(6)};if(fS(t)||Ve()==="win32"&&/^(?:[A-Za-z]:[\\/]|\\\\)/.test(t)||!t.includes(":"))return{local:!0,path:t};let e=t.indexOf(":"),r=t.slice(0,e),n=t.slice(e+1);if(!r||!n)throw new Error("Remote references must use <node>:<absolute-path>");return{local:!1,node:r,path:n}}async function kU(t,e,r){let n=Q(t),i=null;try{let u=await Bl(n);if(u.isSymbolicLink())throw Object.assign(new Error("Transfer destinations cannot be symbolic links"),{code:"symbolic_link_destination"});if(i={type:u.isDirectory()?"directory":u.isFile()?"file":"other",size:u.size},!r)throw Object.assign(new Error(`Destination already exists: ${n}`),{code:"destination_exists"});if(e.kind==="directory-tar"!==u.isDirectory())throw Object.assign(new Error("Existing destination type does not match the transfer source"),{code:"destination_type_mismatch"})}catch(u){if(u.code!=="ENOENT")throw u}let s=1024**3;await Tc({stagingPath:x(),destinationPath:n,size:e.size,reserve:s,directory:e.kind==="directory-tar"});let o=await Sc(Mo(n)),{statfs:c}=await import("node:fs/promises"),l=await c(o.path,{bigint:!0}),d=BigInt(l.bavail)*BigInt(l.bsize);return{destination_path:n,exists:!!i,existing:i,overwrite:r,available_bytes:Number(d>BigInt(Number.MAX_SAFE_INTEGER)?BigInt(Number.MAX_SAFE_INTEGER):d),required_bytes:e.size*(e.kind==="directory-tar"?2:1)+s,reusable_content:!1}}async function gS(t,e){let r=new Dn;try{if(A(e.list,!1))return b({downloads:r.active()},e);if(A(e.pending,!1))return b({requests:r.pendingRequests()},e);let{session:n,client:i}=U(),s,o;if(e.resume!==void 0){if(typeof e.resume!="string"||!e.resume)throw new Error("Usage: interscale pull --resume <download-id>");if(s=r.get(e.resume),s.server_url!==n.server_url)throw new Error(`Download ${s.id} belongs to another Interscale hub/package`);o=(await i.resumeDownload(s.id,s.token)).direct_candidates,e.json||process.stderr.write(`Resuming ${s.id} to ${s.output_path}
|
|
542
|
+
`)}else{if(typeof t!="string"||!t)throw new Error("Usage: interscale pull <machine>:<path> --output <path>");let l=t.indexOf(":");if(l<1)throw new Error("Usage: interscale pull <machine>:<path> --output <path>");let d=t.slice(0,l),u=t.slice(l+1);if(!u)throw new Error("A source path is required: interscale pull <machine>:<path>");let h=typeof e.output=="string"&&e.output?e.output:pS(u.replace(/[/\\]+$/,""))||"pulled",p=r.prepareRequest({serverUrl:n.server_url,input:{node:d,path:u},outputPath:h,requestId:e["request-id"]}),f=await wS(()=>i.createPull(d,u,{requestId:p}),p);s=r.saveCreated({requestId:p,serverUrl:n.server_url,token:f.token,sourcePath:u,relativePath:".",outputPath:h,download:f.download}),o=f.direct_candidates,e.json||process.stderr.write(`Pull ${s.id} created. Resume with: interscale pull --resume ${s.id}
|
|
543
|
+
`)}let c=await co(i,s,o,r,{...kf(e),overwrite:A(e.overwrite,!1),onProgress:bS(e)});e.json||process.stderr.write(`
|
|
544
|
+
`),b(c,e)}finally{r.close()}}async function xU(t,e){let r=new Dn;try{if(A(e.list,!1))return b({downloads:r.active()},e);if(A(e.pending,!1))return b({requests:r.pendingRequests()},e);let{session:n,client:i}=U(),s,o;if(e.resume!==void 0){if(typeof e.resume!="string"||!e.resume)throw new Error("Usage: interscale get --resume <download-id>");if(s=r.get(e.resume),s.server_url!==n.server_url)throw new Error(`Download ${s.id} belongs to another Interscale hub/package`);o=(await i.resumeDownload(s.id,s.token)).direct_candidates,e.json||process.stderr.write(`Resuming ${s.id} to ${s.output_path}
|
|
545
|
+
`)}else{if(!t||typeof e.output!="string"||!e.output)throw new Error("Usage: interscale get <job-id> --output <path> [--path relative-result]");let l=typeof e.path=="string"?e.path:".",d=r.prepareRequest({serverUrl:n.server_url,input:{job_id:t,relative_path:l},outputPath:e.output,requestId:e["request-id"]}),u=await wS(()=>i.createDownload(t,l,{requestId:d}),d);s=r.saveCreated({requestId:d,serverUrl:n.server_url,token:u.token,jobId:t,relativePath:l,outputPath:e.output,download:u.download}),o=u.direct_candidates,e.json||process.stderr.write(`Download ${s.id} created. Resume with: interscale get --resume ${s.id}
|
|
546
|
+
`)}let c=await co(i,s,o,r,{...kf(e),overwrite:A(e.overwrite,!1),onProgress:bS(e)});return!e.json&&!e.quiet&&process.stderr.write(`
|
|
547
|
+
`),e.quiet||b(c,e),c}finally{r.close()}}async function wS(t,e){try{return await t()}catch(r){throw r.request_id=e,r.message+=`; retry the same command with --request-id ${e} (saved under pull/get --pending)`,r}}function yS(t){return({index:e,total:r,skipped:n,route:i})=>{t.json||process.stderr.write(`\r${n?"resume":"upload"} ${i||"direct"} chunk ${e+1}/${r}`)}}function bS(t){return({index:e,total:r,skipped:n})=>{t.json||process.stderr.write(`\r${n?"resume":"download"} chunk ${e+1}/${r}`)}}async function RU(t,e){let r=be(),n={schema:"interscale.doctor/v1",server_url:r.server_url,hub:{reachable:!1},authentication:{state:"not_checked"},checks:[]};try{n.hub={...await ne(r.server_url,"/health"),reachable:!0},n.checks.push({id:"hub_reachability",state:"pass",message:"Hub health endpoint responded"})}catch(s){return n.hub={reachable:!1,error:{code:s.code||"network_error",message:s.message}},n.checks.push({id:"hub_reachability",state:"fail",message:s.message,next_action:"Verify the hub URL, DNS, TLS and server process."}),process.exitCode=2,b(n,e)}let i=new Je(r.server_url,r.fleet_key);try{let s=await i.whoami();n.authentication={state:"pass",actor:s.session?.client_name||"controller",kind:s.session?.kind||null}}catch(s){return n.authentication={state:"fail",error:{code:s.code||"authentication_failed",message:s.message}},n.checks.push({id:"hub_authentication",state:"fail",message:s.message,next_action:"Verify the fleet profile and rotate a compromised or revoked credential."}),process.exitCode=2,i.close(),b(n,e)}try{let s=await i.diagnostics(t||null);if(n.diagnostics=s,n.checks.push(...s.checks),e.path!==void 0){if(!t)throw Object.assign(new Error("--path requires a machine"),{code:"diagnostic_node_required"});try{n.path=await i.fileStat(t,String(e.path)),n.checks.push({id:"path_access",state:"pass",message:"The node resolved and inspected the requested path"})}catch(o){n.path={requested:String(e.path),error:{code:o.code||"path_unavailable",message:o.message}},n.checks.push({id:"path_access",state:"fail",message:o.message,next_action:"Check the exact path spelling on the remote operating system, mount availability, and account permissions."})}}s.checks.some(o=>o.state==="fail")&&(process.exitCode=2),n.checks.some(o=>o.state==="fail")&&(process.exitCode=2)}catch(s){n.checks.push({id:"diagnostics",state:"fail",message:s.message,next_action:t?"Verify the machine identity or run doctor without a machine to inspect fleet reachability.":"Upgrade the hub diagnostics endpoint."}),process.exitCode=2}finally{i.close()}b(n,e)}async function OU(t,e,r,n){let{repoPreflight:i,workerReadiness:s}=await Promise.resolve().then(()=>(wf(),AE)),{client:o}=U();try{if(t==="workers"){let c=[];for(let d;;){let u=await o.nodes({limit:200,cursor:d});if(c.push(...u.nodes||[]),!u.next_cursor)break;d=u.next_cursor}let l=s(c);if(n.json)return b({workers:l},n);for(let d of l)console.log(`${d.ready?"ready ":"missing"} ${d.name}${d.ready?"":`: ${d.missing.join(", ")}`}`);return}if(e!=="preflight"||!r[0]||!r[1])throw new Error("Usage: interscale repo preflight <machine> <path> [--json]");return b(await i(o,r[0],r[1]),n)}finally{o.close()}}function U(){let t;try{t=be()}catch(n){throw/Keychain/.test(n.message)?Object.assign(new Error(`${n.message}. A sandboxed shell cannot read it: use the Interscale MCP tools (interscale_run, interscale_nodes\u2026) instead, or run outside the sandbox`),{code:"keychain_unavailable"}):n}let e={server_url:t.server_url,token:t.fleet_key},r=new Je(t.server_url,t.fleet_key);return jl.add(r),{session:e,client:r}}async function $l(t,e,r={}){let n,i=await Gi(t,`job ${e}`,s=>t.followJob(e,{signal:s,onEvent(o){o.type==="log"&&(r.json?process.stderr:process.stdout).write(`[${o.payload.stream||"stdout"}] ${o.payload.text||""}`),o.state&&o.state!==n&&(n=o.state,process.stderr.write(`
|
|
548
|
+
${e}: ${o.state}
|
|
549
|
+
`))}}));return console.error(`${e}: terminal state ${i.state}`),i.state!=="succeeded"&&(process.exitCode=2),i}function b(t,e={}){e.json?console.log(JSON.stringify(t)):console.log(JSON.stringify(t,null,2))}function vS(t){if(t===void 0)return null;let e=Number(t);if(!Number.isFinite(e)||e<=0||e>86400)throw new Error("--timeout must be greater than zero and no more than 86400 seconds");return Math.ceil(e*1e3)}function ES(t){let e=t.status_detail||{},r=e.progress||{},n=r.completed_bytes,i=r.total_bytes,s=Number.isSafeInteger(n)&&Number.isSafeInteger(i)?` ${n}/${i} bytes${i>0?` (${Math.floor(n/i*100)}%)`:""}`:"",o=e.queue_reason?` waiting=${e.queue_reason}`:"";return`${t.id}: ${t.state} phase=${e.phase||"unknown"} route=${e.route||"pending"}${s}${o}`}function IU(t){if(!t["r2-account-id"]&&!t["r2-bucket"])return null;if(!t["r2-account-id"]||!t["r2-bucket"]||!t["r2-access-key-id"]||!t["r2-secret-access-key-file"])throw new Error("R2 requires --r2-account-id, --r2-bucket, --r2-access-key-id and --r2-secret-access-key-file");return{account_id:t["r2-account-id"],bucket:t["r2-bucket"],access_key_id:t["r2-access-key-id"],secret_access_key_file:Q(t["r2-secret-access-key-file"])}}function SS(t){return new Promise((e,r)=>{let n=!1,i=a(async()=>{if(!n){n=!0;try{await t(),e()}catch(s){r(s)}}},"handler");process.once("SIGINT",i),process.once("SIGTERM",i)})}function NU(){console.log(`Interscale ${we} \u2014 macOS, Windows, Linux
|
|
550
|
+
|
|
551
|
+
Setup:
|
|
552
|
+
interscale hub setup [--public-url URL]
|
|
553
|
+
interscale hub start
|
|
554
|
+
interscale hub install [--caddy=false] Linux VPS systemd + HTTPS Caddy
|
|
555
|
+
interscale hub backup [output.sqlite3]
|
|
556
|
+
interscale hub restore <backup.sqlite3> Server must be stopped
|
|
557
|
+
interscale agent install [--name MACHINE] [--receive-retention-days 30] Plug-and-play, no elevation
|
|
558
|
+
interscale agent install Terminal and supported desktop control are automatic
|
|
559
|
+
interscale agent status|restart|foreground|uninstall
|
|
560
|
+
interscale agent enable-boot Windows: stay reachable after a reboot before anyone signs in
|
|
561
|
+
interscale agent enable-admin-control|disable-admin-control Windows: remote input reaches admin windows (one UAC approval)
|
|
562
|
+
interscale agent wake-target list|add <machine> --mac <address> --broadcast <IPv4[,IPv4]>|remove <machine>
|
|
563
|
+
interscale agent release-key show|pin <ed25519-public.pem>|remove
|
|
564
|
+
interscale agent received-cleanup status|preview|run --confirm [--json]
|
|
565
|
+
|
|
566
|
+
Fleet:
|
|
567
|
+
interscale release sign <manifest.json> --private-key <ed25519.pem> --out <signed-release.json>
|
|
568
|
+
interscale update verify|plan|stage|preflight|apply <signed-release.json> [--public-key <ed25519-public.pem>] [--staging-root PATH] [--previous-runtime-root PATH]
|
|
569
|
+
interscale update status [--staging-root PATH]
|
|
570
|
+
interscale update rollback --yes [--config agent.json] [--staging-root PATH]
|
|
571
|
+
interscale benchmark api [--endpoint summary|nodes|health] [--samples 200]
|
|
572
|
+
interscale fleet status [--watch] [--json] Every machine: version, update state, last error
|
|
573
|
+
interscale nodes [--kind machine|server] [--limit 100] [--cursor <cursor>] [--json] Machines (Mac, Windows), then servers (Linux)
|
|
574
|
+
interscale machines|servers [--json] Only the machines, or only the servers
|
|
575
|
+
interscale nodes wake <machine> [--request-id <id>] [--timeout-seconds 120] [--wait true|false] [--json]
|
|
576
|
+
interscale nodes wake-status <operation-id> [--json]
|
|
577
|
+
interscale nodes archive-candidates [--stale-days 30] [--limit 100] [--json]
|
|
578
|
+
interscale nodes archived [--limit 100] [--json]
|
|
579
|
+
interscale nodes archive <machine> --if-last-seen <timestamp|never> --reason <text> --confirm [--stale-days 30] [--json]
|
|
580
|
+
interscale activity [--node MACHINE] [--workspace ALIAS] [--operation ID] [--parent RUN] [--kind KIND] [--status open|terminal|all] [--limit 50] [--cursor CURSOR] [--json]
|
|
581
|
+
interscale desktop doctor <machine> [--json]
|
|
582
|
+
interscale desktop open <machine> [--request-id ID] [--json]
|
|
583
|
+
interscale desktop list [--node MACHINE] [--limit 100] [--json]
|
|
584
|
+
interscale desktop status|events|close|reconcile <session-id> [--json]
|
|
585
|
+
interscale desktop ticket <session-id> --fingerprint <controller-id> [--json]
|
|
586
|
+
interscale inspect <machine> [--section hardware|gpus|runtimes|frameworks|tools|network|protocol_features] [--limit 100] [--cursor <cursor>] [--json]
|
|
587
|
+
interscale run <machine> [--workspace ALIAS] [--workspace-revision HASH] [--cwd-relative SUBDIR] [--environment-profile NAME] [--inputs-json JSON_ARRAY] [--outputs-json JSON_ARRAY] [--result-dir DIRECTORY] [--idempotency KEY] [--timeout SEC] [--follow] -- <command> [args]
|
|
588
|
+
interscale jobs [--node <machine>] [--state <state>] [--limit 100] [--cursor <cursor>] [--json]
|
|
589
|
+
interscale job <job-id> [--json]
|
|
590
|
+
interscale logs <job-id> [--follow]
|
|
591
|
+
interscale cancel <job-id>
|
|
592
|
+
interscale revoke <machine>
|
|
593
|
+
interscale token create --name <phone>
|
|
594
|
+
interscale token list|revoke <token-id>
|
|
595
|
+
interscale doctor [machine] [--path ABSOLUTE]
|
|
596
|
+
interscale capabilities [--node MACHINE] [--limit 100] [--cursor <cursor>]
|
|
597
|
+
interscale find <capability> [--node MACHINE] [--limit 100] [--cursor <cursor>]
|
|
598
|
+
interscale recipes [machine]
|
|
599
|
+
interscale ensure <capability-or-recipe> --on <machine>
|
|
600
|
+
|
|
601
|
+
Data:
|
|
602
|
+
interscale cp <file-or-directory> --to <machine>:<destination> [--overwrite]
|
|
603
|
+
common transfer options: [--concurrency N] [--chunk-size 64M]
|
|
604
|
+
interscale cp --resume <transfer-id>
|
|
605
|
+
interscale cp --forget <transfer-id> Drop a local record that can no longer resume
|
|
606
|
+
interscale cp --list
|
|
607
|
+
interscale transfer list [--node MACHINE] [--state STATE] [--limit 50] [--json]
|
|
608
|
+
interscale transfer plan <local-path|machine:path> <local-path|machine:path> [--overwrite] [--json]
|
|
609
|
+
interscale transfer start <local-path|machine:path> <local-path|machine:path> [--request-id <stable-key>] [--overwrite] [--json]
|
|
610
|
+
interscale transfer status <transfer-id> [--follow] [--timeout SEC] [--json]
|
|
611
|
+
interscale transfer events <transfer-id> [--since-seq N] [--limit 100] [--json]
|
|
612
|
+
interscale transfer pause|resume|cancel <transfer-id> [--json]
|
|
613
|
+
interscale files find <query> --node <machine> [--source live --path <absolute-root>] [--library <name>] [--json]
|
|
614
|
+
interscale context --node <machine> [--json]
|
|
615
|
+
interscale files stat <absolute-path> --node <machine> [--json]
|
|
616
|
+
interscale files list <absolute-directory> --node <machine> [--limit 100] [--cursor <cursor>] [--json]
|
|
617
|
+
interscale pull <machine>:<path> --output <path> [--overwrite] [--request-id <key>]
|
|
618
|
+
interscale operation list | status <id> | events <id> [--since <cursor>] [--json]
|
|
619
|
+
interscale pull --resume <download-id>
|
|
620
|
+
interscale pull --pending [--json]
|
|
621
|
+
interscale get <job-id> --output <path> [--path relative-result]
|
|
622
|
+
interscale get --resume <download-id>
|
|
623
|
+
interscale get --list
|
|
624
|
+
interscale library add <name> <path>
|
|
625
|
+
interscale library remove <name>|scan|list
|
|
626
|
+
interscale workspace list [--config <agent.json>] [--json]
|
|
627
|
+
interscale workspace list --node <machine> [--limit 100] [--cursor <cursor>] [--json]
|
|
628
|
+
interscale library list [--node <machine>] [--kind all|user|job] [--limit 100] [--cursor <cursor>] [--json]
|
|
629
|
+
interscale artifacts [query] [--node MACHINE]
|
|
630
|
+
interscale artifact where <id-or-name>
|
|
631
|
+
interscale artifact register <path>
|
|
632
|
+
interscale artifact stage <id-or-name> --to <machine>
|
|
633
|
+
|
|
634
|
+
Automation:
|
|
635
|
+
interscale rc start <machine> --cwd <absolute-path> [--provider claude|codex (default claude)]
|
|
636
|
+
[--permission-mode full|workspace|read-only] [--model M] [--title T] [--budget USD]
|
|
637
|
+
interscale rc send <session-id> <message> [--follow] ("rc send <id> -- <msg>" if it starts with --)
|
|
638
|
+
interscale rc log <session-id> [--follow]
|
|
639
|
+
interscale rc list|status|cancel|end
|
|
640
|
+
interscale workers [--json] which machines can host worker agents, and what each lacks
|
|
641
|
+
interscale repo preflight <machine> <path> what a copy or move must carry beyond git
|
|
642
|
+
interscale term <machine> list
|
|
643
|
+
interscale term <machine> send <target> --text "..." [--enter] | --key C-c[,Escape]
|
|
644
|
+
interscale term <machine> capture <target> [--lines 200] [--ansi]
|
|
645
|
+
interscale term <machine> start <session> [--cwd-alias A] [-- command args]
|
|
646
|
+
interscale term <machine> kill <session>
|
|
647
|
+
interscale shell <machine> [--session NAME] [--no-create] [-- command args]
|
|
648
|
+
interactive terminal (tmux on macOS/Linux, ConPTY on Windows; survives detach; Ctrl-] detaches)
|
|
649
|
+
term and shell share sessions: shell --session NAME attaches to a term-started session
|
|
650
|
+
interscale mcp install|serve
|
|
651
|
+
Add --json for machine-readable output.
|
|
652
|
+
interscale login [--hub URL] [--name COMPUTER] Shows a code; approve it in the browser (works over SSH)
|
|
653
|
+
interscale login --email <email> [--password-stdin] [--hub URL] Password sign-in, for scripts
|
|
654
|
+
interscale login --token-stdin [--hub URL] Keep a sign-in handed over by the Linux installer
|
|
655
|
+
interscale login --release-key <public.pem> A self-hosted hub that signs its own releases
|
|
656
|
+
interscale login --join|--no-join Add this computer to the fleet without asking, or never ask
|
|
657
|
+
interscale join [--name COMPUTER] Add this computer to the fleet (verified official package)
|
|
658
|
+
interscale logout
|
|
659
|
+
interscale account setup --email <owner-email>
|
|
660
|
+
interscale account invite|reset-password --email <teammate-email>
|
|
661
|
+
interscale account share|unshare <machine> --email <teammate-email>
|
|
662
|
+
interscale hub password --password-stdin
|
|
663
|
+
Authentication uses this installation's revocable credentials; legacy private profiles remain supported during migration.`)}async function xf(t){process.stdout.write(t),process.stdin.setRawMode(!0),process.stdin.resume();let e="";try{for await(let r of process.stdin)for(let n of r.toString("utf8")){if(n==="")throw new Error("Cancelled");if(n==="\r"||n===`
|
|
664
|
+
`)return e;if(n==="\x7F"||n==="\b"?e=e.slice(0,-1):e+=n,Buffer.byteLength(e)>1024)throw new Error("Password input is too large")}return e}finally{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
665
|
+
`)}}async function Bo(){if(process.stdin.isTTY)throw new Error("Read the password from a pipe or protected file; do not put it in command arguments");let t="";for await(let e of process.stdin)if(t+=e.toString(),Buffer.byteLength(t)>1026)throw new Error("Password input is too large");return t.replace(/\r?\n$/,"")}function Ef({os:t=Ve(),root:e=li(x(),"updates")}={}){if(t==="darwin")return null;let r=Q(Mo(Ul(import.meta.url)),".."),n={node:process.execPath,cli:li(r,"bin","interscale.mjs"),app_root:r,version:we};return U$(e,{recursive:!0,mode:448}),se(li(e,"active-runtime.json"),n),n}var Tf,q$,jl,kS=v(()=>{Ic();wy();Re();zo();cr();pd();Z();fa();pa();yy();Wy();Gy();me();nb();So();ol();S0();Cc();bi();Xi();cc();rc();Du();Sh();R0();Oo();Xn();Cp();Bp();wh();X0();Zh();Tf=!0,q$=new Set(["hub","server","agent","update"]);a(z$,"npmUpdateNotice");a(mS,"hubModules");jl=new Set;a(W$,"main");a(H$,"dispatch");a(G$,"serverCommand");a(dS,"setupServer");a(J$,"agentCommand");a(V$,"receivedCleanupCommand");a(Y$,"releaseKeyCommand");a(X$,"wakeTargetCommand");a(K$,"fleetCommand");a(Z$,"releaseCommand");a(Q$,"updateCommand");a(eU,"accountCommand");a(tU,"installAgent");a(rU,"vscodeCommand");a(uS,"nodesCommand");a(nU,"inspectNodeCommand");a(iU,"capabilitiesCommand");a(sU,"recipesCommand");a(oU,"ensureCommand");a(aU,"libraryCommand");a(cU,"artifactCommand");a(lU,"registerLocalArtifact");a(dU,"rcCommand");a(uU,"followRcTurnAndPrint");a(hU,"mcpCommand");a(Ml,"installMcpIntegrations");a(pU,"runCommand");a(fU,"jobsCommand");a(mU,"activityCommand");a(_U,"logsCommand");a(gU,"cancelCommand");a(wU,"revokeCommand");a(yU,"tokenCommand");a(bU,"desktopCommand");a(_S,"copyCommand");a(vU,"resumeCopyCommand");a(EU,"byteSizeOption");a(SU,"concurrencyOption");a(kf,"transferTuning");a(TU,"transferCommand");a(hS,"parseTransferReference");a(kU,"planLocalDestination");a(gS,"pullCommand");a(xU,"getCommand");a(wS,"submitDownloadIntent");a(yS,"progressPrinter");a(bS,"downloadProgressPrinter");a(RU,"doctorCommand");a(OU,"repoModesCommand");a(U,"authenticatedClient");a($l,"followAndPrint");a(b,"printValue");a(vS,"transferFollowTimeoutMs");a(ES,"renderTransferProgress");a(IU,"r2ConfigFromOptions");a(SS,"waitForSignals");a(NU,"printHelp");a(xf,"readHiddenLine");a(Bo,"readPassword");a(Ef,"recordActiveRuntime")});zo();try{let{positional:t,options:e}=qo(process.argv.slice(2));if(t[0]==="ssh-proxy"&&!e.help&&!e.version){let{sshProxyCommand:n}=await Promise.resolve().then(()=>(Od(),Rd));process.exit(await n(t,e))}let{main:r}=await Promise.resolve().then(()=>(kS(),TS));await r()}catch(t){console.error(`interscale: ${t.message}`),typeof t.next_action=="string"&&t.next_action&&console.error(`Next action: ${t.next_action}`),process.env.INTERSCALE_DEBUG&&console.error(t.stack),process.exit(t.exitCode||1)}
|