@linzumi/cli 1.0.78 → 1.0.80

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