@linzumi/cli 1.0.107 → 1.0.108

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.107 --version
61
+ npx -y @linzumi/cli@1.0.108 --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 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
3
+ var dr=Object.create;var Sn=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,fr=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 pr=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of lr(n))!fr.call(e,o)&&o!==t&&Sn(e,o,{get:()=>n[o],enumerable:!(r=cr(n,o))||r.enumerable});return e};var fe=(e,n,t)=>(t=e!=null?dr(ur(e)):{},pr(n||!e||!e.__esModule?Sn(t,"default",{value:e,enumerable:!0}):t,e));var z=R((wi,Cn)=>{"use strict";var kn=["nodebuffer","arraybuffer","fragments"],On=typeof Blob<"u";On&&kn.push("blob");Cn.exports={BINARY_TYPES:kn,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:On,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var pe=R((Si,Oe)=>{"use strict";var{EMPTY_BUFFER:gr}=z(),Ve=Buffer[Symbol.species];function mr(e,n){if(e.length===0)return gr;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 En(e,n,t,r,o){for(let s=0;s<o;s++)t[r+s]=e[s]^n[s&3]}function Pn(e,n){for(let t=0;t<e.length;t++)e[t]^=n[t&3]}function hr(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}Oe.exports={concat:mr,mask:En,toArrayBuffer:hr,toBuffer:Ge,unmask:Pn};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=E("bufferutil");Oe.exports.mask=function(n,t,r,o,s){s<48?En(n,t,r,o,s):e.mask(n,t,r,o,s)},Oe.exports.unmask=function(n,t){n.length<32?Pn(n,t):e.unmask(n,t)}}catch{}});var Rn=R((ki,An)=>{"use strict";var Tn=Symbol("kDone"),Be=Symbol("kRun"),qe=class{constructor(n){this[Tn]=()=>{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[Tn])}}};An.exports=qe});var me=R((Oi,Nn)=>{"use strict";var ge=E("zlib"),In=pe(),yr=Rn(),{kStatusCode:Mn}=z(),_r=Buffer[Symbol.species],xr=Buffer.from([0,0,255,255]),Ee=Symbol("permessage-deflate"),F=Symbol("total-length"),te=Symbol("callback"),q=Symbol("buffers"),re=Symbol("error"),Ce,We=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,!Ce){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ce=new yr(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[te];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){Ce.add(o=>{this._decompress(n,t,(s,i)=>{o(),r(s,i)})})}compress(n,t,r){Ce.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"?ge.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ge.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Ee]=this,this._inflate[F]=0,this._inflate[q]=[],this._inflate.on("error",vr),this._inflate.on("data",jn)}this._inflate[te]=r,this._inflate.write(n),t&&this._inflate.write(xr),this._inflate.flush(()=>{let s=this._inflate[re];if(s){this._inflate.close(),this._inflate=null,r(s);return}let i=In.concat(this._inflate[q],this._inflate[F]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[F]=0,this._inflate[q]=[],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"?ge.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ge.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[F]=0,this._deflate[q]=[],this._deflate.on("data",br)}this._deflate[te]=r,this._deflate.write(n),this._deflate.flush(ge.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=In.concat(this._deflate[q],this._deflate[F]);t&&(s=new _r(s.buffer,s.byteOffset,s.length-4)),this._deflate[te]=null,this._deflate[F]=0,this._deflate[q]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};Nn.exports=We;function br(e){this[q].push(e),this[F]+=e.length}function jn(e){if(this[F]+=e.length,this[Ee]._maxPayload<1||this[F]<=this[Ee]._maxPayload){this[q].push(e);return}this[re]=new RangeError("Max payload size exceeded"),this[re].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[re][Mn]=1009,this.removeListener("data",jn),this.reset()}function vr(e){if(this[Ee]._inflate=null,this[re]){this[te](this[re]);return}e[Mn]=1007,this[te](e)}});var oe=R((Ci,Pe)=>{"use strict";var{isUtf8:Jn}=E("buffer"),{hasBlob:wr}=z(),Sr=[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 kr(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Ke(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 Or(e){return wr&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Pe.exports={isBlob:Or,isValidStatusCode:kr,isValidUTF8:Ke,tokenChars:Sr};if(Jn)Pe.exports.isValidUTF8=function(e){return e.length<24?Ke(e):Jn(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=E("utf-8-validate");Pe.exports.isValidUTF8=function(n){return n.length<32?Ke(n):e(n)}}catch{}});var Qe=R((Ei,Vn)=>{"use strict";var{Writable:Cr}=E("stream"),Ln=me(),{BINARY_TYPES:Er,EMPTY_BUFFER:$n,kStatusCode:Pr,kWebSocket:Tr}=z(),{concat:He,toArrayBuffer:Ar,unmask:Rr}=pe(),{isValidStatusCode:Ir,isValidUTF8:Un}=oe(),Te=Buffer[Symbol.species],j=0,Dn=1,zn=2,Fn=3,Ze=4,Xe=5,Ae=6,Ye=class extends Cr{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||Er[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[Tr]=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 Te(r.buffer,r.byteOffset+n,r.length-n),new Te(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 Te(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 Dn:this.getPayloadLength16(n);break;case zn:this.getPayloadLength64(n);break;case Fn:this.getMask();break;case Ze:this.getData(n);break;case Xe:case Ae: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[Ln.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=Dn:this._payloadLength===127?this._state=zn: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=Ze}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ze}getData(n){let t=$n;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&&Rr(t,this._mask)}if(this._opcode>7){this.controlMessage(t,n);return}if(this._compressed){this._state=Xe,this.decompress(t,n);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(n)}decompress(n,t){this._extensions[Ln.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=Ar(He(r,t)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=j):(this._state=Ae,setImmediate(()=>{this.emit("message",o,!0),this._state=j,this.startLoop(n)}))}else{let o=He(r,t);if(!this._skipUTF8Validation&&!Un(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._state===Xe||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=j):(this._state=Ae,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,$n),this.end();else{let r=n.readUInt16BE(0);if(!Ir(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let o=new Te(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!Un(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=Ae,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[Pr]=o,i}};Vn.exports=Ye});var tn=R((Ti,qn)=>{"use strict";var{Duplex:Pi}=E("stream"),{randomFillSync:Mr}=E("crypto"),Gn=me(),{EMPTY_BUFFER:jr,kWebSocket:Nr,NOOP:Jr}=z(),{isBlob:se,isValidStatusCode:Lr}=oe(),{mask:Bn,toBuffer:H}=pe(),N=Symbol("kByteLength"),$r=Buffer.alloc(4),Re=8*1024,Z,ie=Re,L=0,Ur=1,Dr=2,en=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=Jr,this[Nr]=void 0}static frame(n,t){let r,o=!1,s=2,i=!1;t.mask&&(r=t.maskBuffer||$r,t.generateMask?t.generateMask(r):(ie===Re&&(Z===void 0&&(Z=Buffer.alloc(Re)),Mr(Z,0,Re),ie=0),r[0]=Z[ie++],r[1]=Z[ie++],r[2]=Z[ie++],r[3]=Z[ie++]),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=jr;else{if(typeof n!="number"||!Lr(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):se(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};se(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):se(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};se(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):se(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};se(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=Dr,n.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(nn,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(zr,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=Ur,s.compress(n,r.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");nn(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)}};qn.exports=en;function nn(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 zr(e,n,t){nn(e,n,t),e.onerror(n)}});var nt=R((Ai,et)=>{"use strict";var{kForOnEventAttribute:he,kListener:rn}=z(),Wn=Symbol("kCode"),Kn=Symbol("kData"),Hn=Symbol("kError"),Zn=Symbol("kMessage"),Xn=Symbol("kReason"),ae=Symbol("kTarget"),Yn=Symbol("kType"),Qn=Symbol("kWasClean"),V=class{constructor(n){this[ae]=null,this[Yn]=n}get target(){return this[ae]}get type(){return this[Yn]}};Object.defineProperty(V.prototype,"target",{enumerable:!0});Object.defineProperty(V.prototype,"type",{enumerable:!0});var X=class extends V{constructor(n,t={}){super(n),this[Wn]=t.code===void 0?0:t.code,this[Xn]=t.reason===void 0?"":t.reason,this[Qn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Wn]}get reason(){return this[Xn]}get wasClean(){return this[Qn]}};Object.defineProperty(X.prototype,"code",{enumerable:!0});Object.defineProperty(X.prototype,"reason",{enumerable:!0});Object.defineProperty(X.prototype,"wasClean",{enumerable:!0});var de=class extends V{constructor(n,t={}){super(n),this[Hn]=t.error===void 0?null:t.error,this[Zn]=t.message===void 0?"":t.message}get error(){return this[Hn]}get message(){return this[Zn]}};Object.defineProperty(de.prototype,"error",{enumerable:!0});Object.defineProperty(de.prototype,"message",{enumerable:!0});var ye=class extends V{constructor(n,t={}){super(n),this[Kn]=t.data===void 0?null:t.data}get data(){return this[Kn]}};Object.defineProperty(ye.prototype,"data",{enumerable:!0});var Fr={addEventListener(e,n,t={}){for(let o of this.listeners(e))if(!t[he]&&o[rn]===n&&!o[he])return;let r;if(e==="message")r=function(s,i){let a=new ye("message",{data:i?s:s.toString()});a[ae]=this,Ie(n,this,a)};else if(e==="close")r=function(s,i){let a=new X("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ae]=this,Ie(n,this,a)};else if(e==="error")r=function(s){let i=new de("error",{error:s,message:s.message});i[ae]=this,Ie(n,this,i)};else if(e==="open")r=function(){let s=new V("open");s[ae]=this,Ie(n,this,s)};else return;r[he]=!!t[he],r[rn]=n,t.once?this.once(e,r):this.on(e,r)},removeEventListener(e,n){for(let t of this.listeners(e))if(t[rn]===n&&!t[he]){this.removeListener(e,t);break}}};et.exports={CloseEvent:X,ErrorEvent:de,Event:V,EventTarget:Fr,MessageEvent:ye};function Ie(e,n,t){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,t):e.call(n,t)}});var on=R((Ri,tt)=>{"use strict";var{tokenChars:_e}=oe();function U(e,n,t){e[n]===void 0?e[n]=[t]:e[n].push(t)}function Vr(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&&_e[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&&_e[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(_e[d]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),o=!1}else if(s)if(_e[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&&_e[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 Gr(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(", ")}tt.exports={format:Gr,parse:Vr}});var Je=R((ji,gt)=>{"use strict";var Br=E("events"),qr=E("https"),Wr=E("http"),st=E("net"),Kr=E("tls"),{randomBytes:Hr,createHash:Zr}=E("crypto"),{Duplex:Ii,Readable:Mi}=E("stream"),{URL:sn}=E("url"),W=me(),Xr=Qe(),Yr=tn(),{isBlob:Qr}=oe(),{BINARY_TYPES:rt,EMPTY_BUFFER:Me,GUID:eo,kForOnEventAttribute:an,kListener:no,kStatusCode:to,kWebSocket:P,NOOP:it}=z(),{EventTarget:{addEventListener:ro,removeEventListener:oo}}=nt(),{format:so,parse:io}=on(),{toBuffer:ao}=pe(),co=30*1e3,at=Symbol("kAborted"),dn=[8,13],G=["CONNECTING","OPEN","CLOSING","CLOSED"],lo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,O=class e extends Br{constructor(n,t,r){super(),this._binaryType=rt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Me,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]),dt(this,n,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){rt.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 Xr({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Yr(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",po),o.on("drain",go),o.on("error",mo),o.on("message",ho),o.on("ping",yo),o.on("pong",_o),s.onerror=xo,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),t.length>0&&n.unshift(t),n.on("close",ut),n.on("data",Ne),n.on("end",ft),n.on("error",pt),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[W.extensionName]&&this._extensions[W.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())}),lt(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){cn(this,n,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(n||Me,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){cn(this,n,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(n||Me,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){cn(this,n,r);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[W.extensionName]||(o.compress=!1),this._sender.send(n||Me,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:G.indexOf("CONNECTING")});Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:G.indexOf("CONNECTING")});Object.defineProperty(O,"OPEN",{enumerable:!0,value:G.indexOf("OPEN")});Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:G.indexOf("OPEN")});Object.defineProperty(O,"CLOSING",{enumerable:!0,value:G.indexOf("CLOSING")});Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:G.indexOf("CLOSING")});Object.defineProperty(O,"CLOSED",{enumerable:!0,value:G.indexOf("CLOSED")});Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:G.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[an])return n[no];return null},set(n){for(let t of this.listeners(e))if(t[an]){this.removeListener(e,t);break}typeof n=="function"&&this.addEventListener(e,n,{[an]:!0})}})});O.prototype.addEventListener=ro;O.prototype.removeEventListener=oo;gt.exports=O;function dt(e,n,t,r){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:dn[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,!dn.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${dn.join(", ")})`);let s;if(n instanceof sn)s=n;else try{s=new sn(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;je(e,l);return}let d=i?443:80,f=Hr(16).toString("base64"),p=i?qr.request:Wr.request,y=new Set,u;if(o.createConnection=o.createConnection||(i?fo:uo),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 W(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=so({[W.extensionName]:u.offer()})),t.length){for(let l of t){if(typeof l!="string"||!lo.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[at]||(g=e._req=null,je(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 sn(x,n)}catch{let v=new SyntaxError(`Invalid URL: ${x}`);je(e,v);return}dt(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=Zr("sha1").update(f+eo).digest("base64");if(l.headers["sec-websocket-accept"]!==J){I(e,x,"Invalid Sec-WebSocket-Accept header");return}let v=l.headers["sec-websocket-protocol"],h;if(v!==void 0?y.size?y.has(v)||(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}v&&(e._protocol=v);let w=l.headers["sec-websocket-extensions"];if(w!==void 0){if(!u){I(e,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=io(w)}catch{I(e,x,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(k);if(b.length!==1||b[0]!==W.extensionName){I(e,x,"Server indicated an extension that was not requested");return}try{u.accept(k[W.extensionName])}catch{I(e,x,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[W.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 je(e,n){e._readyState=O.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function uo(e){return e.path=e.socketPath,st.connect(e)}function fo(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=st.isIP(e.host)?"":e.host),Kr.connect(e)}function I(e,n,t){e._readyState=O.CLOSING;let r=new Error(t);Error.captureStackTrace(r,I),n.setHeader?(n[at]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(je,e,r)):(n.destroy(r),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function cn(e,n,t){if(n){let r=Qr(n)?n.size:ao(n).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${e.readyState} (${G[e.readyState]})`);process.nextTick(t,r)}}function po(e,n){let t=this[P];t._closeFrameReceived=!0,t._closeMessage=n,t._closeCode=e,t._socket[P]!==void 0&&(t._socket.removeListener("data",Ne),process.nextTick(ct,t._socket),e===1005?t.close():t.close(e,n))}function go(){let e=this[P];e.isPaused||e._socket.resume()}function mo(e){let n=this[P];n._socket[P]!==void 0&&(n._socket.removeListener("data",Ne),process.nextTick(ct,n._socket),n.close(e[to])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function ot(){this[P].emitClose()}function ho(e,n){this[P].emit("message",e,n)}function yo(e){let n=this[P];n._autoPong&&n.pong(e,!this._isServer,it),n.emit("ping",e)}function _o(e){this[P].emit("pong",e)}function ct(e){e.resume()}function xo(e){let n=this[P];n.readyState!==O.CLOSED&&(n.readyState===O.OPEN&&(n._readyState=O.CLOSING,lt(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function lt(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),co)}function ut(){let e=this[P];this.removeListener("close",ut),this.removeListener("data",Ne),this.removeListener("end",ft),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",ot),e._receiver.on("finish",ot))}function Ne(e){this[P]._receiver.write(e)||this.pause()}function ft(){let e=this[P];e._readyState=O.CLOSING,e._receiver.end(),this.end()}function pt(){let e=this[P];this.removeListener("error",pt),this.on("error",it),e&&(e._readyState=O.CLOSING,this.destroy())}});var _t=R((Ji,yt)=>{"use strict";var Ni=Je(),{Duplex:bo}=E("stream");function mt(e){e.emit("close")}function vo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ht(e){this.removeListener("error",ht),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function wo(e,n){let t=!0,r=new bo({...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(mt,r);return}let i=!1;e.once("error",function(c){i=!0,s(c)}),e.once("close",function(){i||s(o),process.nextTick(mt,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",vo),r.on("error",ht),r}yt.exports=wo});var bt=R((Li,xt)=>{"use strict";var{tokenChars:So}=oe();function ko(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&&So[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}xt.exports={parse:ko}});var Et=R((Ui,Ct)=>{"use strict";var Oo=E("events"),Le=E("http"),{Duplex:$i}=E("stream"),{createHash:Co}=E("crypto"),vt=on(),Y=me(),Eo=bt(),Po=Je(),{GUID:To,kWebSocket:Ao}=z(),Ro=/^[+/0-9A-Za-z]{22}==$/,wt=0,St=1,Ot=2,ln=class extends Oo{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:Po,...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=Le.createServer((r,o)=>{let s=Le.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=Io(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=wt}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===Ot){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(xe,this);return}if(n&&this.once("close",n),this._state!==St)if(this._state=St,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(xe,this):process.nextTick(xe,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{xe(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",kt);let s=n.headers["sec-websocket-key"],i=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){Q(this,n,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Q(this,n,t,400,"Invalid Upgrade header");return}if(s===void 0||!Ro.test(s)){Q(this,n,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Q(this,n,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){be(t,400);return}let c=n.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Eo.parse(c)}catch{Q(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 Y(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let u=vt.parse(f);u[Y.extensionName]&&(y.accept(u[Y.extensionName]),p[Y.extensionName]=y)}catch{Q(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 be(t,g||401,l,x);this.completeUpgrade(p,s,d,n,t,r,o)});return}if(!this.options.verifyClient(y))return be(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[Ao])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>wt)return be(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Co("sha1").update(t+To).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[Y.extensionName]){let p=n[Y.extensionName].params,y=vt.format({[Y.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
- `)),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
5
+ `)),s.removeListener("error",kt),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(xe,this)})),a(f,o)}};Ct.exports=ln;function Io(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 xe(e){e._state=Ot,e.emit("close")}function kt(){this.destroy()}function be(e,n,t,r){t=t||Le.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} ${Le.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 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
- `,"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 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(`
9
+ `+t)}function Q(e,n,t,r,o,s){if(e.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,Q),e.emit("wsClientError",i,t,n)}else be(t,r,o,s)}});import{spawn as Us}from"node:child_process";import{appendFileSync as Ds,rmSync as nr,writeFileSync as ke,mkdirSync as ue,chmodSync as er,readFileSync as zs,readdirSync as Fs,statSync as Vs,unlinkSync as Gs}from"node:fs";import{dirname as tr,join as Fe}from"node:path";var Mo=fe(_t(),1),jo=fe(Qe(),1),No=fe(tn(),1),un=fe(Je(),1),Jo=fe(Et(),1);function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{appendFileSync as Fo,openSync as Hi}from"node:fs";import{homedir as Rt}from"node:os";import{dirname as Vo,join as It,resolve as Go,sep as Bo}from"node:path";import{mkdirSync as qo}from"node:fs";var B={_generated:"GENERATED by scripts/naming_dual_emit_codegen.mjs from scripts/naming_canonical_key_map.json (N2.2 dual-emit, D46) - DO NOT EDIT; run: node scripts/naming_dual_emit_codegen.mjs --write",events:[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],keys:[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],keyPrimaryLegacy:[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],values:[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]],topic:{legacyPrefix:"local_codex_runner:",canonicalPrefix:"commander:"},originator:{legacy:"kandan-local-codex-runner",canonical:"linzumi-commander"}};var $o=new Map(B.events),Uo=new Map(B.events.map(([e,n])=>[n,e])),Pt=new Map(B.keys),Tt=new Map(B.keyPrimaryLegacy),Do=new Map(B.values),zo=new Map(B.values.map(([e,n])=>[n,e])),Gi={eventCanonicalByLegacy:$o,eventLegacyByCanonical:Uo,keyCanonicalByLegacy:Pt,keyPrimaryLegacyByCanonical:Tt,valueCanonicalByLegacy:Do,valueLegacyByCanonical:zo,originator:B.originator,topic:B.topic};function At(e){let n=new Set(e);for(let t of e){let r=Pt.get(t);r!==void 0&&n.add(r);let o=Tt.get(t);o!==void 0&&n.add(o)}return n}var ee="<SENSITIVE_DATA>",Mt=At(new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"])),Wo=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function Ko(e){if(process.env.VITEST===void 0)return;let n=It(Rt(),".linzumi"),t=Go(e);if(t===n||t.startsWith(`${n}${Bo}`))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 ce(e,n,t={}){let r=t.logFile??Ho();Ko(r);try{qo(Vo(r),{recursive:!0}),Fo(r,`${JSON.stringify({ts:new Date().toISOString(),event:e,...t.sessionId===void 0?{}:{sessionId:t.sessionId},...Zo(n)})}
10
+ `,"utf8")}catch{return}}function Ho(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?It(Rt(),".linzumi","logs","command-events.jsonl"):e}function Zo(e){return jt(e)}function fn(e,n){return Qo(n)?ee:typeof e=="string"?Nt(e):Array.isArray(e)?n==="args"?Xo(e):e.map(t=>fn(t,void 0)):e!==null&&typeof e=="object"?jt(e):e}function jt(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"?ee:fn(o,r)]))}function Xo(e){let n=!1;return e.map(t=>{if(typeof t!="string")return n=!1,fn(t,void 0);if(n)return n=!1,ee;let[r,o]=Yo(t);return Wo.has(r)?o===void 0?(n=!0,t):`${r}=${ee}`:Nt(t)})}function Yo(e){let n=e.indexOf("=");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Qo(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 Nt(e){return es(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,ee)}function es(e){let n;try{n=new URL(e)}catch{return ns(e)}for(let t of[...n.searchParams.keys()])Mt.has(t.toLowerCase())&&n.searchParams.set(t,ee);return n.toString()}function ns(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()])Mt.has(c.toLowerCase())&&(i.set(c,ee),a=!0);switch(a){case!0:return`${r}?${i.toString()}${s}`;case!1:return e}}import{mkdirSync as rs,appendFileSync as os}from"node:fs";import{dirname as ss}from"node:path";function A(e){return e!==void 0&&$(e)?e:void 0}function pn(e){return Array.isArray(e)?e:void 0}function _(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function Jt(e){return JSON.stringify(e)}var ve,is=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function Se(e){let n=as();if(n===void 0)return;let t=ds(n),r=cs(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:we(e.captureMetadata)},...r.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...r.transforms]}};t.nextOrdinal+=1,os(n,`${Jt(o)}
11
+ `,"utf8")}function as(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function ds(e){return ve!==void 0&&ve.path===e||(rs(ss(e),{recursive:!0}),ve={path:e,startedAtMs:Date.now(),nextOrdinal:0}),ve}function cs(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:we(e.rawValue,"$.rawValue",n);return{rawText:ls(e.rawText,n),rawValue:t,transforms:n}}function ls(e,n){if(e!==void 0)try{let t=JSON.parse(e);return JSON.stringify(we(t,"$.rawText",n))}catch{return e}}function we(e,n="$",t=[]){if(Array.isArray(e))return e.map((o,s)=>we(o,`${n}[${s}]`,t));if(!$(e))return e;let r=Object.entries(e).map(([o,s])=>{let i=`${n}.${o}`;return is.test(o)?(t.push({type:"credential_redaction",path:i}),[o,"[REDACTED]"]):[o,s===void 0?void 0:we(s,i,t)]});return Object.fromEntries(r)}function Lt(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 gn(e){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${us(e.args)}`,...Object.entries(e.env).flatMap(([n,t])=>["-c",`mcp_servers.${e.name}.env.${n}=${JSON.stringify(t)}`])]}function us(e){return`[${e.map(n=>JSON.stringify(n)).join(", ")}]`}var fa=["# 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 $t(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}var fs=5*6e4;var gs=(()=>{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 ms(e){let n=e;if(typeof n.ping=="function"&&n.readyState===WebSocket.OPEN)try{n.ping()}catch{}}function zt(e,n={}){return["app-server",...ys(n),"--listen",e]}var hs=["-c","features.apps=false"];function ys(e){return[...hs,...$t(),...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=>gn(n)),...e.modelProvider===void 0?[]:_s(e.modelProvider)]}function _s(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 Ft(e,n=t=>new un.default(t)){let t=await vs(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(()=>ms(t),gs);f.unref?.();let p=u=>{if(clearInterval(f),d(u),c.closeError===void 0){c.closeError=new Error(u);for(let g of a)Dt(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=bs(g);if(l!==void 0){if(Se({provider:"codex-app-server",captureKind:xs(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"){Ss(t,l,s);return}if(!("id"in l)&&typeof l.method=="string"){let x=l;o.size===0?i.push(x):o.forEach(C=>Ut(C,x))}}}),await ks(t,r),{request:(u,g)=>{let l=c.nextId;return c.nextId+=1,Vt(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};Se({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=>Ut(u,g))},onRequest:u=>{s.add(u)},onClose:u=>{if(c.closeError!==void 0){Dt(u,c.closeError);return}a.add(u)},close:()=>{clearInterval(f),t.close()}}}function xs(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function bs(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){ce("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 Ut(e,n){try{e(n)}catch(t){ce("codex.notification_callback_failed",{purpose:"codex.app_server",method:n.method,message:t instanceof Error?t.message:String(t)})}}function Dt(e,n){try{e(n)}catch(t){ce("codex.close_callback_failed",{purpose:"codex.app_server",message:t instanceof Error?t.message:String(t)})}}async function vs(e,n,t=2e3){let r=Date.now()+t,o;for(;Date.now()<=r;){let s=n(e);try{return await Os(s),s}catch(i){o=i instanceof Error?i:new Error(String(i)),ws(s)}}throw o??new Error("websocket open failed")}function ws(e){try{e.close()}catch{}}async function Ss(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 ks(e,n){let t=await Vt(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"};Se({provider:"codex-app-server",captureKind:"outgoing",rawText:JSON.stringify(r),rawValue:{message:r}}),e.send(JSON.stringify(r))}function Vt(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}),Se({provider:"codex-app-server",captureKind:"request",rawText:JSON.stringify(t),rawValue:{message:t}}),e.send(JSON.stringify(t))})}function Os(e){return new Promise((n,t)=>{e.addEventListener("open",()=>n(),{once:!0}),e.addEventListener("error",()=>t(new Error("websocket open failed")),{once:!0})})}var ja=300*1e3;function $e(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 mn(e){let n=e.fetchImpl??fetch,t=$e(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 Cs,mkdirSync as Da,readFileSync as Es,renameSync as za,rmSync as Fa,writeFileSync as Va}from"node:fs";import{homedir as Ps}from"node:os";import{dirname as qa,join as Ts}from"node:path";function As(){return Ts(Ps(),".linzumi","auth.json")}function hn(e,n=As()){if(!Cs(n))return;let t=Rs(Es(n,"utf8")),r=$e(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 Rs(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:Ms(r),personal_agent_delegation:Is(o)}}function Is(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 Ms(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 Gt(e){let n=js(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 Bt(e){let n=qt(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 js(e){return qt(e)}function qt(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 Wt(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:Ht(n.approvalPolicy,n.sandbox,{sandboxedNeverDefault:n.sandboxedApprovalNeverDefault}),...n.sandbox===void 0?{}:{sandbox:n.sandbox}}}function Kt(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:Ht(n.approvalPolicy,n.sandbox,{sandboxedNeverDefault:n.sandboxedApprovalNeverDefault}),...n.sandbox===void 0?{}:{sandboxPolicy:Js(n.sandbox,e.cwd)}}}function Ns(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 Ht(e,n,t){let r=Ns(e,n,t);return r==="on-failure"?"on-request":r}function Js(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 yn={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function Zt(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 ne="/home/agent",Ls=`${ne}/.linzumi-provisioned`;var _n="/dev/shm/linzumi",pd=`${_n}/codex`,gd=`${_n}/mcp-auth.json`;var md=`${_n}/codex.env`;var bd=`${ne}/cloud-supervisor.mjs`,Xt=`${ne}/mcp-server.mjs`,xn=`${ne}/.secrets`,bn=`${xn}/mcp-auth.json`,Ue=`${ne}/.codex`,Yt=`${Ue}/linzumi-thread-map.json`;var vn=`${ne}/.turn-heartbeats`,Qt=5e3,$s=/^[A-Za-z0-9-]{8,64}$/;function wn(e){if(!$s.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var Bs=3e4,qs=200;function le(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 ze;function Ws(e){ze=e;try{ue(tr(e),{recursive:!0}),ke(e,"")}catch{ze=void 0}}function D(e){let n=`${JSON.stringify(e)}
13
+ `;if(process.stdout.write(n),ze!==void 0)try{Ds(ze,n)}catch{}}function De(e,n,t){D({phase:"exit",ok:e,reason:le(n),turnMs:t})}function Ks(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 Hs(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 Zs(e,n=Ue){let t=Lt({command:"node",argsPrefix:[Xt],kandanUrl:e.kandanUrl,authFilePath:bn,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return zt(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[t],...e.modelProvider===void 0?{}:{modelProvider:Ks(e.modelProvider)},env:{CODEX_HOME:n,...rr(e)}})}function rr(e){let n=process.env[yn.llmProxyToken];return e.modelProvider===void 0||n===void 0||n===""?{}:{[e.modelProvider.envKey]:n}}function Xs(e,n){let t=process.env[yn.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}),er(e,448),ke(n,t,{mode:384}),er(n,384)}function Ys(e){try{nr(e,{recursive:!0,force:!0})}catch{}}var Qs=64;function or(e){try{let n=JSON.parse(zs(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 ei(e,n,t){try{let r=or(e);delete r[n];let o=Object.entries(r),s=o.slice(Math.max(0,o.length-(Qs-1)));s.push([n,t]),ue(tr(e),{recursive:!0}),ke(e,JSON.stringify(Object.fromEntries(s)))}catch{}}var ni=new Set(["turn/completed","turn/failed","turn/aborted"]),ti=2e3;function sr(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:(pn(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,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
- `),rr(1)});
15
+ `)}function ri(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 oi=15e3;function si(e){return/already_replied|no_active_asker_binding/i.test(e)}async function ii(e){let n=e.body.trim();if(n==="")return"skipped";let t=hn(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(),oi);try{return await fetch(s,{...i,signal:a.signal})}finally{clearTimeout(c)}},o=mn({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(si(i))return"already";throw new Error(`reply relay failed: ${i}`)}}var ai=900,di=1e4,ci=3,li=8e3;function ui(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 fi(e){return async n=>{let t=hn(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(),di);try{return await fetch(s,{...i,signal:a.signal})}finally{clearTimeout(c)}};return mn({kandanUrl:e.kandanUrl,accessToken:t.accessToken,operatingMode:"text",fetchImpl:r}).agentTurnProgress(n)}}function pi(e){let n=Date.now,t=e.flushIntervalMs??ai,r=e.log??D,o=e.post??fi({kandanUrl:e.kandanUrl,mcpAuthPath:e.mcpAuthPath}),s=new Map,i=!1,a=0,c=0,d,f,p=!1,y=!1,u=(v,h)=>{let w=s.get(v);if(w!==void 0)return w;let k={kind:h,text:"",snapshotIndex:0,state:"streaming",dirty:!1,lastFlushMs:0,ackedState:void 0};return s.set(v,k),k},g=v=>v.state==="streaming"?v.lastFlushMs+t:0,l=async(v,h)=>{let w=h.text,k=h.state;h.dirty=!1,h.snapshotIndex+=1,h.lastFlushMs=n();try{return await o({stream_key:`${e.streamKeyPrefix}:${v}`,item_id:v,kind:h.kind,body:w,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 S=b instanceof Error?b.message:String(b);return ui(S)?(y=!0,i=!0,r({phase:"progress",outcome:"permanent_reject",message:le(S)}),!1):(r({phase:"progress",outcome:"post_failed",consecutive_failures:a,message:le(S)}),a>=ci&&(i=!0,r({phase:"progress",outcome:"disabled"})),!1)}},x=async()=>{for(;;){if(i)return;let v=n(),h,w=!1;for(let[k,b]of s){if(!b.dirty||b.text==="")continue;let S=g(b);S<=v?(await l(k,b),w=!0):h=h===void 0?S:Math.min(h,S)}if(!w){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:v=>{try{let h=A(v.params)??{};if(v.method==="item/agentMessage/delta"){let w=Gt(h);if(w!==void 0){let k=u(w.itemKey,"codex_assistant_message");k.text+=w.delta,k.dirty=!0,C()}return}if(v.method==="item/reasoning/textDelta"){let w=Bt(h);if(w!==void 0){let k=u(w.itemKey,"codex_reasoning");k.text+=w.delta,k.dirty=!0,C()}return}if(v.method==="item/completed"){let w=A(h.item),k=_(w?.type),b=_(w?.id);if(b===void 0)return;if(k==="agentMessage"){let S=sr(v.params),m=u(b,"codex_assistant_message");S!==""&&(m.text=S),m.state="completed",m.dirty=!0,C()}else if(k==="reasoning"){let S=s.get(b);S!==void 0&&(S.state="completed",S.dirty=!0,C())}}}catch(h){r({phase:"progress",outcome:"notification_error",message:le(h instanceof Error?h.message:String(h))})}},finish:async v=>{try{let h=n()+(e.finishDeadlineMs??li),w=()=>new Promise(b=>setTimeout(b,Math.max(0,h-n())).unref?.());p=!0,clearTimeout(f),d!==void 0&&await Promise.race([d,w()]);for(let b of s.values())b.state==="streaming"&&b.text!==""&&(b.state=v);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 S=!1;for(let[m,T]of b){if(y||n()>=h)break;await l(m,T)||(S=!0)}S&&!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:le(h instanceof Error?h.message:String(h))})}}}}function gi(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"approved"}}async function mi(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 Ft(e)}catch(r){if(Date.now()>=n)throw r;await new Promise(o=>setTimeout(o,qs))}}}var hi=360*60*1e3;function yi(e,n){try{for(let t of Fs(e))try{let r=Fe(e,t);n-Vs(r).mtimeMs>hi&&Gs(r)}catch{}}catch{}}function _i(e,n,t=Qt){wn(n);let r=Fe(e,`${n}.beat`),o=()=>{try{ke(r,`${Date.now()}
16
+ `)}catch{}};try{ue(e,{recursive:!0})}catch{}yi(e,Date.now()),o();let s=setInterval(o,t);return s.unref?.(),()=>{clearInterval(s);try{nr(r,{force:!0})}catch{}}}function xi(e,n,t){try{wn(n),ue(e,{recursive:!0}),ke(Fe(e,`${n}.exit`),`${JSON.stringify({phase:"exit",ok:t.ok,reason:le(t.reason),turnMs:t.turnMs})}
17
+ `)}catch{}}async function bi(e,n={}){let t=n.now??Date.now,r=n.secretsDir??xn,o=n.mcpAuthPath??bn,s=n.codexHome??Ue,i=n.threadMapPath??Yt,a=t();Hs(e);let c=e.turnNonce!==void 0&&e.turnNonce!==""?_i(n.heartbeatDir??vn,e.turnNonce,n.heartbeatIntervalMs):void 0,d,f=()=>{try{d?.pid!==void 0&&d.kill("SIGINT")}catch{}};try{Xs(r,o);let p=Zs(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):Us("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,...rr(e)},stdio:["ignore","ignore","inherit"],detached:!1});let u=await mi(y,a+Bs,d);try{u.onRequest?.(m=>gi(m.method));let g=e.codexThreadId,l;if(g!==void 0&&g!==""){let m=or(i)[g];m!==void 0&&("error"in await u.request("thread/resume",{threadId:m,...Wt({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!==""&&ei(i,g,l),D({phase:"thread",mode:"started"})}else D({phase:"thread",mode:"resumed"});let x="",C=!1,M=!1,J=pi({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}),v,h=new Promise((m,T)=>{v={resolve:m,reject:T}}),w=m=>{if(M){D({phase:"codex-exit",benign:!0});return}setTimeout(()=>{M||v?.reject(m())},n.postTerminalGraceMs??ti).unref?.()};u.onNotification(m=>{if(D({phase:"notification",method:m.method}),J.onNotification(m),m.method==="item/completed"){let K=sr(m.params);K!==""&&(x=K),ri(m.params)&&(C=!0)}if(!ni.has(m.method))return;M=!0;let T=m.method==="turn/completed";v?.resolve({ok:T,reason:m.method==="turn/completed"?"turn completed":`turn terminal: ${m.method}`,turnMs:t()-a})}),u.onClose?.(m=>w(()=>new Error(`codex connection closed before a turn terminal: ${m?.message??"connection closed"}`))),d?.once("exit",m=>w(()=>new Error(`codex app-server process exited mid-turn (code ${m})`)));let k=await u.request("turn/start",{threadId:l,input:e.input,...Kt({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 S=b;if(b.ok){let m=n.relayReply??ii;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&&(S={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 K=T instanceof Error?T.message:String(T);D({phase:"reply",relay:"failed",reason:K}),S={ok:!1,reason:K,turnMs:b.turnMs}}}return await J.finish(S.ok?"completed":"failed"),S}finally{u.close()}}finally{c?.(),f(),Ys(r)}}async function ir(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 De(!1,"missing turn config argv[2]",0),1;let r;try{r=Zt(t)}catch(a){return De(!1,`config decode failed: ${a instanceof Error?a.message:String(a)}`,0),1}let o=n.heartbeatDir??vn;Ws(Fe(o,"last-turn.debug.jsonl")),D({phase:"boot",turn_nonce:r.turnNonce??null,node:process.version});let s=n.runTurn??bi,i=a=>{r.turnNonce!==void 0&&r.turnNonce!==""&&xi(o,r.turnNonce,a)};try{let a=await s(r);return i(a),De(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}),De(!1,c,0),1}}function ar(e){let n=!1,t=()=>{n||(n=!0,process.exit(e))};try{process.stdout.write("",t)}catch{t()}setTimeout(t,1e3).unref?.()}ir(process.argv).then(e=>{ar(e)}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
18
+ `),ar(1)});