@linzumi/cli 1.0.31 → 1.0.32

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/README.md CHANGED
@@ -58,7 +58,7 @@ Install the CLI or run it with `npx`:
58
58
  ```bash
59
59
  npm install -g @linzumi/cli@latest
60
60
  npx -y @linzumi/cli@latest signup
61
- npx -y @linzumi/cli@1.0.31 --version
61
+ npx -y @linzumi/cli@1.0.32 --version
62
62
  linzumi --version
63
63
  ```
64
64
 
@@ -1,18 +1,18 @@
1
1
  import { createRequire } from 'node:module';
2
2
  const require = createRequire(import.meta.url);
3
- var Hr=Object.create;var hn=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var Zr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var x=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Qr=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Zr(n))!Yr.call(e,o)&&o!==r&&hn(e,o,{get:()=>n[o],enumerable:!(t=Kr(n,o))||t.enumerable});return e};var se=(e,n,r)=>(r=e!=null?Hr(Xr(e)):{},Qr(n||!e||!e.__esModule?hn(r,"default",{value:e,enumerable:!0}):r,e));var I=E((Bs,mn)=>{"use strict";var gn=["nodebuffer","arraybuffer","fragments"],yn=typeof Blob<"u";yn&&gn.push("blob");mn.exports={BINARY_TYPES:gn,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yn,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ie=E((Gs,xe)=>{"use strict";var{EMPTY_BUFFER:et}=I(),je=Buffer[Symbol.species];function nt(e,n){if(e.length===0)return et;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(n),t=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,t),t+=s.length}return t<n?new je(r.buffer,r.byteOffset,t):r}function _n(e,n,r,t,o){for(let s=0;s<o;s++)r[t+s]=e[s]^n[s&3]}function xn(e,n){for(let r=0;r<e.length;r++)e[r]^=n[r&3]}function rt(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function $e(e){if($e.readOnly=!0,Buffer.isBuffer(e))return e;let n;return e instanceof ArrayBuffer?n=new je(e):ArrayBuffer.isView(e)?n=new je(e.buffer,e.byteOffset,e.byteLength):(n=Buffer.from(e),$e.readOnly=!1),n}xe.exports={concat:nt,mask:_n,toArrayBuffer:rt,toBuffer:$e,unmask:xn};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=x("bufferutil");xe.exports.mask=function(n,r,t,o,s){s<48?_n(n,r,t,o,s):e.mask(n,r,t,o,s)},xe.exports.unmask=function(n,r){n.length<32?xn(n,r):e.unmask(n,r)}}catch{}});var wn=E((zs,Sn)=>{"use strict";var bn=Symbol("kDone"),Je=Symbol("kRun"),Ue=class{constructor(n){this[bn]=()=>{this.pending--,this[Je]()},this.concurrency=n||1/0,this.jobs=[],this.pending=0}add(n){this.jobs.push(n),this[Je]()}[Je](){if(this.pending!==this.concurrency&&this.jobs.length){let n=this.jobs.shift();this.pending++,n(this[bn])}}};Sn.exports=Ue});var de=E((qs,Cn)=>{"use strict";var ae=x("zlib"),vn=ie(),tt=wn(),{kStatusCode:En}=I(),ot=Buffer[Symbol.species],st=Buffer.from([0,0,255,255]),Se=Symbol("permessage-deflate"),M=Symbol("total-length"),X=Symbol("callback"),J=Symbol("buffers"),Y=Symbol("error"),be,De=class{constructor(n,r,t){if(this._maxPayload=t|0,this._options=n||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!be){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;be=new tt(o)}}static get extensionName(){return"permessage-deflate"}offer(){let n={};return this._options.serverNoContextTakeover&&(n.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(n.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(n.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?n.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(n.client_max_window_bits=!0),n}accept(n){return n=this.normalizeParams(n),this.params=this._isServer?this.acceptAsServer(n):this.acceptAsClient(n),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let n=this._deflate[X];this._deflate.close(),this._deflate=null,n&&n(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(n){let r=this._options,t=n.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!t)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(t.server_no_context_takeover=!0),r.clientNoContextTakeover&&(t.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(t.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?t.client_max_window_bits=r.clientMaxWindowBits:(t.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete t.client_max_window_bits,t}acceptAsClient(n){let r=n[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(n){return n.forEach(r=>{Object.keys(r).forEach(t=>{let o=r[t];if(o.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(o=o[0],t==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else if(t==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else throw new Error(`Unknown parameter "${t}"`);r[t]=o})}),n}decompress(n,r,t){be.add(o=>{this._decompress(n,r,(s,i)=>{o(),t(s,i)})})}compress(n,r,t){be.add(o=>{this._compress(n,r,(s,i)=>{o(),t(s,i)})})}_decompress(n,r,t){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ae.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ae.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Se]=this,this._inflate[M]=0,this._inflate[J]=[],this._inflate.on("error",at),this._inflate.on("data",kn)}this._inflate[X]=t,this._inflate.write(n),r&&this._inflate.write(st),this._inflate.flush(()=>{let s=this._inflate[Y];if(s){this._inflate.close(),this._inflate=null,t(s);return}let i=vn.concat(this._inflate[J],this._inflate[M]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[M]=0,this._inflate[J]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),t(null,i)})}_compress(n,r,t){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ae.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ae.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[M]=0,this._deflate[J]=[],this._deflate.on("data",it)}this._deflate[X]=t,this._deflate.write(n),this._deflate.flush(ae.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=vn.concat(this._deflate[J],this._deflate[M]);r&&(s=new ot(s.buffer,s.byteOffset,s.length-4)),this._deflate[X]=null,this._deflate[M]=0,this._deflate[J]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),t(null,s)})}};Cn.exports=De;function it(e){this[J].push(e),this[M]+=e.length}function kn(e){if(this[M]+=e.length,this[Se]._maxPayload<1||this[M]<=this[Se]._maxPayload){this[J].push(e);return}this[Y]=new RangeError("Max payload size exceeded"),this[Y].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Y][En]=1009,this.removeListener("data",kn),this.reset()}function at(e){if(this[Se]._inflate=null,this[Y]){this[X](this[Y]);return}e[En]=1007,this[X](e)}});var Q=E((Ws,we)=>{"use strict";var{isUtf8:On}=x("buffer"),{hasBlob:dt}=I(),ct=[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 lt(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Ve(e){let n=e.length,r=0;for(;r<n;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===n||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function ut(e){return dt&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}we.exports={isBlob:ut,isValidStatusCode:lt,isValidUTF8:Ve,tokenChars:ct};if(On)we.exports.isValidUTF8=function(e){return e.length<24?Ve(e):On(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=x("utf-8-validate");we.exports.isValidUTF8=function(n){return n.length<32?Ve(n):e(n)}}catch{}});var qe=E((Hs,Nn)=>{"use strict";var{Writable:ft}=x("stream"),Tn=de(),{BINARY_TYPES:pt,EMPTY_BUFFER:Pn,kStatusCode:ht,kWebSocket:gt}=I(),{concat:Fe,toArrayBuffer:yt,unmask:mt}=ie(),{isValidStatusCode:_t,isValidUTF8:Rn}=Q(),ve=Buffer[Symbol.species],C=0,An=1,In=2,Mn=3,Be=4,Ge=5,Ee=6,ze=class extends ft{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||pt[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[gt]=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=C}_write(n,r,t){if(this._opcode===8&&this._state==C)return t();this._bufferedBytes+=n.length,this._buffers.push(n),this.startLoop(t)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new ve(t.buffer,t.byteOffset+n,t.length-n),new ve(t.buffer,t.byteOffset,n)}let r=Buffer.allocUnsafe(n);do{let t=this._buffers[0],o=r.length-n;n>=t.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(t.buffer,t.byteOffset,n),o),this._buffers[0]=new ve(t.buffer,t.byteOffset+n,t.length-n)),n-=t.length}while(n>0);return r}startLoop(n){this._loop=!0;do switch(this._state){case C:this.getInfo(n);break;case An:this.getPayloadLength16(n);break;case In:this.getPayloadLength64(n);break;case Mn:this.getMask();break;case Be:this.getData(n);break;case Ge:case Ee:this._loop=!1;return}while(this._loop);this._errored||n()}getInfo(n){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");n(o);return}let t=(r[0]&64)===64;if(t&&!this._extensions[Tn.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._compressed=t}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");n(o);return}if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");n(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");n(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");n(o);return}this._payloadLength===126?this._state=An:this._payloadLength===127?this._state=In:this.haveLength(n)}getPayloadLength16(n){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(n)}getPayloadLength64(n){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),t=r.readUInt32BE(0);if(t>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");n(o);return}this._payloadLength=t*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(n)}haveLength(n){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");n(r);return}this._masked?this._state=Mn:this._state=Be}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Be}getData(n){let r=Pn;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&&mt(r,this._mask)}if(this._opcode>7){this.controlMessage(r,n);return}if(this._compressed){this._state=Ge,this.decompress(r,n);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(n)}decompress(n,r){this._extensions[Tn.extensionName].decompress(n,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===C&&this.startLoop(r)})}dataMessage(n){if(!this._fin){this._state=C;return}let r=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Fe(t,r):this._binaryType==="arraybuffer"?o=yt(Fe(t,r)):this._binaryType==="blob"?o=new Blob(t):o=t,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit("message",o,!0),this._state=C,this.startLoop(n)}))}else{let o=Fe(t,r);if(!this._skipUTF8Validation&&!Rn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._state===Ge||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit("message",o,!1),this._state=C,this.startLoop(n)}))}}controlMessage(n,r){if(this._opcode===8){if(n.length===0)this._loop=!1,this.emit("conclude",1005,Pn),this.end();else{let t=n.readUInt16BE(0);if(!_t(t)){let s=this.createError(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new ve(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!Rn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",t,o),this.end()}this._state=C;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",n),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",n),this._state=C,this.startLoop(r)}))}createError(n,r,t,o,s){this._loop=!1,this._errored=!0;let i=new n(t?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[ht]=o,i}};Nn.exports=ze});var Ke=E((Zs,$n)=>{"use strict";var{Duplex:Ks}=x("stream"),{randomFillSync:xt}=x("crypto"),Ln=de(),{EMPTY_BUFFER:bt,kWebSocket:St,NOOP:wt}=I(),{isBlob:ee,isValidStatusCode:vt}=Q(),{mask:jn,toBuffer:V}=ie(),O=Symbol("kByteLength"),Et=Buffer.alloc(4),ke=8*1024,F,ne=ke,T=0,kt=1,Ct=2,We=class e{constructor(n,r,t){this._extensions=r||{},t&&(this._generateMask=t,this._maskBuffer=Buffer.alloc(4)),this._socket=n,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=T,this.onerror=wt,this[St]=void 0}static frame(n,r){let t,o=!1,s=2,i=!1;r.mask&&(t=r.maskBuffer||Et,r.generateMask?r.generateMask(t):(ne===ke&&(F===void 0&&(F=Buffer.alloc(ke)),xt(F,0,ke),ne=0),t[0]=F[ne++],t[1]=F[ne++],t[2]=F[ne++],t[3]=F[ne++]),i=(t[0]|t[1]|t[2]|t[3])===0,s=6);let a;typeof n=="string"?(!r.mask||i)&&r[O]!==void 0?a=r[O]:(n=Buffer.from(n),a=n.length):(a=n.length,o=r.mask&&r.readOnly&&!i);let d=a;a>=65536?(s+=8,d=127):a>125&&(s+=2,d=126);let c=Buffer.allocUnsafe(o?a+s:s);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=d,d===126?c.writeUInt16BE(a,2):d===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[s-4]=t[0],c[s-3]=t[1],c[s-2]=t[2],c[s-1]=t[3],i?[c,n]:o?(jn(n,t,c,s,a),[c]):(jn(n,t,n,0,a),[c,n])):[c,n]}close(n,r,t,o){let s;if(n===void 0)s=bt;else{if(typeof n!="number"||!vt(n))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(n,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(n,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[O]:s.length,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==T?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):ee(n)?(o=n.size,s=!1):(n=V(n),o=n.length,s=V.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[O]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ee(n)?this._state!==T?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==T?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}pong(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):ee(n)?(o=n.size,s=!1):(n=V(n),o=n.length,s=V.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[O]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ee(n)?this._state!==T?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==T?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}send(n,r,t){let o=this._extensions[Ln.extensionName],s=r.binary?2:1,i=r.compress,a,d;typeof n=="string"?(a=Buffer.byteLength(n),d=!1):ee(n)?(a=n.size,d=!1):(n=V(n),a=n.length,d=V.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let c={[O]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};ee(n)?this._state!==T?this.enqueue([this.getBlobData,n,this._compress,c,t]):this.getBlobData(n,this._compress,c,t):this._state!==T?this.enqueue([this.dispatch,n,this._compress,c,t]):this.dispatch(n,this._compress,c,t)}getBlobData(n,r,t,o){this._bufferedBytes+=t[O],this._state=Ct,n.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(He,this,a,o);return}this._bufferedBytes-=t[O];let i=V(s);r?this.dispatch(i,r,t,o):(this._state=T,this.sendFrame(e.frame(i,t),o),this.dequeue())}).catch(s=>{process.nextTick(Ot,this,s,o)})}dispatch(n,r,t,o){if(!r){this.sendFrame(e.frame(n,t),o);return}let s=this._extensions[Ln.extensionName];this._bufferedBytes+=t[O],this._state=kt,s.compress(n,t.fin,(i,a)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");He(this,d,o);return}this._bufferedBytes-=t[O],this._state=T,t.readOnly=!1,this.sendFrame(e.frame(a,t),o),this.dequeue()})}dequeue(){for(;this._state===T&&this._queue.length;){let n=this._queue.shift();this._bufferedBytes-=n[3][O],Reflect.apply(n[0],this,n.slice(1))}}enqueue(n){this._bufferedBytes+=n[3][O],this._queue.push(n)}sendFrame(n,r){n.length===2?(this._socket.cork(),this._socket.write(n[0]),this._socket.write(n[1],r),this._socket.uncork()):this._socket.write(n[0],r)}};$n.exports=We;function He(e,n,r){typeof r=="function"&&r(n);for(let t=0;t<e._queue.length;t++){let o=e._queue[t],s=o[o.length-1];typeof s=="function"&&s(n)}}function Ot(e,n,r){He(e,n,r),e.onerror(n)}});var qn=E((Xs,zn)=>{"use strict";var{kForOnEventAttribute:ce,kListener:Ze}=I(),Jn=Symbol("kCode"),Un=Symbol("kData"),Dn=Symbol("kError"),Vn=Symbol("kMessage"),Fn=Symbol("kReason"),re=Symbol("kTarget"),Bn=Symbol("kType"),Gn=Symbol("kWasClean"),N=class{constructor(n){this[re]=null,this[Bn]=n}get target(){return this[re]}get type(){return this[Bn]}};Object.defineProperty(N.prototype,"target",{enumerable:!0});Object.defineProperty(N.prototype,"type",{enumerable:!0});var B=class extends N{constructor(n,r={}){super(n),this[Jn]=r.code===void 0?0:r.code,this[Fn]=r.reason===void 0?"":r.reason,this[Gn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Jn]}get reason(){return this[Fn]}get wasClean(){return this[Gn]}};Object.defineProperty(B.prototype,"code",{enumerable:!0});Object.defineProperty(B.prototype,"reason",{enumerable:!0});Object.defineProperty(B.prototype,"wasClean",{enumerable:!0});var te=class extends N{constructor(n,r={}){super(n),this[Dn]=r.error===void 0?null:r.error,this[Vn]=r.message===void 0?"":r.message}get error(){return this[Dn]}get message(){return this[Vn]}};Object.defineProperty(te.prototype,"error",{enumerable:!0});Object.defineProperty(te.prototype,"message",{enumerable:!0});var le=class extends N{constructor(n,r={}){super(n),this[Un]=r.data===void 0?null:r.data}get data(){return this[Un]}};Object.defineProperty(le.prototype,"data",{enumerable:!0});var Tt={addEventListener(e,n,r={}){for(let o of this.listeners(e))if(!r[ce]&&o[Ze]===n&&!o[ce])return;let t;if(e==="message")t=function(s,i){let a=new le("message",{data:i?s:s.toString()});a[re]=this,Ce(n,this,a)};else if(e==="close")t=function(s,i){let a=new B("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[re]=this,Ce(n,this,a)};else if(e==="error")t=function(s){let i=new te("error",{error:s,message:s.message});i[re]=this,Ce(n,this,i)};else if(e==="open")t=function(){let s=new N("open");s[re]=this,Ce(n,this,s)};else return;t[ce]=!!r[ce],t[Ze]=n,r.once?this.once(e,t):this.on(e,t)},removeEventListener(e,n){for(let r of this.listeners(e))if(r[Ze]===n&&!r[ce]){this.removeListener(e,r);break}}};zn.exports={CloseEvent:B,ErrorEvent:te,Event:N,EventTarget:Tt,MessageEvent:le};function Ce(e,n,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(n,r)}});var Xe=E((Ys,Wn)=>{"use strict";var{tokenChars:ue}=Q();function P(e,n,r){e[n]===void 0?e[n]=[r]:e[n].push(r)}function Pt(e){let n=Object.create(null),r=Object.create(null),t=!1,o=!1,s=!1,i,a,d=-1,c=-1,f=-1,p=0;for(;p<e.length;p++)if(c=e.charCodeAt(p),i===void 0)if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(p!==0&&(c===32||c===9))f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(d,f);c===44?(P(n,u,r),r=Object.create(null)):i=u,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(c===32||c===9)f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),P(r,e.slice(d,f),!0),c===44&&(P(n,i,r),r=Object.create(null),i=void 0),d=f=-1}else if(c===61&&d!==-1&&f===-1)a=e.slice(d,p),d=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(ue[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:t||(t=!0),o=!1}else if(s)if(ue[c]===1)d===-1&&(d=p);else if(c===34&&d!==-1)s=!1,f=p;else if(c===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(d!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(d,f);t&&(u=u.replace(/\\/g,""),t=!1),P(r,a,u),c===44&&(P(n,i,r),r=Object.create(null),i=void 0),a=void 0,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let g=e.slice(d,f);return i===void 0?P(n,g,r):(a===void 0?P(r,g,!0):t?P(r,a,g.replace(/\\/g,"")):P(r,a,g),P(n,i,r)),n}function Rt(e){return Object.keys(e).map(n=>{let r=e[n];return Array.isArray(r)||(r=[r]),r.map(t=>[n].concat(Object.keys(t).map(o=>{let s=t[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Wn.exports={format:Rt,parse:Pt}});var Re=E((ni,sr)=>{"use strict";var At=x("events"),It=x("https"),Mt=x("http"),Zn=x("net"),Nt=x("tls"),{randomBytes:Lt,createHash:jt}=x("crypto"),{Duplex:Qs,Readable:ei}=x("stream"),{URL:Ye}=x("url"),U=de(),$t=qe(),Jt=Ke(),{isBlob:Ut}=Q(),{BINARY_TYPES:Hn,EMPTY_BUFFER:Oe,GUID:Dt,kForOnEventAttribute:Qe,kListener:Vt,kStatusCode:Ft,kWebSocket:b,NOOP:Xn}=I(),{EventTarget:{addEventListener:Bt,removeEventListener:Gt}}=qn(),{format:zt,parse:qt}=Xe(),{toBuffer:Wt}=ie(),Ht=30*1e3,Yn=Symbol("kAborted"),en=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],Kt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_=class e extends At{constructor(n,r,t){super(),this._binaryType=Hn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Oe,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,n!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(t=r,r=[]):r=[r]),Qn(this,n,r,t)):(this._autoPong=t.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){Hn.includes(n)&&(this._binaryType=n,this._receiver&&(this._receiver._binaryType=n))}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(n,r,t){let o=new $t({allowSynchronousEvents:t.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:t.maxPayload,skipUTF8Validation:t.skipUTF8Validation}),s=new Jt(n,this._extensions,t.generateMask);this._receiver=o,this._sender=s,this._socket=n,o[b]=this,s[b]=this,n[b]=this,o.on("conclude",Yt),o.on("drain",Qt),o.on("error",eo),o.on("message",no),o.on("ping",ro),o.on("pong",to),s.onerror=oo,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),r.length>0&&n.unshift(r),n.on("close",rr),n.on("data",Pe),n.on("end",tr),n.on("error",or),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[U.extensionName]&&this._extensions[U.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(n,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(n,r,!this._isServer,t=>{t||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),nr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.ping(n||Oe,r,t)}pong(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.pong(n||Oe,r,t)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(t=r,r={}),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[U.extensionName]||(o.compress=!1),this._sender.send(n||Oe,o,t)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(_.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(_.prototype,`on${e}`,{enumerable:!0,get(){for(let n of this.listeners(e))if(n[Qe])return n[Vt];return null},set(n){for(let r of this.listeners(e))if(r[Qe]){this.removeListener(e,r);break}typeof n=="function"&&this.addEventListener(e,n,{[Qe]:!0})}})});_.prototype.addEventListener=Bt;_.prototype.removeEventListener=Gt;sr.exports=_;function Qn(e,n,r,t){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:en[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...t,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!en.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${en.join(", ")})`);let s;if(n instanceof Ye)s=n;else try{s=new Ye(n)}catch{throw new SyntaxError(`Invalid URL: ${n}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!a?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let l=new SyntaxError(d);if(e._redirects===0)throw l;Te(e,l);return}let c=i?443:80,f=Lt(16).toString("base64"),p=i?It.request:Mt.request,g=new Set,u;if(o.createConnection=o.createConnection||(i?Xt:Zt),o.defaultPort=o.defaultPort||c,o.port=s.port||c,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(u=new U(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=zt({[U.extensionName]:u.offer()})),r.length){for(let l of r){if(typeof l!="string"||!Kt.test(l)||g.has(l))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(l)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let l=o.path.split(":");o.socketPath=l[0],o.path=l[1]}let h;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let l=t&&t.headers;if(t={...t,headers:{}},l)for(let[m,w]of Object.entries(l))t.headers[m.toLowerCase()]=w}else if(e.listenerCount("redirect")===0){let l=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!l||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,l||delete o.headers.host,o.auth=void 0)}o.auth&&!t.headers.authorization&&(t.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),h=e._req=p(o),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=p(o);o.timeout&&h.on("timeout",()=>{k(e,h,"Opening handshake has timed out")}),h.on("error",l=>{h===null||h[Yn]||(h=e._req=null,Te(e,l))}),h.on("response",l=>{let m=l.headers.location,w=l.statusCode;if(m&&o.followRedirects&&w>=300&&w<400){if(++e._redirects>o.maxRedirects){k(e,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new Ye(m,n)}catch{let R=new SyntaxError(`Invalid URL: ${m}`);Te(e,R);return}Qn(e,v,r,t)}else e.emit("unexpected-response",h,l)||k(e,h,`Unexpected server response: ${l.statusCode}`)}),h.on("upgrade",(l,m,w)=>{if(e.emit("upgrade",l),e.readyState!==_.CONNECTING)return;h=e._req=null;let v=l.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){k(e,m,"Invalid Upgrade header");return}let _e=jt("sha1").update(f+Dt).digest("base64");if(l.headers["sec-websocket-accept"]!==_e){k(e,m,"Invalid Sec-WebSocket-Accept header");return}let R=l.headers["sec-websocket-protocol"],$;if(R!==void 0?g.size?g.has(R)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":g.size&&($="Server sent no subprotocol"),$){k(e,m,$);return}R&&(e._protocol=R);let Z=l.headers["sec-websocket-extensions"];if(Z!==void 0){if(!u){k(e,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let y;try{y=qt(Z)}catch{k(e,m,"Invalid Sec-WebSocket-Extensions header");return}let S=Object.keys(y);if(S.length!==1||S[0]!==U.extensionName){k(e,m,"Server indicated an extension that was not requested");return}try{u.accept(y[U.extensionName])}catch{k(e,m,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[U.extensionName]=u}e.setSocket(m,w,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(h,e):h.end()}function Te(e,n){e._readyState=_.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function Zt(e){return e.path=e.socketPath,Zn.connect(e)}function Xt(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Zn.isIP(e.host)?"":e.host),Nt.connect(e)}function k(e,n,r){e._readyState=_.CLOSING;let t=new Error(r);Error.captureStackTrace(t,k),n.setHeader?(n[Yn]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(Te,e,t)):(n.destroy(t),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function nn(e,n,r){if(n){let t=Ut(n)?n.size:Wt(n).length;e._socket?e._sender._bufferedBytes+=t:e._bufferedAmount+=t}if(r){let t=new Error(`WebSocket is not open: readyState ${e.readyState} (${L[e.readyState]})`);process.nextTick(r,t)}}function Yt(e,n){let r=this[b];r._closeFrameReceived=!0,r._closeMessage=n,r._closeCode=e,r._socket[b]!==void 0&&(r._socket.removeListener("data",Pe),process.nextTick(er,r._socket),e===1005?r.close():r.close(e,n))}function Qt(){let e=this[b];e.isPaused||e._socket.resume()}function eo(e){let n=this[b];n._socket[b]!==void 0&&(n._socket.removeListener("data",Pe),process.nextTick(er,n._socket),n.close(e[Ft])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function Kn(){this[b].emitClose()}function no(e,n){this[b].emit("message",e,n)}function ro(e){let n=this[b];n._autoPong&&n.pong(e,!this._isServer,Xn),n.emit("ping",e)}function to(e){this[b].emit("pong",e)}function er(e){e.resume()}function oo(e){let n=this[b];n.readyState!==_.CLOSED&&(n.readyState===_.OPEN&&(n._readyState=_.CLOSING,nr(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function nr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Ht)}function rr(){let e=this[b];this.removeListener("close",rr),this.removeListener("data",Pe),this.removeListener("end",tr),e._readyState=_.CLOSING;let n;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(n=e._socket.read())!==null&&e._receiver.write(n),e._receiver.end(),this[b]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Kn),e._receiver.on("finish",Kn))}function Pe(e){this[b]._receiver.write(e)||this.pause()}function tr(){let e=this[b];e._readyState=_.CLOSING,e._receiver.end(),this.end()}function or(){let e=this[b];this.removeListener("error",or),this.on("error",Xn),e&&(e._readyState=_.CLOSING,this.destroy())}});var cr=E((ti,dr)=>{"use strict";var ri=Re(),{Duplex:so}=x("stream");function ir(e){e.emit("close")}function io(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ar(e){this.removeListener("error",ar),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function ao(e,n){let r=!0,t=new so({...n,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&t._readableState.objectMode?s.toString():s;t.push(a)||e.pause()}),e.once("error",function(s){t.destroyed||(r=!1,t.destroy(s))}),e.once("close",function(){t.destroyed||t.push(null)}),t._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(ir,t);return}let i=!1;e.once("error",function(d){i=!0,s(d)}),e.once("close",function(){i||s(o),process.nextTick(ir,t)}),r&&e.terminate()},t._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){t._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),t._readableState.endEmitted&&t.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},t._read=function(){e.isPaused&&e.resume()},t._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){t._write(o,s,i)});return}e.send(o,i)},t.on("end",io),t.on("error",ar),t}dr.exports=ao});var ur=E((oi,lr)=>{"use strict";var{tokenChars:co}=Q();function lo(e){let n=new Set,r=-1,t=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(t===-1&&co[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))t===-1&&r!==-1&&(t=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);t===-1&&(t=o);let a=e.slice(r,t);if(n.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);n.add(a),r=t=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||t!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(n.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return n.add(s),n}lr.exports={parse:lo}});var _r=E((ii,mr)=>{"use strict";var uo=x("events"),Ae=x("http"),{Duplex:si}=x("stream"),{createHash:fo}=x("crypto"),fr=Xe(),G=de(),po=ur(),ho=Re(),{GUID:go,kWebSocket:yo}=I(),mo=/^[+/0-9A-Za-z]{22}==$/,pr=0,hr=1,yr=2,rn=class extends uo{constructor(n,r){if(super(),n={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ho,...n},n.port==null&&!n.server&&!n.noServer||n.port!=null&&(n.server||n.noServer)||n.server&&n.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(n.port!=null?(this._server=Ae.createServer((t,o)=>{let s=Ae.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(n.port,n.host,n.backlog,r)):n.server&&(this._server=n.server),this._server){let t=this.emit.bind(this,"connection");this._removeListeners=_o(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,t)}})}n.perMessageDeflate===!0&&(n.perMessageDeflate={}),n.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=n,this._state=pr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(n){if(this._state===yr){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(fe,this);return}if(n&&this.once("close",n),this._state!==hr)if(this._state=hr,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(fe,this):process.nextTick(fe,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{fe(this)})}}shouldHandle(n){if(this.options.path){let r=n.url.indexOf("?");if((r!==-1?n.url.slice(0,r):n.url)!==this.options.path)return!1}return!0}handleUpgrade(n,r,t,o){r.on("error",gr);let s=n.headers["sec-websocket-key"],i=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){z(this,n,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){z(this,n,r,400,"Invalid Upgrade header");return}if(s===void 0||!mo.test(s)){z(this,n,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){z(this,n,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){pe(r,400);return}let d=n.headers["sec-websocket-protocol"],c=new Set;if(d!==void 0)try{c=po.parse(d)}catch{z(this,n,r,400,"Invalid Sec-WebSocket-Protocol header");return}let f=n.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let g=new G(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let u=fr.parse(f);u[G.extensionName]&&(g.accept(u[G.extensionName]),p[G.extensionName]=g)}catch{z(this,n,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:n.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(n.socket.authorized||n.socket.encrypted),req:n};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(u,h,l,m)=>{if(!u)return pe(r,h||401,l,m);this.completeUpgrade(p,s,c,n,r,t,o)});return}if(!this.options.verifyClient(g))return pe(r,401)}this.completeUpgrade(p,s,c,n,r,t,o)}completeUpgrade(n,r,t,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[yo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>pr)return pe(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fo("sha1").update(r+go).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(t.size){let p=this.options.handleProtocols?this.options.handleProtocols(t,o):t.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(n[G.extensionName]){let p=n[G.extensionName].params,g=fr.format({[G.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),f._extensions=n}this.emit("headers",c,o),s.write(c.concat(`\r
3
+ var Hr=Object.create;var hn=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var Zr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var x=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Qr=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Zr(n))!Yr.call(e,o)&&o!==r&&hn(e,o,{get:()=>n[o],enumerable:!(t=Kr(n,o))||t.enumerable});return e};var se=(e,n,r)=>(r=e!=null?Hr(Xr(e)):{},Qr(n||!e||!e.__esModule?hn(r,"default",{value:e,enumerable:!0}):r,e));var I=E((Gs,mn)=>{"use strict";var gn=["nodebuffer","arraybuffer","fragments"],yn=typeof Blob<"u";yn&&gn.push("blob");mn.exports={BINARY_TYPES:gn,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yn,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ie=E((Bs,xe)=>{"use strict";var{EMPTY_BUFFER:et}=I(),Le=Buffer[Symbol.species];function nt(e,n){if(e.length===0)return et;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(n),t=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,t),t+=s.length}return t<n?new Le(r.buffer,r.byteOffset,t):r}function _n(e,n,r,t,o){for(let s=0;s<o;s++)r[t+s]=e[s]^n[s&3]}function xn(e,n){for(let r=0;r<e.length;r++)e[r]^=n[r&3]}function rt(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Je(e){if(Je.readOnly=!0,Buffer.isBuffer(e))return e;let n;return e instanceof ArrayBuffer?n=new Le(e):ArrayBuffer.isView(e)?n=new Le(e.buffer,e.byteOffset,e.byteLength):(n=Buffer.from(e),Je.readOnly=!1),n}xe.exports={concat:nt,mask:_n,toArrayBuffer:rt,toBuffer:Je,unmask:xn};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=x("bufferutil");xe.exports.mask=function(n,r,t,o,s){s<48?_n(n,r,t,o,s):e.mask(n,r,t,o,s)},xe.exports.unmask=function(n,r){n.length<32?xn(n,r):e.unmask(n,r)}}catch{}});var wn=E((zs,Sn)=>{"use strict";var bn=Symbol("kDone"),$e=Symbol("kRun"),Ue=class{constructor(n){this[bn]=()=>{this.pending--,this[$e]()},this.concurrency=n||1/0,this.jobs=[],this.pending=0}add(n){this.jobs.push(n),this[$e]()}[$e](){if(this.pending!==this.concurrency&&this.jobs.length){let n=this.jobs.shift();this.pending++,n(this[bn])}}};Sn.exports=Ue});var de=E((qs,Cn)=>{"use strict";var ae=x("zlib"),vn=ie(),tt=wn(),{kStatusCode:En}=I(),ot=Buffer[Symbol.species],st=Buffer.from([0,0,255,255]),Se=Symbol("permessage-deflate"),M=Symbol("total-length"),X=Symbol("callback"),$=Symbol("buffers"),Y=Symbol("error"),be,De=class{constructor(n,r,t){if(this._maxPayload=t|0,this._options=n||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!be){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;be=new tt(o)}}static get extensionName(){return"permessage-deflate"}offer(){let n={};return this._options.serverNoContextTakeover&&(n.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(n.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(n.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?n.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(n.client_max_window_bits=!0),n}accept(n){return n=this.normalizeParams(n),this.params=this._isServer?this.acceptAsServer(n):this.acceptAsClient(n),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let n=this._deflate[X];this._deflate.close(),this._deflate=null,n&&n(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(n){let r=this._options,t=n.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!t)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(t.server_no_context_takeover=!0),r.clientNoContextTakeover&&(t.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(t.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?t.client_max_window_bits=r.clientMaxWindowBits:(t.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete t.client_max_window_bits,t}acceptAsClient(n){let r=n[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(n){return n.forEach(r=>{Object.keys(r).forEach(t=>{let o=r[t];if(o.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(o=o[0],t==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else if(t==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${t}": ${o}`);o=s}else if(t==="client_no_context_takeover"||t==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${t}": ${o}`)}else throw new Error(`Unknown parameter "${t}"`);r[t]=o})}),n}decompress(n,r,t){be.add(o=>{this._decompress(n,r,(s,i)=>{o(),t(s,i)})})}compress(n,r,t){be.add(o=>{this._compress(n,r,(s,i)=>{o(),t(s,i)})})}_decompress(n,r,t){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ae.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ae.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Se]=this,this._inflate[M]=0,this._inflate[$]=[],this._inflate.on("error",at),this._inflate.on("data",kn)}this._inflate[X]=t,this._inflate.write(n),r&&this._inflate.write(st),this._inflate.flush(()=>{let s=this._inflate[Y];if(s){this._inflate.close(),this._inflate=null,t(s);return}let i=vn.concat(this._inflate[$],this._inflate[M]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[M]=0,this._inflate[$]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),t(null,i)})}_compress(n,r,t){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?ae.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ae.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[M]=0,this._deflate[$]=[],this._deflate.on("data",it)}this._deflate[X]=t,this._deflate.write(n),this._deflate.flush(ae.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=vn.concat(this._deflate[$],this._deflate[M]);r&&(s=new ot(s.buffer,s.byteOffset,s.length-4)),this._deflate[X]=null,this._deflate[M]=0,this._deflate[$]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),t(null,s)})}};Cn.exports=De;function it(e){this[$].push(e),this[M]+=e.length}function kn(e){if(this[M]+=e.length,this[Se]._maxPayload<1||this[M]<=this[Se]._maxPayload){this[$].push(e);return}this[Y]=new RangeError("Max payload size exceeded"),this[Y].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Y][En]=1009,this.removeListener("data",kn),this.reset()}function at(e){if(this[Se]._inflate=null,this[Y]){this[X](this[Y]);return}e[En]=1007,this[X](e)}});var Q=E((Ws,we)=>{"use strict";var{isUtf8:On}=x("buffer"),{hasBlob:dt}=I(),ct=[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 lt(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Ve(e){let n=e.length,r=0;for(;r<n;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===n||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=n||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function ut(e){return dt&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}we.exports={isBlob:ut,isValidStatusCode:lt,isValidUTF8:Ve,tokenChars:ct};if(On)we.exports.isValidUTF8=function(e){return e.length<24?Ve(e):On(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=x("utf-8-validate");we.exports.isValidUTF8=function(n){return n.length<32?Ve(n):e(n)}}catch{}});var qe=E((Hs,Nn)=>{"use strict";var{Writable:ft}=x("stream"),Pn=de(),{BINARY_TYPES:pt,EMPTY_BUFFER:Tn,kStatusCode:ht,kWebSocket:gt}=I(),{concat:Fe,toArrayBuffer:yt,unmask:mt}=ie(),{isValidStatusCode:_t,isValidUTF8:Rn}=Q(),ve=Buffer[Symbol.species],C=0,An=1,In=2,Mn=3,Ge=4,Be=5,Ee=6,ze=class extends ft{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||pt[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[gt]=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=C}_write(n,r,t){if(this._opcode===8&&this._state==C)return t();this._bufferedBytes+=n.length,this._buffers.push(n),this.startLoop(t)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new ve(t.buffer,t.byteOffset+n,t.length-n),new ve(t.buffer,t.byteOffset,n)}let r=Buffer.allocUnsafe(n);do{let t=this._buffers[0],o=r.length-n;n>=t.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(t.buffer,t.byteOffset,n),o),this._buffers[0]=new ve(t.buffer,t.byteOffset+n,t.length-n)),n-=t.length}while(n>0);return r}startLoop(n){this._loop=!0;do switch(this._state){case C:this.getInfo(n);break;case An:this.getPayloadLength16(n);break;case In:this.getPayloadLength64(n);break;case Mn:this.getMask();break;case Ge:this.getData(n);break;case Be:case Ee:this._loop=!1;return}while(this._loop);this._errored||n()}getInfo(n){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");n(o);return}let t=(r[0]&64)===64;if(t&&!this._extensions[Pn.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._compressed=t}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");n(o);return}if(t){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");n(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");n(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");n(o);return}this._payloadLength===126?this._state=An:this._payloadLength===127?this._state=In:this.haveLength(n)}getPayloadLength16(n){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(n)}getPayloadLength64(n){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),t=r.readUInt32BE(0);if(t>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");n(o);return}this._payloadLength=t*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(n)}haveLength(n){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");n(r);return}this._masked?this._state=Mn:this._state=Ge}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ge}getData(n){let r=Tn;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&&mt(r,this._mask)}if(this._opcode>7){this.controlMessage(r,n);return}if(this._compressed){this._state=Be,this.decompress(r,n);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(n)}decompress(n,r){this._extensions[Pn.extensionName].decompress(n,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===C&&this.startLoop(r)})}dataMessage(n){if(!this._fin){this._state=C;return}let r=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Fe(t,r):this._binaryType==="arraybuffer"?o=yt(Fe(t,r)):this._binaryType==="blob"?o=new Blob(t):o=t,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit("message",o,!0),this._state=C,this.startLoop(n)}))}else{let o=Fe(t,r);if(!this._skipUTF8Validation&&!Rn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._state===Be||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit("message",o,!1),this._state=C,this.startLoop(n)}))}}controlMessage(n,r){if(this._opcode===8){if(n.length===0)this._loop=!1,this.emit("conclude",1005,Tn),this.end();else{let t=n.readUInt16BE(0);if(!_t(t)){let s=this.createError(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new ve(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!Rn(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",t,o),this.end()}this._state=C;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",n),this._state=C):(this._state=Ee,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",n),this._state=C,this.startLoop(r)}))}createError(n,r,t,o,s){this._loop=!1,this._errored=!0;let i=new n(t?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[ht]=o,i}};Nn.exports=ze});var Ke=E((Zs,Jn)=>{"use strict";var{Duplex:Ks}=x("stream"),{randomFillSync:xt}=x("crypto"),jn=de(),{EMPTY_BUFFER:bt,kWebSocket:St,NOOP:wt}=I(),{isBlob:ee,isValidStatusCode:vt}=Q(),{mask:Ln,toBuffer:V}=ie(),O=Symbol("kByteLength"),Et=Buffer.alloc(4),ke=8*1024,F,ne=ke,P=0,kt=1,Ct=2,We=class e{constructor(n,r,t){this._extensions=r||{},t&&(this._generateMask=t,this._maskBuffer=Buffer.alloc(4)),this._socket=n,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=P,this.onerror=wt,this[St]=void 0}static frame(n,r){let t,o=!1,s=2,i=!1;r.mask&&(t=r.maskBuffer||Et,r.generateMask?r.generateMask(t):(ne===ke&&(F===void 0&&(F=Buffer.alloc(ke)),xt(F,0,ke),ne=0),t[0]=F[ne++],t[1]=F[ne++],t[2]=F[ne++],t[3]=F[ne++]),i=(t[0]|t[1]|t[2]|t[3])===0,s=6);let a;typeof n=="string"?(!r.mask||i)&&r[O]!==void 0?a=r[O]:(n=Buffer.from(n),a=n.length):(a=n.length,o=r.mask&&r.readOnly&&!i);let d=a;a>=65536?(s+=8,d=127):a>125&&(s+=2,d=126);let c=Buffer.allocUnsafe(o?a+s:s);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=d,d===126?c.writeUInt16BE(a,2):d===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[s-4]=t[0],c[s-3]=t[1],c[s-2]=t[2],c[s-1]=t[3],i?[c,n]:o?(Ln(n,t,c,s,a),[c]):(Ln(n,t,n,0,a),[c,n])):[c,n]}close(n,r,t,o){let s;if(n===void 0)s=bt;else{if(typeof n!="number"||!vt(n))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(n,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(n,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[O]:s.length,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==P?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(e.frame(s,i),o)}ping(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):ee(n)?(o=n.size,s=!1):(n=V(n),o=n.length,s=V.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[O]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ee(n)?this._state!==P?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==P?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}pong(n,r,t){let o,s;if(typeof n=="string"?(o=Buffer.byteLength(n),s=!1):ee(n)?(o=n.size,s=!1):(n=V(n),o=n.length,s=V.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[O]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ee(n)?this._state!==P?this.enqueue([this.getBlobData,n,!1,i,t]):this.getBlobData(n,!1,i,t):this._state!==P?this.enqueue([this.dispatch,n,!1,i,t]):this.sendFrame(e.frame(n,i),t)}send(n,r,t){let o=this._extensions[jn.extensionName],s=r.binary?2:1,i=r.compress,a,d;typeof n=="string"?(a=Buffer.byteLength(n),d=!1):ee(n)?(a=n.size,d=!1):(n=V(n),a=n.length,d=V.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let c={[O]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};ee(n)?this._state!==P?this.enqueue([this.getBlobData,n,this._compress,c,t]):this.getBlobData(n,this._compress,c,t):this._state!==P?this.enqueue([this.dispatch,n,this._compress,c,t]):this.dispatch(n,this._compress,c,t)}getBlobData(n,r,t,o){this._bufferedBytes+=t[O],this._state=Ct,n.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(He,this,a,o);return}this._bufferedBytes-=t[O];let i=V(s);r?this.dispatch(i,r,t,o):(this._state=P,this.sendFrame(e.frame(i,t),o),this.dequeue())}).catch(s=>{process.nextTick(Ot,this,s,o)})}dispatch(n,r,t,o){if(!r){this.sendFrame(e.frame(n,t),o);return}let s=this._extensions[jn.extensionName];this._bufferedBytes+=t[O],this._state=kt,s.compress(n,t.fin,(i,a)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");He(this,d,o);return}this._bufferedBytes-=t[O],this._state=P,t.readOnly=!1,this.sendFrame(e.frame(a,t),o),this.dequeue()})}dequeue(){for(;this._state===P&&this._queue.length;){let n=this._queue.shift();this._bufferedBytes-=n[3][O],Reflect.apply(n[0],this,n.slice(1))}}enqueue(n){this._bufferedBytes+=n[3][O],this._queue.push(n)}sendFrame(n,r){n.length===2?(this._socket.cork(),this._socket.write(n[0]),this._socket.write(n[1],r),this._socket.uncork()):this._socket.write(n[0],r)}};Jn.exports=We;function He(e,n,r){typeof r=="function"&&r(n);for(let t=0;t<e._queue.length;t++){let o=e._queue[t],s=o[o.length-1];typeof s=="function"&&s(n)}}function Ot(e,n,r){He(e,n,r),e.onerror(n)}});var qn=E((Xs,zn)=>{"use strict";var{kForOnEventAttribute:ce,kListener:Ze}=I(),$n=Symbol("kCode"),Un=Symbol("kData"),Dn=Symbol("kError"),Vn=Symbol("kMessage"),Fn=Symbol("kReason"),re=Symbol("kTarget"),Gn=Symbol("kType"),Bn=Symbol("kWasClean"),N=class{constructor(n){this[re]=null,this[Gn]=n}get target(){return this[re]}get type(){return this[Gn]}};Object.defineProperty(N.prototype,"target",{enumerable:!0});Object.defineProperty(N.prototype,"type",{enumerable:!0});var G=class extends N{constructor(n,r={}){super(n),this[$n]=r.code===void 0?0:r.code,this[Fn]=r.reason===void 0?"":r.reason,this[Bn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$n]}get reason(){return this[Fn]}get wasClean(){return this[Bn]}};Object.defineProperty(G.prototype,"code",{enumerable:!0});Object.defineProperty(G.prototype,"reason",{enumerable:!0});Object.defineProperty(G.prototype,"wasClean",{enumerable:!0});var te=class extends N{constructor(n,r={}){super(n),this[Dn]=r.error===void 0?null:r.error,this[Vn]=r.message===void 0?"":r.message}get error(){return this[Dn]}get message(){return this[Vn]}};Object.defineProperty(te.prototype,"error",{enumerable:!0});Object.defineProperty(te.prototype,"message",{enumerable:!0});var le=class extends N{constructor(n,r={}){super(n),this[Un]=r.data===void 0?null:r.data}get data(){return this[Un]}};Object.defineProperty(le.prototype,"data",{enumerable:!0});var Pt={addEventListener(e,n,r={}){for(let o of this.listeners(e))if(!r[ce]&&o[Ze]===n&&!o[ce])return;let t;if(e==="message")t=function(s,i){let a=new le("message",{data:i?s:s.toString()});a[re]=this,Ce(n,this,a)};else if(e==="close")t=function(s,i){let a=new G("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[re]=this,Ce(n,this,a)};else if(e==="error")t=function(s){let i=new te("error",{error:s,message:s.message});i[re]=this,Ce(n,this,i)};else if(e==="open")t=function(){let s=new N("open");s[re]=this,Ce(n,this,s)};else return;t[ce]=!!r[ce],t[Ze]=n,r.once?this.once(e,t):this.on(e,t)},removeEventListener(e,n){for(let r of this.listeners(e))if(r[Ze]===n&&!r[ce]){this.removeListener(e,r);break}}};zn.exports={CloseEvent:G,ErrorEvent:te,Event:N,EventTarget:Pt,MessageEvent:le};function Ce(e,n,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(n,r)}});var Xe=E((Ys,Wn)=>{"use strict";var{tokenChars:ue}=Q();function T(e,n,r){e[n]===void 0?e[n]=[r]:e[n].push(r)}function Tt(e){let n=Object.create(null),r=Object.create(null),t=!1,o=!1,s=!1,i,a,d=-1,c=-1,f=-1,p=0;for(;p<e.length;p++)if(c=e.charCodeAt(p),i===void 0)if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(p!==0&&(c===32||c===9))f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(d,f);c===44?(T(n,u,r),r=Object.create(null)):i=u,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(c===32||c===9)f===-1&&d!==-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),T(r,e.slice(d,f),!0),c===44&&(T(n,i,r),r=Object.create(null),i=void 0),d=f=-1}else if(c===61&&d!==-1&&f===-1)a=e.slice(d,p),d=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(ue[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:t||(t=!0),o=!1}else if(s)if(ue[c]===1)d===-1&&(d=p);else if(c===34&&d!==-1)s=!1,f=p;else if(c===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&ue[c]===1)d===-1&&(d=p);else if(d!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let u=e.slice(d,f);t&&(u=u.replace(/\\/g,""),t=!1),T(r,a,u),c===44&&(T(n,i,r),r=Object.create(null),i=void 0),a=void 0,d=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let g=e.slice(d,f);return i===void 0?T(n,g,r):(a===void 0?T(r,g,!0):t?T(r,a,g.replace(/\\/g,"")):T(r,a,g),T(n,i,r)),n}function Rt(e){return Object.keys(e).map(n=>{let r=e[n];return Array.isArray(r)||(r=[r]),r.map(t=>[n].concat(Object.keys(t).map(o=>{let s=t[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Wn.exports={format:Rt,parse:Tt}});var Re=E((ni,sr)=>{"use strict";var At=x("events"),It=x("https"),Mt=x("http"),Zn=x("net"),Nt=x("tls"),{randomBytes:jt,createHash:Lt}=x("crypto"),{Duplex:Qs,Readable:ei}=x("stream"),{URL:Ye}=x("url"),U=de(),Jt=qe(),$t=Ke(),{isBlob:Ut}=Q(),{BINARY_TYPES:Hn,EMPTY_BUFFER:Oe,GUID:Dt,kForOnEventAttribute:Qe,kListener:Vt,kStatusCode:Ft,kWebSocket:b,NOOP:Xn}=I(),{EventTarget:{addEventListener:Gt,removeEventListener:Bt}}=qn(),{format:zt,parse:qt}=Xe(),{toBuffer:Wt}=ie(),Ht=30*1e3,Yn=Symbol("kAborted"),en=[8,13],j=["CONNECTING","OPEN","CLOSING","CLOSED"],Kt=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_=class e extends At{constructor(n,r,t){super(),this._binaryType=Hn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Oe,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,n!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(t=r,r=[]):r=[r]),Qn(this,n,r,t)):(this._autoPong=t.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){Hn.includes(n)&&(this._binaryType=n,this._receiver&&(this._receiver._binaryType=n))}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(n,r,t){let o=new Jt({allowSynchronousEvents:t.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:t.maxPayload,skipUTF8Validation:t.skipUTF8Validation}),s=new $t(n,this._extensions,t.generateMask);this._receiver=o,this._sender=s,this._socket=n,o[b]=this,s[b]=this,n[b]=this,o.on("conclude",Yt),o.on("drain",Qt),o.on("error",eo),o.on("message",no),o.on("ping",ro),o.on("pong",to),s.onerror=oo,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),r.length>0&&n.unshift(r),n.on("close",rr),n.on("data",Te),n.on("end",tr),n.on("error",or),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[U.extensionName]&&this._extensions[U.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(n,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(n,r,!this._isServer,t=>{t||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),nr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.ping(n||Oe,r,t)}pong(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(t=n,n=r=void 0):typeof r=="function"&&(t=r,r=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}r===void 0&&(r=!this._isServer),this._sender.pong(n||Oe,r,t)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(n,r,t){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(t=r,r={}),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){nn(this,n,t);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[U.extensionName]||(o.compress=!1),this._sender.send(n||Oe,o,t)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){k(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:j.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:!0,value:j.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:!0,value:j.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:!0,value:j.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:!0,value:j.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:!0,value:j.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:j.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:!0,value:j.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(_.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(_.prototype,`on${e}`,{enumerable:!0,get(){for(let n of this.listeners(e))if(n[Qe])return n[Vt];return null},set(n){for(let r of this.listeners(e))if(r[Qe]){this.removeListener(e,r);break}typeof n=="function"&&this.addEventListener(e,n,{[Qe]:!0})}})});_.prototype.addEventListener=Gt;_.prototype.removeEventListener=Bt;sr.exports=_;function Qn(e,n,r,t){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:en[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...t,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!en.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${en.join(", ")})`);let s;if(n instanceof Ye)s=n;else try{s=new Ye(n)}catch{throw new SyntaxError(`Invalid URL: ${n}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!a?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let l=new SyntaxError(d);if(e._redirects===0)throw l;Pe(e,l);return}let c=i?443:80,f=jt(16).toString("base64"),p=i?It.request:Mt.request,g=new Set,u;if(o.createConnection=o.createConnection||(i?Xt:Zt),o.defaultPort=o.defaultPort||c,o.port=s.port||c,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(u=new U(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=zt({[U.extensionName]:u.offer()})),r.length){for(let l of r){if(typeof l!="string"||!Kt.test(l)||g.has(l))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(l)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let l=o.path.split(":");o.socketPath=l[0],o.path=l[1]}let h;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let l=t&&t.headers;if(t={...t,headers:{}},l)for(let[m,w]of Object.entries(l))t.headers[m.toLowerCase()]=w}else if(e.listenerCount("redirect")===0){let l=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!l||e._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,l||delete o.headers.host,o.auth=void 0)}o.auth&&!t.headers.authorization&&(t.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),h=e._req=p(o),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=p(o);o.timeout&&h.on("timeout",()=>{k(e,h,"Opening handshake has timed out")}),h.on("error",l=>{h===null||h[Yn]||(h=e._req=null,Pe(e,l))}),h.on("response",l=>{let m=l.headers.location,w=l.statusCode;if(m&&o.followRedirects&&w>=300&&w<400){if(++e._redirects>o.maxRedirects){k(e,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new Ye(m,n)}catch{let R=new SyntaxError(`Invalid URL: ${m}`);Pe(e,R);return}Qn(e,v,r,t)}else e.emit("unexpected-response",h,l)||k(e,h,`Unexpected server response: ${l.statusCode}`)}),h.on("upgrade",(l,m,w)=>{if(e.emit("upgrade",l),e.readyState!==_.CONNECTING)return;h=e._req=null;let v=l.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){k(e,m,"Invalid Upgrade header");return}let _e=Lt("sha1").update(f+Dt).digest("base64");if(l.headers["sec-websocket-accept"]!==_e){k(e,m,"Invalid Sec-WebSocket-Accept header");return}let R=l.headers["sec-websocket-protocol"],J;if(R!==void 0?g.size?g.has(R)||(J="Server sent an invalid subprotocol"):J="Server sent a subprotocol but none was requested":g.size&&(J="Server sent no subprotocol"),J){k(e,m,J);return}R&&(e._protocol=R);let Z=l.headers["sec-websocket-extensions"];if(Z!==void 0){if(!u){k(e,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let y;try{y=qt(Z)}catch{k(e,m,"Invalid Sec-WebSocket-Extensions header");return}let S=Object.keys(y);if(S.length!==1||S[0]!==U.extensionName){k(e,m,"Server indicated an extension that was not requested");return}try{u.accept(y[U.extensionName])}catch{k(e,m,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[U.extensionName]=u}e.setSocket(m,w,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(h,e):h.end()}function Pe(e,n){e._readyState=_.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function Zt(e){return e.path=e.socketPath,Zn.connect(e)}function Xt(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Zn.isIP(e.host)?"":e.host),Nt.connect(e)}function k(e,n,r){e._readyState=_.CLOSING;let t=new Error(r);Error.captureStackTrace(t,k),n.setHeader?(n[Yn]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(Pe,e,t)):(n.destroy(t),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function nn(e,n,r){if(n){let t=Ut(n)?n.size:Wt(n).length;e._socket?e._sender._bufferedBytes+=t:e._bufferedAmount+=t}if(r){let t=new Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(r,t)}}function Yt(e,n){let r=this[b];r._closeFrameReceived=!0,r._closeMessage=n,r._closeCode=e,r._socket[b]!==void 0&&(r._socket.removeListener("data",Te),process.nextTick(er,r._socket),e===1005?r.close():r.close(e,n))}function Qt(){let e=this[b];e.isPaused||e._socket.resume()}function eo(e){let n=this[b];n._socket[b]!==void 0&&(n._socket.removeListener("data",Te),process.nextTick(er,n._socket),n.close(e[Ft])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function Kn(){this[b].emitClose()}function no(e,n){this[b].emit("message",e,n)}function ro(e){let n=this[b];n._autoPong&&n.pong(e,!this._isServer,Xn),n.emit("ping",e)}function to(e){this[b].emit("pong",e)}function er(e){e.resume()}function oo(e){let n=this[b];n.readyState!==_.CLOSED&&(n.readyState===_.OPEN&&(n._readyState=_.CLOSING,nr(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function nr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Ht)}function rr(){let e=this[b];this.removeListener("close",rr),this.removeListener("data",Te),this.removeListener("end",tr),e._readyState=_.CLOSING;let n;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(n=e._socket.read())!==null&&e._receiver.write(n),e._receiver.end(),this[b]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Kn),e._receiver.on("finish",Kn))}function Te(e){this[b]._receiver.write(e)||this.pause()}function tr(){let e=this[b];e._readyState=_.CLOSING,e._receiver.end(),this.end()}function or(){let e=this[b];this.removeListener("error",or),this.on("error",Xn),e&&(e._readyState=_.CLOSING,this.destroy())}});var cr=E((ti,dr)=>{"use strict";var ri=Re(),{Duplex:so}=x("stream");function ir(e){e.emit("close")}function io(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ar(e){this.removeListener("error",ar),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function ao(e,n){let r=!0,t=new so({...n,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&t._readableState.objectMode?s.toString():s;t.push(a)||e.pause()}),e.once("error",function(s){t.destroyed||(r=!1,t.destroy(s))}),e.once("close",function(){t.destroyed||t.push(null)}),t._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(ir,t);return}let i=!1;e.once("error",function(d){i=!0,s(d)}),e.once("close",function(){i||s(o),process.nextTick(ir,t)}),r&&e.terminate()},t._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){t._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),t._readableState.endEmitted&&t.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},t._read=function(){e.isPaused&&e.resume()},t._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){t._write(o,s,i)});return}e.send(o,i)},t.on("end",io),t.on("error",ar),t}dr.exports=ao});var ur=E((oi,lr)=>{"use strict";var{tokenChars:co}=Q();function lo(e){let n=new Set,r=-1,t=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(t===-1&&co[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))t===-1&&r!==-1&&(t=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);t===-1&&(t=o);let a=e.slice(r,t);if(n.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);n.add(a),r=t=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||t!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(n.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return n.add(s),n}lr.exports={parse:lo}});var _r=E((ii,mr)=>{"use strict";var uo=x("events"),Ae=x("http"),{Duplex:si}=x("stream"),{createHash:fo}=x("crypto"),fr=Xe(),B=de(),po=ur(),ho=Re(),{GUID:go,kWebSocket:yo}=I(),mo=/^[+/0-9A-Za-z]{22}==$/,pr=0,hr=1,yr=2,rn=class extends uo{constructor(n,r){if(super(),n={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ho,...n},n.port==null&&!n.server&&!n.noServer||n.port!=null&&(n.server||n.noServer)||n.server&&n.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(n.port!=null?(this._server=Ae.createServer((t,o)=>{let s=Ae.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(n.port,n.host,n.backlog,r)):n.server&&(this._server=n.server),this._server){let t=this.emit.bind(this,"connection");this._removeListeners=_o(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,t)}})}n.perMessageDeflate===!0&&(n.perMessageDeflate={}),n.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=n,this._state=pr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(n){if(this._state===yr){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(fe,this);return}if(n&&this.once("close",n),this._state!==hr)if(this._state=hr,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(fe,this):process.nextTick(fe,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{fe(this)})}}shouldHandle(n){if(this.options.path){let r=n.url.indexOf("?");if((r!==-1?n.url.slice(0,r):n.url)!==this.options.path)return!1}return!0}handleUpgrade(n,r,t,o){r.on("error",gr);let s=n.headers["sec-websocket-key"],i=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){z(this,n,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){z(this,n,r,400,"Invalid Upgrade header");return}if(s===void 0||!mo.test(s)){z(this,n,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){z(this,n,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){pe(r,400);return}let d=n.headers["sec-websocket-protocol"],c=new Set;if(d!==void 0)try{c=po.parse(d)}catch{z(this,n,r,400,"Invalid Sec-WebSocket-Protocol header");return}let f=n.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let g=new B(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let u=fr.parse(f);u[B.extensionName]&&(g.accept(u[B.extensionName]),p[B.extensionName]=g)}catch{z(this,n,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:n.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(n.socket.authorized||n.socket.encrypted),req:n};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(u,h,l,m)=>{if(!u)return pe(r,h||401,l,m);this.completeUpgrade(p,s,c,n,r,t,o)});return}if(!this.options.verifyClient(g))return pe(r,401)}this.completeUpgrade(p,s,c,n,r,t,o)}completeUpgrade(n,r,t,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[yo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>pr)return pe(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fo("sha1").update(r+go).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(t.size){let p=this.options.handleProtocols?this.options.handleProtocols(t,o):t.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(n[B.extensionName]){let p=n[B.extensionName].params,g=fr.format({[B.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),f._extensions=n}this.emit("headers",c,o),s.write(c.concat(`\r
4
4
  `).join(`\r
5
5
  `)),s.removeListener("error",gr),f.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(fe,this)})),a(f,o)}};mr.exports=rn;function _o(e,n){for(let r of Object.keys(n))e.on(r,n[r]);return function(){for(let t of Object.keys(n))e.removeListener(t,n[t])}}function fe(e){e._state=yr,e.emit("close")}function gr(){this.destroy()}function pe(e,n,r,t){r=r||Ae.STATUS_CODES[n],t={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...t},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${n} ${Ae.STATUS_CODES[n]}\r
6
6
  `+Object.keys(t).map(o=>`${o}: ${t[o]}`).join(`\r
7
7
  `)+`\r
8
8
  \r
9
- `+r)}function z(e,n,r,t,o,s){if(e.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,z),e.emit("wsClientError",i,r,n)}else pe(r,t,o,s)}});import{spawn as hs}from"node:child_process";import{rmSync as Vr,writeFileSync as Le,mkdirSync as me,chmodSync as Dr,readFileSync as gs,readdirSync as ys,statSync as ms,unlinkSync as _s}from"node:fs";import{dirname as xs,join as pn}from"node:path";var xo=se(cr(),1),bo=se(qe(),1),So=se(Ke(),1),tn=se(Re(),1),wo=se(_r(),1);function j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{appendFileSync as vo,openSync as li}from"node:fs";import{homedir as Eo}from"node:os";import{dirname as ko,join as Co}from"node:path";import{mkdirSync as Oo}from"node:fs";var q="<SENSITIVE_DATA>",xr=new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"]),To=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function oe(e,n,r={}){let t=r.logFile??Po();try{Oo(ko(t),{recursive:!0}),vo(t,`${JSON.stringify({ts:new Date().toISOString(),event:e,...r.sessionId===void 0?{}:{sessionId:r.sessionId},...Ro(n)})}
10
- `,"utf8")}catch{return}}function Po(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?Co(Eo(),".linzumi","logs","command-events.jsonl"):e}function Ro(e){return br(e)}function on(e,n){return Mo(n)?q:typeof e=="string"?Sr(e):Array.isArray(e)?n==="args"?Ao(e):e.map(r=>on(r,void 0)):e!==null&&typeof e=="object"?br(e):e}function br(e){let n=typeof e.name=="string"?e.name.toLowerCase():void 0,r=n==="authorization"||n==="cookie"||n==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="runner_console").map(([t,o])=>[t,r&&t==="value"?q:on(o,t)]))}function Ao(e){let n=!1;return e.map(r=>{if(typeof r!="string")return n=!1,on(r,void 0);if(n)return n=!1,q;let[t,o]=Io(r);return To.has(t)?o===void 0?(n=!0,r):`${t}=${q}`:Sr(r)})}function Io(e){let n=e.indexOf("=");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Mo(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function Sr(e){return No(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,q)}function No(e){let n;try{n=new URL(e)}catch{return Lo(e)}for(let r of[...n.searchParams.keys()])xr.has(r.toLowerCase())&&n.searchParams.set(r,q);return n.toString()}function Lo(e){let n=e.indexOf("?"),r=e.indexOf("#");if(n===-1||r!==-1&&r<n)return e;let t=e.slice(0,n),o=r===-1?e.slice(n+1):e.slice(n+1,r),s=r===-1?"":e.slice(r),i=new URLSearchParams(o),a=!1;for(let d of[...i.keys()])xr.has(d.toLowerCase())&&(i.set(d,q),a=!0);switch(a){case!0:return`${t}?${i.toString()}${s}`;case!1:return e}}import{mkdirSync as jo,appendFileSync as $o}from"node:fs";import{dirname as Jo}from"node:path";function W(e){return e!==void 0&&j(e)?e:void 0}function wr(e){return Array.isArray(e)?e:void 0}function H(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function vr(e){return JSON.stringify(e)}var he,Uo=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function ye(e){let n=Do();if(n===void 0)return;let r=Vo(n),t=Fo(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:r.nextOrdinal,offsetMs:Math.max(0,Date.now()-r.startedAtMs),...t.rawText===void 0?{}:{rawText:t.rawText},...t.rawValue===void 0?{}:{rawValue:t.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:ge(e.captureMetadata)},...t.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...t.transforms]}};r.nextOrdinal+=1,$o(n,`${vr(o)}
11
- `,"utf8")}function Do(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function Vo(e){return he!==void 0&&he.path===e||(jo(Jo(e),{recursive:!0}),he={path:e,startedAtMs:Date.now(),nextOrdinal:0}),he}function Fo(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let n=[],r=e.rawValue===void 0?void 0:ge(e.rawValue,"$.rawValue",n);return{rawText:Bo(e.rawText,n),rawValue:r,transforms:n}}function Bo(e,n){if(e!==void 0)try{let r=JSON.parse(e);return JSON.stringify(ge(r,"$.rawText",n))}catch{return e}}function ge(e,n="$",r=[]){if(Array.isArray(e))return e.map((o,s)=>ge(o,`${n}[${s}]`,r));if(!j(e))return e;let t=Object.entries(e).map(([o,s])=>{let i=`${n}.${o}`;return Uo.test(o)?(r.push({type:"credential_redaction",path:i}),[o,"[REDACTED]"]):[o,s===void 0?void 0:ge(s,i,r)]});return Object.fromEntries(t)}function Er(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},ELECTRON_RUN_AS_NODE:"1"}}}function sn(e){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${Go(e.args)}`,...Object.entries(e.env).flatMap(([n,r])=>["-c",`mcp_servers.${e.name}.env.${n}=${JSON.stringify(r)}`])]}function Go(e){return`[${e.map(n=>JSON.stringify(n)).join(", ")}]`}var Oi=["# Managed by Linzumi - do not edit by hand.","# This isolated CODEX_HOME keeps Linzumi-spawned codex processes off the","# user's ~/.codex config and the macOS Keychain. See codexHome.ts.",'mcp_oauth_credentials_store = "file"','cli_auth_credentials_store = "file"',""].join(`
12
- `);function kr(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}var zo=(()=>{let e=process.env.LINZUMI_CODEX_WS_KEEPALIVE_MS;if(e===void 0)return 2e4;let n=Number.parseInt(e,10);return Number.isInteger(n)&&n>0?n:2e4})();function qo(e){let n=e;if(typeof n.ping=="function"&&n.readyState===WebSocket.OPEN)try{n.ping()}catch{}}function Tr(e,n={}){return["app-server",...Ho(n),"--listen",e]}var Wo=["-c","features.apps=false"];function Ho(e){return[...Wo,...kr(),...e.model===void 0?[]:["-c",`model=${JSON.stringify(e.model)}`],...e.reasoningEffort===void 0?[]:["-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`],...e.fast===!0?["-c",`service_tier=${JSON.stringify("fast")}`]:[],...(e.mcpServers??[]).flatMap(n=>sn(n)),...e.modelProvider===void 0?[]:Ko(e.modelProvider)]}function Ko(e){return["-c",`model_providers.${e.id}.name=${JSON.stringify(e.name)}`,"-c",`model_providers.${e.id}.base_url=${JSON.stringify(e.baseUrl)}`,"-c",`model_providers.${e.id}.env_key=${JSON.stringify(e.envKey)}`,"-c",`model_providers.${e.id}.wire_api=${JSON.stringify(e.wireApi)}`,...Object.entries(e.httpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.http_headers.${n}=${JSON.stringify(r)}`]),...Object.entries(e.envHttpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.env_http_headers.${n}=${JSON.stringify(r)}`]),"-c",`model_provider=${JSON.stringify(e.id)}`]}async function Pr(e,n=r=>new tn.default(r)){let r=await Yo(e,n),t=new Map,o=new Set,s=new Set,i=[],a=new Set,d={nextId:1,closeError:void 0},c=u=>{let h=new Error(u);t.forEach(l=>l.reject(h)),t.clear()},f=setInterval(()=>qo(r),zo);f.unref?.();let p=u=>{if(clearInterval(f),c(u),d.closeError===void 0){d.closeError=new Error(u);for(let h of a)Or(h,d.closeError);a.clear()}};return r.addEventListener("close",()=>p("codex app-server websocket closed")),r.addEventListener("error",()=>p("codex app-server websocket closed")),r.addEventListener("message",u=>{let h=String(u.data),l=Xo(h);if(l!==void 0){if(ye({provider:"codex-app-server",captureKind:Zo(l),rawText:h,rawValue:{message:l}}),"id"in l&&("result"in l||"error"in l)){let m=t.get(l.id);m!==void 0&&(t.delete(l.id),m.resolve(l));return}if("id"in l&&typeof l.method=="string"){es(r,l,s);return}if(!("id"in l)&&typeof l.method=="string"){let m=l;o.size===0?i.push(m):o.forEach(w=>Cr(w,m))}}}),await ns(r,t),{request:(u,h)=>{let l=d.nextId;return d.nextId+=1,Rr(r,t,h===void 0?{jsonrpc:"2.0",id:l,method:u}:{jsonrpc:"2.0",id:l,method:u,params:h})},notify:(u,h)=>{let l=h===void 0?{jsonrpc:"2.0",method:u}:{jsonrpc:"2.0",method:u,params:h};ye({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(l),rawValue:{message:l}}),r.send(JSON.stringify(l))},onNotification:u=>{o.add(u),i.splice(0).forEach(h=>Cr(u,h))},onRequest:u=>{s.add(u)},onClose:u=>{if(d.closeError!==void 0){Or(u,d.closeError);return}a.add(u)},close:()=>{clearInterval(f),r.close()}}}function Zo(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function Xo(e){let n=String(e);try{let r=JSON.parse(n);if(!j(r))throw new Error("codex app-server sent non-object JSON-RPC message");return r}catch(r){oe("codex.app_server_frame_malformed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r),payload:n.slice(0,512),payloadChars:n.length});return}}function Cr(e,n){try{e(n)}catch(r){oe("codex.notification_callback_failed",{purpose:"codex.app_server",method:n.method,message:r instanceof Error?r.message:String(r)})}}function Or(e,n){try{e(n)}catch(r){oe("codex.close_callback_failed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r)})}}async function Yo(e,n,r=2e3){let t=Date.now()+r,o;for(;Date.now()<=t;){let s=n(e);try{return await rs(s),s}catch(i){o=i instanceof Error?i:new Error(String(i)),Qo(s)}}throw o??new Error("websocket open failed")}function Qo(e){try{e.close()}catch{}}async function es(e,n,r){try{if(r.size===0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}));return}for(let t of r){let o=await t(n);if(o!==void 0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,result:o}));return}}e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}))}catch(t){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}))}}async function ns(e,n){let r=await Rr(e,n,{jsonrpc:"2.0",id:"initialize",method:"initialize",params:{clientInfo:{name:"kandan-local-codex-runner",version:"0.0.1"},capabilities:{experimentalApi:!0}}});if("error"in r)throw new Error(`codex initialize failed: ${r.error.message}`);let t={jsonrpc:"2.0",method:"initialized"};ye({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(t),rawValue:{message:t}}),e.send(JSON.stringify(t))}function Rr(e,n,r){return e.readyState!==WebSocket.OPEN?Promise.reject(new Error("codex app-server websocket is not open")):new Promise((t,o)=>{n.set(r.id,{resolve:t,reject:o}),ye({provider:"codex-app-server",captureKind:"request",rawText:JSON.stringify(r),rawValue:{message:r}}),e.send(JSON.stringify(r))})}function rs(e){return new Promise((n,r)=>{e.addEventListener("open",()=>n(),{once:!0}),e.addEventListener("error",()=>r(new Error("websocket open failed")),{once:!0})})}var Gi=300*1e3;function Ie(e){let n=new URL(e);switch(n.protocol){case"ws:":n.protocol="http:";break;case"wss:":n.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return n.pathname="",n.search="",n.hash="",n.toString().replace(/\/$/,"")}function Ar(e){let n=e.fetchImpl??fetch,r=Ie(e.kandanUrl),t=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",o=e.operatingMode??"text",s=async(i,a,d,c={})=>{let f=new URL(a,r),p={...d,operating_mode:o},g={method:i,headers:{authorization:`Bearer ${e.accessToken}`},...c.signal===void 0?{}:{signal:c.signal}};if(i==="GET")for(let[w,v]of Object.entries(p))v!=null&&f.searchParams.set(w,String(v));else g.headers={...g.headers,"content-type":"application/json"},g.body=JSON.stringify(p);let u=await n(f,g),h=await u.json(),l=j(h)?h:void 0;if(l===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${a}`);if(u.ok&&l.ok===!0)return l;let m=typeof l.error=="string"?l.error:`HTTP ${u.status}`;throw new Error(`Linzumi MCP API ${a} failed: ${m}`)};return{validateAuth:()=>s("GET",`${t}/validate`,{}),issueOnboardingDiscoveryToken:i=>s("POST",`${t}/onboarding-discovery-token`,i),getMessage:i=>s("GET",`${t}/message`,i),getThread:i=>s("GET",`${t}/thread`,i),getChannel:i=>s("GET",`${t}/channel`,i),searchWorkspace:i=>s("GET",`${t}/search`,i),askWorkspace:i=>s("POST",`${t}/ask`,i),webSearch:i=>s("GET",`${t}/web-search`,i),fetchUrl:i=>s("GET",`${t}/fetch-url`,i),getCodingJobMetadata:i=>s("GET",`${t}/coding-job-metadata`,i),renameCodingJob:i=>s("POST",`${t}/coding-job-title`,i),upsertCodingJobPlan:(i,a)=>s("POST",`${t}/coding-job-plan`,i,a),replaceCodingJobPlanSteps:i=>s("POST",`${t}/coding-job-plan/steps`,i),updateCodingJobPlanStep:i=>s("POST",`${t}/coding-job-plan/step`,i),linkCodingJobPullRequest:i=>s("POST",`${t}/coding-job-primary-pr`,i),listVaultSecrets:i=>s("GET",`${t}/vault-secrets`,i),noteProjectDirectory:i=>s("POST",`${t}/discovered-project`,i),noteAgentConversation:i=>s("POST",`${t}/discovered-conversation`,i),noteOnboardingDiscoveryStatus:i=>s("POST",`${t}/discovery-status`,i),sendChannelMessage:i=>s("POST",`${t}/channel-message`,i),agentReply:i=>s("POST",`${t}/agent-reply`,i),agentListCodingJobs:i=>s("GET",`${t}/agent/coding-jobs`,i),agentStartCodingJob:i=>s("POST",`${t}/agent/start-coding-job`,i),agentInterruptCodingJob:i=>s("POST",`${t}/agent/interrupt-coding-job`,i),agentSendCodingJobMessage:i=>s("POST",`${t}/agent/send-coding-job-message`,i),agentReadCodingJobThread:i=>s("GET",`${t}/agent/coding-job-thread`,i),agentResolveJobApproval:i=>s("POST",`${t}/agent/resolve-job-approval`,i),agentArchiveCodingJob:i=>s("POST",`${t}/agent/archive-coding-job`,i),agentUnarchiveCodingJob:i=>s("POST",`${t}/agent/unarchive-coding-job`,i),agentSetThreadStatus:i=>s("POST",`${t}/agent/set-thread-status`,i),agentCreateChannel:i=>s("POST",`${t}/agent/create-channel`,i),agentRenameChannel:i=>s("POST",`${t}/agent/rename-channel`,i),agentArchiveChannel:i=>s("POST",`${t}/agent/archive-channel`,i),agentUnarchiveChannel:i=>s("POST",`${t}/agent/unarchive-channel`,i),agentAddReaction:i=>s("POST",`${t}/agent/add-reaction`,i),agentRemoveReaction:i=>s("POST",`${t}/agent/remove-reaction`,i),agentPinMessage:i=>s("POST",`${t}/agent/pin-message`,i),agentUnpinMessage:i=>s("POST",`${t}/agent/unpin-message`,i),prepareMessageUploads:i=>s("POST",`${t}/message-uploads/prepare`,i),attachMessageFiles:i=>s("POST",`${t}/message-files/attach`,i),prepareCustomEmoji:i=>s("POST",`${t}/custom-emoji/prepare`,i),renameCustomEmoji:i=>s("POST",`${t}/custom-emoji/rename`,i),sendThreadReply:i=>s("POST",`${t}/thread-reply`,i),sendDm:i=>s("POST",`${t}/dm`,i),dmOwner:i=>s("POST",`${t}/dm-owner`,i),getVaultValues:i=>s("POST",`${t}/vault-values`,i)}}import{existsSync as ts,mkdirSync as Zi,readFileSync as os,writeFileSync as Xi}from"node:fs";import{homedir as ss}from"node:os";import{dirname as ea,join as is}from"node:path";function as(){return is(ss(),".linzumi","auth.json")}function Ir(e,n=as()){if(!ts(n))return;let r=ds(os(n,"utf8")),t=Ie(e),o=r.local_codex_runner?.[t];if(!(o===void 0||o.access_token.trim()==="")&&!(o.expires_at!==void 0&&Date.parse(o.expires_at)<=Date.now()))return{accessToken:o.access_token,kandanBaseUrl:t,issuedAt:o.issued_at,expiresAt:o.expires_at}}function ds(e){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Kandan auth cache must contain a JSON object");let r=n,t=r.local_codex_runner,o=r.personal_agent_delegation;if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:ls(t),personal_agent_delegation:cs(o)}}function cs(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.access_token,r=e.issued_at,t=e.expires_at;if(!(typeof n!="string"||typeof r!="string"))return{access_token:n,issued_at:r,expires_at:typeof t=="string"?t:void 0}}function ls(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>{if(typeof r!="object"||r===null||Array.isArray(r))return[];let t=r.access_token,o=r.issued_at,s=r.expires_at;return typeof t!="string"||typeof o!="string"?[]:[[n,{access_token:t,issued_at:o,expires_at:typeof s=="string"?s:void 0}]]}))}function Mr(e){let n=e.channelSession;return{...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{reasoningEffort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:Lr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandbox:n.sandbox}}}function Nr(e){let n=e.channelSession;return{cwd:e.cwd,...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{effort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:Lr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandboxPolicy:us(n.sandbox,e.cwd)}}}function Lr(e,n){switch(e){case void 0:case"default":return"on-request";case"never":return n==="danger-full-access"?"never":"on-request";case"on-request":case"on-failure":return e;default:throw new Error(`unsupported Codex approval policy: ${e}`)}}function us(e,n){switch(e){case"danger-full-access":return{type:"dangerFullAccess"};case"read-only":return{type:"readOnly",access:{type:"fullAccess"},networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[n],readOnlyAccess:{type:"fullAccess"},networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};default:throw new Error(`unsupported Codex sandbox mode: ${e}`)}}var an={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function jr(e){let n;try{n=JSON.parse(Buffer.from(e,"base64").toString("utf8"))}catch{throw new Error("invalid guest cloud turn config payload (not base64 JSON)")}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("invalid guest cloud turn config payload");let r=n;for(let[t,o]of[["codexVersion",r.codexVersion],["sandbox",r.sandbox],["approvalPolicy",r.approvalPolicy],["kandanUrl",r.kandanUrl],["cwd",r.cwd]])if(typeof o!="string"||o==="")throw new Error(`invalid guest cloud turn config payload (${t} missing)`);if(!Array.isArray(r.input))throw new Error("invalid guest cloud turn config payload (input)");if(typeof r.appServerPort!="number"||!Number.isInteger(r.appServerPort))throw new Error("invalid guest cloud turn config payload (appServerPort)");return r}var K="/home/agent",fs=`${K}/.linzumi-provisioned`;var dn="/dev/shm/linzumi",ya=`${dn}/codex`,ma=`${dn}/mcp-auth.json`;var _a=`${dn}/codex.env`;var va=`${K}/cloud-supervisor.mjs`,$r=`${K}/mcp-server.mjs`,cn=`${K}/.secrets`,ln=`${cn}/mcp-auth.json`,Me=`${K}/.codex`,Jr=`${Me}/linzumi-thread-map.json`;var un=`${K}/.turn-heartbeats`,Ur=5e3,ps=/^[A-Za-z0-9-]{8,64}$/;function fn(e){if(!ps.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var bs=3e4,Ss=200;function Fr(e){return e.replace(/\bsmk_[A-Za-z0-9._-]+/g,"smk_[REDACTED]").replace(/\b(sk|lz|tok|bearer)[-_][A-Za-z0-9._-]{8,}/gi,"$1_[REDACTED]")}function D(e){process.stdout.write(`${JSON.stringify(e)}
13
- `)}function Ne(e,n,r){D({phase:"exit",ok:e,reason:Fr(n),turnMs:r})}function ws(e){return{id:e.id,name:e.name,baseUrl:e.baseUrl,envKey:e.envKey,wireApi:e.wireApi,...e.httpHeaders===void 0?{}:{httpHeaders:{...e.httpHeaders}},...e.envHttpHeaders===void 0?{}:{envHttpHeaders:{...e.envHttpHeaders}}}}function vs(e){if(e.sandbox!=="danger-full-access")throw new Error(`guest cloud turn requires sandbox "danger-full-access", got ${JSON.stringify(e.sandbox)}`);if(e.approvalPolicy!=="never")throw new Error(`guest cloud turn requires approvalPolicy "never", got ${JSON.stringify(e.approvalPolicy)}`)}function Es(e,n=Me){let r=Er({command:"node",argsPrefix:[$r],kandanUrl:e.kandanUrl,authFilePath:ln,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return Tr(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[r],...e.modelProvider===void 0?{}:{modelProvider:ws(e.modelProvider)},env:{CODEX_HOME:n,...Br(e)}})}function Br(e){let n=process.env[an.llmProxyToken];return e.modelProvider===void 0||n===void 0||n===""?{}:{[e.modelProvider.envKey]:n}}function ks(e,n){let r=process.env[an.mcpAuthFileContents];if(r===void 0||r==="")throw new Error("guest cloud turn missing MCP auth-cache (LINZUMI_CLOUD_MCP_AUTH_JSON)");me(e,{recursive:!0,mode:448}),Dr(e,448),Le(n,r,{mode:384}),Dr(n,384)}function Cs(e){try{Vr(e,{recursive:!0,force:!0})}catch{}}var Os=64;function Gr(e){try{let n=JSON.parse(gs(e,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))return{};let r={};for(let[t,o]of Object.entries(n))typeof o=="string"&&o!==""&&(r[t]=o);return r}catch{return{}}}function Ts(e,n,r){try{let t=Gr(e);delete t[n];let o=Object.entries(t),s=o.slice(Math.max(0,o.length-(Os-1)));s.push([n,r]),me(xs(e),{recursive:!0}),Le(e,JSON.stringify(Object.fromEntries(s)))}catch{}}var Ps=new Set(["turn/completed","turn/failed","turn/aborted"]),Rs=2e3;function As(e){let n=W(W(e)?.item);return n===void 0||H(n.type)!=="agentMessage"?"":(wr(n.content)??[]).map(o=>{let s=W(o);if(s===void 0)return;let i=H(s.type);if(!(i!=="text"&&i!=="output_text"&&i!=="input_text"))return H(s.text)??H(s.content)}).filter(o=>o!==void 0&&o!=="").join(`
9
+ `+r)}function z(e,n,r,t,o,s){if(e.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,z),e.emit("wsClientError",i,r,n)}else pe(r,t,o,s)}});import{spawn as hs}from"node:child_process";import{rmSync as Vr,writeFileSync as je,mkdirSync as me,chmodSync as Dr,readFileSync as gs,readdirSync as ys,statSync as ms,unlinkSync as _s}from"node:fs";import{dirname as xs,join as pn}from"node:path";var xo=se(cr(),1),bo=se(qe(),1),So=se(Ke(),1),tn=se(Re(),1),wo=se(_r(),1);function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{appendFileSync as vo,openSync as li}from"node:fs";import{homedir as Eo}from"node:os";import{dirname as ko,join as Co}from"node:path";import{mkdirSync as Oo}from"node:fs";var q="<SENSITIVE_DATA>",xr=new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"]),Po=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function oe(e,n,r={}){let t=r.logFile??To();try{Oo(ko(t),{recursive:!0}),vo(t,`${JSON.stringify({ts:new Date().toISOString(),event:e,...r.sessionId===void 0?{}:{sessionId:r.sessionId},...Ro(n)})}
10
+ `,"utf8")}catch{return}}function To(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?Co(Eo(),".linzumi","logs","command-events.jsonl"):e}function Ro(e){return br(e)}function on(e,n){return Mo(n)?q:typeof e=="string"?Sr(e):Array.isArray(e)?n==="args"?Ao(e):e.map(r=>on(r,void 0)):e!==null&&typeof e=="object"?br(e):e}function br(e){let n=typeof e.name=="string"?e.name.toLowerCase():void 0,r=n==="authorization"||n==="cookie"||n==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="runner_console").map(([t,o])=>[t,r&&t==="value"?q:on(o,t)]))}function Ao(e){let n=!1;return e.map(r=>{if(typeof r!="string")return n=!1,on(r,void 0);if(n)return n=!1,q;let[t,o]=Io(r);return Po.has(t)?o===void 0?(n=!0,r):`${t}=${q}`:Sr(r)})}function Io(e){let n=e.indexOf("=");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Mo(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function Sr(e){return No(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,q)}function No(e){let n;try{n=new URL(e)}catch{return jo(e)}for(let r of[...n.searchParams.keys()])xr.has(r.toLowerCase())&&n.searchParams.set(r,q);return n.toString()}function jo(e){let n=e.indexOf("?"),r=e.indexOf("#");if(n===-1||r!==-1&&r<n)return e;let t=e.slice(0,n),o=r===-1?e.slice(n+1):e.slice(n+1,r),s=r===-1?"":e.slice(r),i=new URLSearchParams(o),a=!1;for(let d of[...i.keys()])xr.has(d.toLowerCase())&&(i.set(d,q),a=!0);switch(a){case!0:return`${t}?${i.toString()}${s}`;case!1:return e}}import{mkdirSync as Lo,appendFileSync as Jo}from"node:fs";import{dirname as $o}from"node:path";function W(e){return e!==void 0&&L(e)?e:void 0}function wr(e){return Array.isArray(e)?e:void 0}function H(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function vr(e){return JSON.stringify(e)}var he,Uo=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function ye(e){let n=Do();if(n===void 0)return;let r=Vo(n),t=Fo(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:r.nextOrdinal,offsetMs:Math.max(0,Date.now()-r.startedAtMs),...t.rawText===void 0?{}:{rawText:t.rawText},...t.rawValue===void 0?{}:{rawValue:t.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:ge(e.captureMetadata)},...t.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...t.transforms]}};r.nextOrdinal+=1,Jo(n,`${vr(o)}
11
+ `,"utf8")}function Do(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function Vo(e){return he!==void 0&&he.path===e||(Lo($o(e),{recursive:!0}),he={path:e,startedAtMs:Date.now(),nextOrdinal:0}),he}function Fo(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let n=[],r=e.rawValue===void 0?void 0:ge(e.rawValue,"$.rawValue",n);return{rawText:Go(e.rawText,n),rawValue:r,transforms:n}}function Go(e,n){if(e!==void 0)try{let r=JSON.parse(e);return JSON.stringify(ge(r,"$.rawText",n))}catch{return e}}function ge(e,n="$",r=[]){if(Array.isArray(e))return e.map((o,s)=>ge(o,`${n}[${s}]`,r));if(!L(e))return e;let t=Object.entries(e).map(([o,s])=>{let i=`${n}.${o}`;return Uo.test(o)?(r.push({type:"credential_redaction",path:i}),[o,"[REDACTED]"]):[o,s===void 0?void 0:ge(s,i,r)]});return Object.fromEntries(t)}function Er(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},ELECTRON_RUN_AS_NODE:"1"}}}function sn(e){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${Bo(e.args)}`,...Object.entries(e.env).flatMap(([n,r])=>["-c",`mcp_servers.${e.name}.env.${n}=${JSON.stringify(r)}`])]}function Bo(e){return`[${e.map(n=>JSON.stringify(n)).join(", ")}]`}var Oi=["# Managed by Linzumi - do not edit by hand.","# This isolated CODEX_HOME keeps Linzumi-spawned codex processes off the","# user's ~/.codex config and the macOS Keychain. See codexHome.ts.",'mcp_oauth_credentials_store = "file"','cli_auth_credentials_store = "file"',""].join(`
12
+ `);function kr(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}var zo=(()=>{let e=process.env.LINZUMI_CODEX_WS_KEEPALIVE_MS;if(e===void 0)return 2e4;let n=Number.parseInt(e,10);return Number.isInteger(n)&&n>0?n:2e4})();function qo(e){let n=e;if(typeof n.ping=="function"&&n.readyState===WebSocket.OPEN)try{n.ping()}catch{}}function Pr(e,n={}){return["app-server",...Ho(n),"--listen",e]}var Wo=["-c","features.apps=false"];function Ho(e){return[...Wo,...kr(),...e.model===void 0?[]:["-c",`model=${JSON.stringify(e.model)}`],...e.reasoningEffort===void 0?[]:["-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`],...e.fast===!0?["-c",`service_tier=${JSON.stringify("fast")}`]:[],...(e.mcpServers??[]).flatMap(n=>sn(n)),...e.modelProvider===void 0?[]:Ko(e.modelProvider)]}function Ko(e){return["-c",`model_providers.${e.id}.name=${JSON.stringify(e.name)}`,"-c",`model_providers.${e.id}.base_url=${JSON.stringify(e.baseUrl)}`,"-c",`model_providers.${e.id}.env_key=${JSON.stringify(e.envKey)}`,"-c",`model_providers.${e.id}.wire_api=${JSON.stringify(e.wireApi)}`,...Object.entries(e.httpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.http_headers.${n}=${JSON.stringify(r)}`]),...Object.entries(e.envHttpHeaders??{}).flatMap(([n,r])=>["-c",`model_providers.${e.id}.env_http_headers.${n}=${JSON.stringify(r)}`]),"-c",`model_provider=${JSON.stringify(e.id)}`]}async function Tr(e,n=r=>new tn.default(r)){let r=await Yo(e,n),t=new Map,o=new Set,s=new Set,i=[],a=new Set,d={nextId:1,closeError:void 0},c=u=>{let h=new Error(u);t.forEach(l=>l.reject(h)),t.clear()},f=setInterval(()=>qo(r),zo);f.unref?.();let p=u=>{if(clearInterval(f),c(u),d.closeError===void 0){d.closeError=new Error(u);for(let h of a)Or(h,d.closeError);a.clear()}};return r.addEventListener("close",()=>p("codex app-server websocket closed")),r.addEventListener("error",()=>p("codex app-server websocket closed")),r.addEventListener("message",u=>{let h=String(u.data),l=Xo(h);if(l!==void 0){if(ye({provider:"codex-app-server",captureKind:Zo(l),rawText:h,rawValue:{message:l}}),"id"in l&&("result"in l||"error"in l)){let m=t.get(l.id);m!==void 0&&(t.delete(l.id),m.resolve(l));return}if("id"in l&&typeof l.method=="string"){es(r,l,s);return}if(!("id"in l)&&typeof l.method=="string"){let m=l;o.size===0?i.push(m):o.forEach(w=>Cr(w,m))}}}),await ns(r,t),{request:(u,h)=>{let l=d.nextId;return d.nextId+=1,Rr(r,t,h===void 0?{jsonrpc:"2.0",id:l,method:u}:{jsonrpc:"2.0",id:l,method:u,params:h})},notify:(u,h)=>{let l=h===void 0?{jsonrpc:"2.0",method:u}:{jsonrpc:"2.0",method:u,params:h};ye({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(l),rawValue:{message:l}}),r.send(JSON.stringify(l))},onNotification:u=>{o.add(u),i.splice(0).forEach(h=>Cr(u,h))},onRequest:u=>{s.add(u)},onClose:u=>{if(d.closeError!==void 0){Or(u,d.closeError);return}a.add(u)},close:()=>{clearInterval(f),r.close()}}}function Zo(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function Xo(e){let n=String(e);try{let r=JSON.parse(n);if(!L(r))throw new Error("codex app-server sent non-object JSON-RPC message");return r}catch(r){oe("codex.app_server_frame_malformed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r),payload:n.slice(0,512),payloadChars:n.length});return}}function Cr(e,n){try{e(n)}catch(r){oe("codex.notification_callback_failed",{purpose:"codex.app_server",method:n.method,message:r instanceof Error?r.message:String(r)})}}function Or(e,n){try{e(n)}catch(r){oe("codex.close_callback_failed",{purpose:"codex.app_server",message:r instanceof Error?r.message:String(r)})}}async function Yo(e,n,r=2e3){let t=Date.now()+r,o;for(;Date.now()<=t;){let s=n(e);try{return await rs(s),s}catch(i){o=i instanceof Error?i:new Error(String(i)),Qo(s)}}throw o??new Error("websocket open failed")}function Qo(e){try{e.close()}catch{}}async function es(e,n,r){try{if(r.size===0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}));return}for(let t of r){let o=await t(n);if(o!==void 0){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,result:o}));return}}e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}}))}catch(t){e.send(JSON.stringify({jsonrpc:"2.0",id:n.id,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}))}}async function ns(e,n){let r=await Rr(e,n,{jsonrpc:"2.0",id:"initialize",method:"initialize",params:{clientInfo:{name:"kandan-local-codex-runner",version:"0.0.1"},capabilities:{experimentalApi:!0}}});if("error"in r)throw new Error(`codex initialize failed: ${r.error.message}`);let t={jsonrpc:"2.0",method:"initialized"};ye({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(t),rawValue:{message:t}}),e.send(JSON.stringify(t))}function Rr(e,n,r){return e.readyState!==WebSocket.OPEN?Promise.reject(new Error("codex app-server websocket is not open")):new Promise((t,o)=>{n.set(r.id,{resolve:t,reject:o}),ye({provider:"codex-app-server",captureKind:"request",rawText:JSON.stringify(r),rawValue:{message:r}}),e.send(JSON.stringify(r))})}function rs(e){return new Promise((n,r)=>{e.addEventListener("open",()=>n(),{once:!0}),e.addEventListener("error",()=>r(new Error("websocket open failed")),{once:!0})})}var Bi=300*1e3;function Ie(e){let n=new URL(e);switch(n.protocol){case"ws:":n.protocol="http:";break;case"wss:":n.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return n.pathname="",n.search="",n.hash="",n.toString().replace(/\/$/,"")}function Ar(e){let n=e.fetchImpl??fetch,r=Ie(e.kandanUrl),t=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",o=e.operatingMode??"text",s=async(i,a,d,c={})=>{let f=new URL(a,r),p={...d,operating_mode:o},g={method:i,headers:{authorization:`Bearer ${e.accessToken}`},...c.signal===void 0?{}:{signal:c.signal}};if(i==="GET")for(let[w,v]of Object.entries(p))v!=null&&f.searchParams.set(w,String(v));else g.headers={...g.headers,"content-type":"application/json"},g.body=JSON.stringify(p);let u=await n(f,g),h=await u.json(),l=L(h)?h:void 0;if(l===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${a}`);if(u.ok&&l.ok===!0)return l;let m=typeof l.error=="string"?l.error:`HTTP ${u.status}`;throw new Error(`Linzumi MCP API ${a} failed: ${m}`)};return{validateAuth:()=>s("GET",`${t}/validate`,{}),issueOnboardingDiscoveryToken:i=>s("POST",`${t}/onboarding-discovery-token`,i),getMessage:i=>s("GET",`${t}/message`,i),getThread:i=>s("GET",`${t}/thread`,i),getChannel:i=>s("GET",`${t}/channel`,i),searchWorkspace:i=>s("GET",`${t}/search`,i),askWorkspace:i=>s("POST",`${t}/ask`,i),webSearch:i=>s("GET",`${t}/web-search`,i),fetchUrl:i=>s("GET",`${t}/fetch-url`,i),getCodingJobMetadata:i=>s("GET",`${t}/coding-job-metadata`,i),listProjects:i=>s("GET",`${t}/projects`,i),getProjectTasks:i=>s("GET",`${t}/project-tasks`,i),createProjectTask:i=>s("POST",`${t}/project-tasks/create`,i),updateProjectTask:i=>s("POST",`${t}/project-tasks/update`,i),deleteProjectTask:i=>s("POST",`${t}/project-tasks/delete`,i),addProjectTaskDependency:i=>s("POST",`${t}/project-tasks/add-dependency`,i),removeProjectTaskDependency:i=>s("POST",`${t}/project-tasks/remove-dependency`,i),renameCodingJob:i=>s("POST",`${t}/coding-job-title`,i),upsertCodingJobPlan:(i,a)=>s("POST",`${t}/coding-job-plan`,i,a),replaceCodingJobPlanSteps:i=>s("POST",`${t}/coding-job-plan/steps`,i),updateCodingJobPlanStep:i=>s("POST",`${t}/coding-job-plan/step`,i),linkCodingJobPullRequest:i=>s("POST",`${t}/coding-job-primary-pr`,i),listVaultSecrets:i=>s("GET",`${t}/vault-secrets`,i),noteProjectDirectory:i=>s("POST",`${t}/discovered-project`,i),noteAgentConversation:i=>s("POST",`${t}/discovered-conversation`,i),noteOnboardingDiscoveryStatus:i=>s("POST",`${t}/discovery-status`,i),sendChannelMessage:i=>s("POST",`${t}/channel-message`,i),agentReply:i=>s("POST",`${t}/agent-reply`,i),agentListCodingJobs:i=>s("GET",`${t}/agent/coding-jobs`,i),agentStartCodingJob:i=>s("POST",`${t}/agent/start-coding-job`,i),agentInterruptCodingJob:i=>s("POST",`${t}/agent/interrupt-coding-job`,i),agentSendCodingJobMessage:i=>s("POST",`${t}/agent/send-coding-job-message`,i),agentReadCodingJobThread:i=>s("GET",`${t}/agent/coding-job-thread`,i),agentResolveJobApproval:i=>s("POST",`${t}/agent/resolve-job-approval`,i),agentArchiveCodingJob:i=>s("POST",`${t}/agent/archive-coding-job`,i),agentUnarchiveCodingJob:i=>s("POST",`${t}/agent/unarchive-coding-job`,i),agentSetThreadStatus:i=>s("POST",`${t}/agent/set-thread-status`,i),agentCreateChannel:i=>s("POST",`${t}/agent/create-channel`,i),agentRenameChannel:i=>s("POST",`${t}/agent/rename-channel`,i),agentArchiveChannel:i=>s("POST",`${t}/agent/archive-channel`,i),agentUnarchiveChannel:i=>s("POST",`${t}/agent/unarchive-channel`,i),agentAddReaction:i=>s("POST",`${t}/agent/add-reaction`,i),agentRemoveReaction:i=>s("POST",`${t}/agent/remove-reaction`,i),agentPinMessage:i=>s("POST",`${t}/agent/pin-message`,i),agentUnpinMessage:i=>s("POST",`${t}/agent/unpin-message`,i),prepareMessageUploads:i=>s("POST",`${t}/message-uploads/prepare`,i),attachMessageFiles:i=>s("POST",`${t}/message-files/attach`,i),prepareCustomEmoji:i=>s("POST",`${t}/custom-emoji/prepare`,i),renameCustomEmoji:i=>s("POST",`${t}/custom-emoji/rename`,i),sendThreadReply:i=>s("POST",`${t}/thread-reply`,i),sendDm:i=>s("POST",`${t}/dm`,i),dmOwner:i=>s("POST",`${t}/dm-owner`,i),getVaultValues:i=>s("POST",`${t}/vault-values`,i)}}import{existsSync as ts,mkdirSync as Zi,readFileSync as os,writeFileSync as Xi}from"node:fs";import{homedir as ss}from"node:os";import{dirname as ea,join as is}from"node:path";function as(){return is(ss(),".linzumi","auth.json")}function Ir(e,n=as()){if(!ts(n))return;let r=ds(os(n,"utf8")),t=Ie(e),o=r.local_codex_runner?.[t];if(!(o===void 0||o.access_token.trim()==="")&&!(o.expires_at!==void 0&&Date.parse(o.expires_at)<=Date.now()))return{accessToken:o.access_token,kandanBaseUrl:t,issuedAt:o.issued_at,expiresAt:o.expires_at}}function ds(e){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Kandan auth cache must contain a JSON object");let r=n,t=r.local_codex_runner,o=r.personal_agent_delegation;if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:ls(t),personal_agent_delegation:cs(o)}}function cs(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.access_token,r=e.issued_at,t=e.expires_at;if(!(typeof n!="string"||typeof r!="string"))return{access_token:n,issued_at:r,expires_at:typeof t=="string"?t:void 0}}function ls(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([n,r])=>{if(typeof r!="object"||r===null||Array.isArray(r))return[];let t=r.access_token,o=r.issued_at,s=r.expires_at;return typeof t!="string"||typeof o!="string"?[]:[[n,{access_token:t,issued_at:o,expires_at:typeof s=="string"?s:void 0}]]}))}function Mr(e){let n=e.channelSession;return{...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{reasoningEffort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:jr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandbox:n.sandbox}}}function Nr(e){let n=e.channelSession;return{cwd:e.cwd,...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{effort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:jr(n.approvalPolicy,n.sandbox),...n.sandbox===void 0?{}:{sandboxPolicy:us(n.sandbox,e.cwd)}}}function jr(e,n){switch(e){case void 0:case"default":return"on-request";case"never":return n==="danger-full-access"?"never":"on-request";case"on-request":case"on-failure":return e;default:throw new Error(`unsupported Codex approval policy: ${e}`)}}function us(e,n){switch(e){case"danger-full-access":return{type:"dangerFullAccess"};case"read-only":return{type:"readOnly",access:{type:"fullAccess"},networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[n],readOnlyAccess:{type:"fullAccess"},networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};default:throw new Error(`unsupported Codex sandbox mode: ${e}`)}}var an={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function Lr(e){let n;try{n=JSON.parse(Buffer.from(e,"base64").toString("utf8"))}catch{throw new Error("invalid guest cloud turn config payload (not base64 JSON)")}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("invalid guest cloud turn config payload");let r=n;for(let[t,o]of[["codexVersion",r.codexVersion],["sandbox",r.sandbox],["approvalPolicy",r.approvalPolicy],["kandanUrl",r.kandanUrl],["cwd",r.cwd]])if(typeof o!="string"||o==="")throw new Error(`invalid guest cloud turn config payload (${t} missing)`);if(!Array.isArray(r.input))throw new Error("invalid guest cloud turn config payload (input)");if(typeof r.appServerPort!="number"||!Number.isInteger(r.appServerPort))throw new Error("invalid guest cloud turn config payload (appServerPort)");return r}var K="/home/agent",fs=`${K}/.linzumi-provisioned`;var dn="/dev/shm/linzumi",ya=`${dn}/codex`,ma=`${dn}/mcp-auth.json`;var _a=`${dn}/codex.env`;var va=`${K}/cloud-supervisor.mjs`,Jr=`${K}/mcp-server.mjs`,cn=`${K}/.secrets`,ln=`${cn}/mcp-auth.json`,Me=`${K}/.codex`,$r=`${Me}/linzumi-thread-map.json`;var un=`${K}/.turn-heartbeats`,Ur=5e3,ps=/^[A-Za-z0-9-]{8,64}$/;function fn(e){if(!ps.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var bs=3e4,Ss=200;function Fr(e){return e.replace(/\bsmk_[A-Za-z0-9._-]+/g,"smk_[REDACTED]").replace(/\b(sk|lz|tok|bearer)[-_][A-Za-z0-9._-]{8,}/gi,"$1_[REDACTED]")}function D(e){process.stdout.write(`${JSON.stringify(e)}
13
+ `)}function Ne(e,n,r){D({phase:"exit",ok:e,reason:Fr(n),turnMs:r})}function ws(e){return{id:e.id,name:e.name,baseUrl:e.baseUrl,envKey:e.envKey,wireApi:e.wireApi,...e.httpHeaders===void 0?{}:{httpHeaders:{...e.httpHeaders}},...e.envHttpHeaders===void 0?{}:{envHttpHeaders:{...e.envHttpHeaders}}}}function vs(e){if(e.sandbox!=="danger-full-access")throw new Error(`guest cloud turn requires sandbox "danger-full-access", got ${JSON.stringify(e.sandbox)}`);if(e.approvalPolicy!=="never")throw new Error(`guest cloud turn requires approvalPolicy "never", got ${JSON.stringify(e.approvalPolicy)}`)}function Es(e,n=Me){let r=Er({command:"node",argsPrefix:[Jr],kandanUrl:e.kandanUrl,authFilePath:ln,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return Pr(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[r],...e.modelProvider===void 0?{}:{modelProvider:ws(e.modelProvider)},env:{CODEX_HOME:n,...Gr(e)}})}function Gr(e){let n=process.env[an.llmProxyToken];return e.modelProvider===void 0||n===void 0||n===""?{}:{[e.modelProvider.envKey]:n}}function ks(e,n){let r=process.env[an.mcpAuthFileContents];if(r===void 0||r==="")throw new Error("guest cloud turn missing MCP auth-cache (LINZUMI_CLOUD_MCP_AUTH_JSON)");me(e,{recursive:!0,mode:448}),Dr(e,448),je(n,r,{mode:384}),Dr(n,384)}function Cs(e){try{Vr(e,{recursive:!0,force:!0})}catch{}}var Os=64;function Br(e){try{let n=JSON.parse(gs(e,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))return{};let r={};for(let[t,o]of Object.entries(n))typeof o=="string"&&o!==""&&(r[t]=o);return r}catch{return{}}}function Ps(e,n,r){try{let t=Br(e);delete t[n];let o=Object.entries(t),s=o.slice(Math.max(0,o.length-(Os-1)));s.push([n,r]),me(xs(e),{recursive:!0}),je(e,JSON.stringify(Object.fromEntries(s)))}catch{}}var Ts=new Set(["turn/completed","turn/failed","turn/aborted"]),Rs=2e3;function As(e){let n=W(W(e)?.item);return n===void 0||H(n.type)!=="agentMessage"?"":(wr(n.content)??[]).map(o=>{let s=W(o);if(s===void 0)return;let i=H(s.type);if(!(i!=="text"&&i!=="output_text"&&i!=="input_text"))return H(s.text)??H(s.content)}).filter(o=>o!==void 0&&o!=="").join(`
14
14
 
15
- `)}var Is=15e3;function Ms(e){return/already_replied|no_active_asker_binding/i.test(e)}async function Ns(e){let n=e.body.trim();if(n==="")return"skipped";let r=Ir(e.kandanUrl,e.mcpAuthPath);if(r===void 0)throw new Error("reply relay: no agent token in the guest MCP auth file");let t=async(s,i)=>{let a=new AbortController,d=setTimeout(()=>a.abort(),Is);try{return await fetch(s,{...i,signal:a.signal})}finally{clearTimeout(d)}},o=Ar({kandanUrl:e.kandanUrl,accessToken:r.accessToken,operatingMode:"text",fetchImpl:t});try{return await o.agentReply({body:n}),"posted"}catch(s){let i=s instanceof Error?s.message:String(s);if(Ms(i))return"already";throw new Error(`reply relay failed: ${i}`)}}function Ls(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"approved"}}async function js(e,n,r){for(;;){if(r.exitCode!==null&&r.exitCode!==void 0)throw new Error(`codex app-server exited before it accepted a connection (code ${r.exitCode})`);try{return await Pr(e)}catch(t){if(Date.now()>=n)throw t;await new Promise(o=>setTimeout(o,Ss))}}}var $s=360*60*1e3;function Js(e,n){try{for(let r of ys(e))try{let t=pn(e,r);n-ms(t).mtimeMs>$s&&_s(t)}catch{}}catch{}}function Us(e,n,r=Ur){fn(n);let t=pn(e,`${n}.beat`),o=()=>{try{Le(t,`${Date.now()}
16
- `)}catch{}};try{me(e,{recursive:!0})}catch{}Js(e,Date.now()),o();let s=setInterval(o,r);return s.unref?.(),()=>{clearInterval(s);try{Vr(t,{force:!0})}catch{}}}function Ds(e,n,r){try{fn(n),me(e,{recursive:!0}),Le(pn(e,`${n}.exit`),`${JSON.stringify({phase:"exit",ok:r.ok,reason:Fr(r.reason),turnMs:r.turnMs})}
17
- `)}catch{}}async function Vs(e,n={}){let r=n.now??Date.now,t=n.secretsDir??cn,o=n.mcpAuthPath??ln,s=n.codexHome??Me,i=n.threadMapPath??Jr,a=r();vs(e);let d=e.turnNonce!==void 0&&e.turnNonce!==""?Us(n.heartbeatDir??un,e.turnNonce,n.heartbeatIntervalMs):void 0,c,f=()=>{try{c?.pid!==void 0&&c.kill("SIGINT")}catch{}};try{ks(t,o);let p=Es(e,s),g=`ws://127.0.0.1:${e.appServerPort}`;n.spawnCodex===void 0&&me(s,{recursive:!0,mode:448}),c=n.spawnCodex?n.spawnCodex(p):hs("codex",p,{cwd:e.cwd,env:{PATH:process.env.PATH??"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",...process.env.HOME===void 0?{}:{HOME:process.env.HOME},CODEX_HOME:s,...Br(e)},stdio:["ignore","ignore","inherit"],detached:!1});let u=await js(g,a+bs,c);try{u.onRequest?.(y=>Ls(y.method));let h=e.codexThreadId,l;if(h!==void 0&&h!==""){let y=Gr(i)[h];y!==void 0&&("error"in await u.request("thread/resume",{threadId:y,...Mr({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})})||(l=y))}if(l===void 0){let y=await u.request("thread/start",{cwd:e.cwd,serviceName:"kandan-cloud-agent",personality:"pragmatic",approvalPolicy:e.approvalPolicy,...e.model===void 0?{}:{model:e.model},...e.sandbox===void 0?{}:{sandbox:e.sandbox}});if("error"in y)throw new Error(`thread/start failed: ${y.error.message}`);let S=H(W(W(y.result)?.thread)?.id);if(S===void 0)throw new Error("thread/start response did not include thread.id");l=S,h!==void 0&&h!==""&&Ts(i,h,l),D({phase:"thread",mode:"started"})}else D({phase:"thread",mode:"resumed"});let m="",w=!1,v,_e=new Promise((y,S)=>{v={resolve:y,reject:S}}),R=y=>{if(w){D({phase:"codex-exit",benign:!0});return}setTimeout(()=>{w||v?.reject(y())},n.postTerminalGraceMs??Rs).unref?.()};u.onNotification(y=>{if(D({phase:"notification",method:y.method}),y.method==="item/completed"){let A=As(y.params);A!==""&&(m=A)}if(!Ps.has(y.method))return;w=!0;let S=y.method==="turn/completed";v?.resolve({ok:S,reason:y.method==="turn/completed"?"turn completed":`turn terminal: ${y.method}`,turnMs:r()-a})}),u.onClose?.(y=>R(()=>new Error(`codex connection closed before a turn terminal: ${y?.message??"connection closed"}`))),c?.once("exit",y=>R(()=>new Error(`codex app-server process exited mid-turn (code ${y})`)));let $=await u.request("turn/start",{threadId:l,input:e.input,...Nr({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})});if("error"in $)throw new Error(`turn/start failed: ${$.error.message}`);let Z=await _e;if(Z.ok){let y=n.relayReply??Ns;try{let S=await y({kandanUrl:e.kandanUrl,mcpAuthPath:o,body:m});D({phase:"reply",relay:S})}catch(S){let A=S instanceof Error?S.message:String(S);return D({phase:"reply",relay:"failed",reason:A}),{ok:!1,reason:A,turnMs:Z.turnMs}}}return Z}finally{u.close()}}finally{d?.(),f(),Cs(t)}}async function zr(e=process.argv,n={}){let r=e[2];if(r==="--selftest")return D({phase:"selftest",ok:!0,node:process.version}),0;if(r===void 0||r==="")return Ne(!1,"missing turn config argv[2]",0),1;let t;try{t=jr(r)}catch(a){return Ne(!1,`config decode failed: ${a instanceof Error?a.message:String(a)}`,0),1}let o=n.heartbeatDir??un,s=n.runTurn??Vs,i=a=>{t.turnNonce!==void 0&&t.turnNonce!==""&&Ds(o,t.turnNonce,a)};try{let a=await s(t);return i(a),Ne(a.ok,a.reason,a.turnMs),a.ok?0:1}catch(a){let d=a instanceof Error?a.message:String(a);return i({ok:!1,reason:d,turnMs:0}),Ne(!1,d,0),1}}function qr(e){let n=!1,r=()=>{n||(n=!0,process.exit(e))};try{process.stdout.write("",r)}catch{r()}setTimeout(r,1e3).unref?.()}zr(process.argv).then(e=>{qr(e)}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
15
+ `)}var Is=15e3;function Ms(e){return/already_replied|no_active_asker_binding/i.test(e)}async function Ns(e){let n=e.body.trim();if(n==="")return"skipped";let r=Ir(e.kandanUrl,e.mcpAuthPath);if(r===void 0)throw new Error("reply relay: no agent token in the guest MCP auth file");let t=async(s,i)=>{let a=new AbortController,d=setTimeout(()=>a.abort(),Is);try{return await fetch(s,{...i,signal:a.signal})}finally{clearTimeout(d)}},o=Ar({kandanUrl:e.kandanUrl,accessToken:r.accessToken,operatingMode:"text",fetchImpl:t});try{return await o.agentReply({body:n}),"posted"}catch(s){let i=s instanceof Error?s.message:String(s);if(Ms(i))return"already";throw new Error(`reply relay failed: ${i}`)}}function js(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"approved"}}async function Ls(e,n,r){for(;;){if(r.exitCode!==null&&r.exitCode!==void 0)throw new Error(`codex app-server exited before it accepted a connection (code ${r.exitCode})`);try{return await Tr(e)}catch(t){if(Date.now()>=n)throw t;await new Promise(o=>setTimeout(o,Ss))}}}var Js=360*60*1e3;function $s(e,n){try{for(let r of ys(e))try{let t=pn(e,r);n-ms(t).mtimeMs>Js&&_s(t)}catch{}}catch{}}function Us(e,n,r=Ur){fn(n);let t=pn(e,`${n}.beat`),o=()=>{try{je(t,`${Date.now()}
16
+ `)}catch{}};try{me(e,{recursive:!0})}catch{}$s(e,Date.now()),o();let s=setInterval(o,r);return s.unref?.(),()=>{clearInterval(s);try{Vr(t,{force:!0})}catch{}}}function Ds(e,n,r){try{fn(n),me(e,{recursive:!0}),je(pn(e,`${n}.exit`),`${JSON.stringify({phase:"exit",ok:r.ok,reason:Fr(r.reason),turnMs:r.turnMs})}
17
+ `)}catch{}}async function Vs(e,n={}){let r=n.now??Date.now,t=n.secretsDir??cn,o=n.mcpAuthPath??ln,s=n.codexHome??Me,i=n.threadMapPath??$r,a=r();vs(e);let d=e.turnNonce!==void 0&&e.turnNonce!==""?Us(n.heartbeatDir??un,e.turnNonce,n.heartbeatIntervalMs):void 0,c,f=()=>{try{c?.pid!==void 0&&c.kill("SIGINT")}catch{}};try{ks(t,o);let p=Es(e,s),g=`ws://127.0.0.1:${e.appServerPort}`;n.spawnCodex===void 0&&me(s,{recursive:!0,mode:448}),c=n.spawnCodex?n.spawnCodex(p):hs("codex",p,{cwd:e.cwd,env:{PATH:process.env.PATH??"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",...process.env.HOME===void 0?{}:{HOME:process.env.HOME},CODEX_HOME:s,...Gr(e)},stdio:["ignore","ignore","inherit"],detached:!1});let u=await Ls(g,a+bs,c);try{u.onRequest?.(y=>js(y.method));let h=e.codexThreadId,l;if(h!==void 0&&h!==""){let y=Br(i)[h];y!==void 0&&("error"in await u.request("thread/resume",{threadId:y,...Mr({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})})||(l=y))}if(l===void 0){let y=await u.request("thread/start",{cwd:e.cwd,serviceName:"kandan-cloud-agent",personality:"pragmatic",approvalPolicy:e.approvalPolicy,...e.model===void 0?{}:{model:e.model},...e.sandbox===void 0?{}:{sandbox:e.sandbox}});if("error"in y)throw new Error(`thread/start failed: ${y.error.message}`);let S=H(W(W(y.result)?.thread)?.id);if(S===void 0)throw new Error("thread/start response did not include thread.id");l=S,h!==void 0&&h!==""&&Ps(i,h,l),D({phase:"thread",mode:"started"})}else D({phase:"thread",mode:"resumed"});let m="",w=!1,v,_e=new Promise((y,S)=>{v={resolve:y,reject:S}}),R=y=>{if(w){D({phase:"codex-exit",benign:!0});return}setTimeout(()=>{w||v?.reject(y())},n.postTerminalGraceMs??Rs).unref?.()};u.onNotification(y=>{if(D({phase:"notification",method:y.method}),y.method==="item/completed"){let A=As(y.params);A!==""&&(m=A)}if(!Ts.has(y.method))return;w=!0;let S=y.method==="turn/completed";v?.resolve({ok:S,reason:y.method==="turn/completed"?"turn completed":`turn terminal: ${y.method}`,turnMs:r()-a})}),u.onClose?.(y=>R(()=>new Error(`codex connection closed before a turn terminal: ${y?.message??"connection closed"}`))),c?.once("exit",y=>R(()=>new Error(`codex app-server process exited mid-turn (code ${y})`)));let J=await u.request("turn/start",{threadId:l,input:e.input,...Nr({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox}})});if("error"in J)throw new Error(`turn/start failed: ${J.error.message}`);let Z=await _e;if(Z.ok){let y=n.relayReply??Ns;try{let S=await y({kandanUrl:e.kandanUrl,mcpAuthPath:o,body:m});D({phase:"reply",relay:S})}catch(S){let A=S instanceof Error?S.message:String(S);return D({phase:"reply",relay:"failed",reason:A}),{ok:!1,reason:A,turnMs:Z.turnMs}}}return Z}finally{u.close()}}finally{d?.(),f(),Cs(t)}}async function zr(e=process.argv,n={}){let r=e[2];if(r==="--selftest")return D({phase:"selftest",ok:!0,node:process.version}),0;if(r===void 0||r==="")return Ne(!1,"missing turn config argv[2]",0),1;let t;try{t=Lr(r)}catch(a){return Ne(!1,`config decode failed: ${a instanceof Error?a.message:String(a)}`,0),1}let o=n.heartbeatDir??un,s=n.runTurn??Vs,i=a=>{t.turnNonce!==void 0&&t.turnNonce!==""&&Ds(o,t.turnNonce,a)};try{let a=await s(t);return i(a),Ne(a.ok,a.reason,a.turnMs),a.ok?0:1}catch(a){let d=a instanceof Error?a.message:String(a);return i({ok:!1,reason:d,turnMs:0}),Ne(!1,d,0),1}}function qr(e){let n=!1,r=()=>{n||(n=!0,process.exit(e))};try{process.stdout.write("",r)}catch{r()}setTimeout(r,1e3).unref?.()}zr(process.argv).then(e=>{qr(e)}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
18
18
  `),qr(1)});