@vibelet/cli 0.1.16 → 0.1.18

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/dist/index.cjs CHANGED
@@ -1,28 +1,28 @@
1
- "use strict";var hu=Object.create;var gi=Object.defineProperty;var gu=Object.getOwnPropertyDescriptor;var mu=Object.getOwnPropertyNames;var yu=Object.getPrototypeOf,Su=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mu(e))!Su.call(t,s)&&s!==n&&gi(t,s,{get:()=>e[s],enumerable:!(r=gu(e,s))||r.enumerable});return t};var Ve=(t,e,n)=>(n=t!=null?hu(yu(t)):{},vu(e||!t||!t.__esModule?gi(n,"default",{value:t,enumerable:!0}):n,t));var de=y((Tm,Si)=>{"use strict";var mi=["nodebuffer","arraybuffer","fragments"],yi=typeof Blob<"u";yi&&mi.push("blob");Si.exports={BINARY_TYPES:mi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ct=y((km,gn)=>{"use strict";var{EMPTY_BUFFER:_u}=de(),Sr=Buffer[Symbol.species];function bu(t,e){if(t.length===0)return _u;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Sr(n.buffer,n.byteOffset,r):n}function vi(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function _i(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function wu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function vr(t){if(vr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Sr(t):ArrayBuffer.isView(t)?e=new Sr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vr.readOnly=!1),e}gn.exports={concat:bu,mask:vi,toArrayBuffer:wu,toBuffer:vr,unmask:_i};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");gn.exports.mask=function(e,n,r,s,i){i<48?vi(e,n,r,s,i):t.mask(e,n,r,s,i)},gn.exports.unmask=function(e,n){e.length<32?_i(e,n):t.unmask(e,n)}}catch{}});var Ii=y((Em,wi)=>{"use strict";var bi=Symbol("kDone"),_r=Symbol("kRun"),br=class{constructor(e){this[bi]=()=>{this.pending--,this[_r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[_r]()}[_r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bi])}}};wi.exports=br});var Rt=y((Cm,ki)=>{"use strict";var Pt=require("zlib"),Ai=Ct(),Iu=Ii(),{kStatusCode:xi}=de(),Au=Buffer[Symbol.species],xu=Buffer.from([0,0,255,255]),yn=Symbol("permessage-deflate"),fe=Symbol("total-length"),Ye=Symbol("callback"),ye=Symbol("buffers"),Je=Symbol("error"),mn,wr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!mn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;mn=new Iu(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ye];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){mn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){mn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Pt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Pt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[yn]=this,this._inflate[fe]=0,this._inflate[ye]=[],this._inflate.on("error",ku),this._inflate.on("data",Ti)}this._inflate[Ye]=r,this._inflate.write(e),n&&this._inflate.write(xu),this._inflate.flush(()=>{let i=this._inflate[Je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Ai.concat(this._inflate[ye],this._inflate[fe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fe]=0,this._inflate[ye]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Pt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Pt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[fe]=0,this._deflate[ye]=[],this._deflate.on("data",Tu)}this._deflate[Ye]=r,this._deflate.write(e),this._deflate.flush(Pt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ai.concat(this._deflate[ye],this._deflate[fe]);n&&(i=new Au(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ye]=null,this._deflate[fe]=0,this._deflate[ye]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ki.exports=wr;function Tu(t){this[ye].push(t),this[fe]+=t.length}function Ti(t){if(this[fe]+=t.length,this[yn]._maxPayload<1||this[fe]<=this[yn]._maxPayload){this[ye].push(t);return}this[Je]=new RangeError("Max payload size exceeded"),this[Je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Je][xi]=1009,this.removeListener("data",Ti),this.reset()}function ku(t){if(this[yn]._inflate=null,this[Je]){this[Ye](this[Je]);return}t[xi]=1007,this[Ye](t)}});var Ke=y((Pm,Sn)=>{"use strict";var{isUtf8:Ei}=require("buffer"),{hasBlob:Eu}=de(),Cu=[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 Pu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ir(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Ru(t){return Eu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Sn.exports={isBlob:Ru,isValidStatusCode:Pu,isValidUTF8:Ir,tokenChars:Cu};if(Ei)Sn.exports.isValidUTF8=function(t){return t.length<24?Ir(t):Ei(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Sn.exports.isValidUTF8=function(e){return e.length<32?Ir(e):t(e)}}catch{}});var Er=y((Rm,Oi)=>{"use strict";var{Writable:Lu}=require("stream"),Ci=Rt(),{BINARY_TYPES:Mu,EMPTY_BUFFER:Pi,kStatusCode:Nu,kWebSocket:Ou}=de(),{concat:Ar,toArrayBuffer:Bu,unmask:Du}=Ct(),{isValidStatusCode:Hu,isValidUTF8:Ri}=Ke(),vn=Buffer[Symbol.species],X=0,Li=1,Mi=2,Ni=3,xr=4,Tr=5,_n=6,kr=class extends Lu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Mu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ou]=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=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new vn(r.buffer,r.byteOffset+e,r.length-e),new vn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new vn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case Li:this.getPayloadLength16(e);break;case Mi:this.getPayloadLength64(e);break;case Ni:this.getMask();break;case xr:this.getData(e);break;case Tr:case _n:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Ci.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Li:this._payloadLength===127?this._state=Mi:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Ni:this._state=xr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=xr}getData(e){let n=Pi;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Du(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Tr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Ci.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ar(r,n):this._binaryType==="arraybuffer"?s=Bu(Ar(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=_n,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Ar(r,n);if(!this._skipUTF8Validation&&!Ri(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Tr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=_n,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Pi),this.end();else{let r=e.readUInt16BE(0);if(!Hu(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new vn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ri(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=_n,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Nu]=s,o}};Oi.exports=kr});var Rr=y((Mm,Hi)=>{"use strict";var{Duplex:Lm}=require("stream"),{randomFillSync:Fu}=require("crypto"),Bi=Rt(),{EMPTY_BUFFER:Uu,kWebSocket:qu,NOOP:ju}=de(),{isBlob:Xe,isValidStatusCode:Wu}=Ke(),{mask:Di,toBuffer:Le}=Ct(),Q=Symbol("kByteLength"),Gu=Buffer.alloc(4),bn=8*1024,Me,Qe=bn,ne=0,$u=1,zu=2,Cr=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ne,this.onerror=ju,this[qu]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Gu,n.generateMask?n.generateMask(r):(Qe===bn&&(Me===void 0&&(Me=Buffer.alloc(bn)),Fu(Me,0,bn),Qe=0),r[0]=Me[Qe++],r[1]=Me[Qe++],r[2]=Me[Qe++],r[3]=Me[Qe++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Q]!==void 0?a=n[Q]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Di(e,r,c,i,a),[c]):(Di(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Uu;else{if(typeof e!="number"||!Wu(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Q]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ne?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Q]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Xe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Q]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Xe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Bi.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Xe(e)?(a=e.size,l=!1):(e=Le(e),a=e.length,l=Le.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Q]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Xe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ne?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Q],this._state=zu,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Pr,this,a,s);return}this._bufferedBytes-=r[Q];let o=Le(i);n?this.dispatch(o,n,r,s):(this._state=ne,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Vu,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Bi.extensionName];this._bufferedBytes+=r[Q],this._state=$u,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Pr(this,l,s);return}this._bufferedBytes-=r[Q],this._state=ne,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ne&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Q],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Q],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Hi.exports=Cr;function Pr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Vu(t,e,n){Pr(t,e,n),t.onerror(e)}});var Vi=y((Nm,zi)=>{"use strict";var{kForOnEventAttribute:Lt,kListener:Lr}=de(),Fi=Symbol("kCode"),Ui=Symbol("kData"),qi=Symbol("kError"),ji=Symbol("kMessage"),Wi=Symbol("kReason"),Ze=Symbol("kTarget"),Gi=Symbol("kType"),$i=Symbol("kWasClean"),pe=class{constructor(e){this[Ze]=null,this[Gi]=e}get target(){return this[Ze]}get type(){return this[Gi]}};Object.defineProperty(pe.prototype,"target",{enumerable:!0});Object.defineProperty(pe.prototype,"type",{enumerable:!0});var Ne=class extends pe{constructor(e,n={}){super(e),this[Fi]=n.code===void 0?0:n.code,this[Wi]=n.reason===void 0?"":n.reason,this[$i]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Fi]}get reason(){return this[Wi]}get wasClean(){return this[$i]}};Object.defineProperty(Ne.prototype,"code",{enumerable:!0});Object.defineProperty(Ne.prototype,"reason",{enumerable:!0});Object.defineProperty(Ne.prototype,"wasClean",{enumerable:!0});var et=class extends pe{constructor(e,n={}){super(e),this[qi]=n.error===void 0?null:n.error,this[ji]=n.message===void 0?"":n.message}get error(){return this[qi]}get message(){return this[ji]}};Object.defineProperty(et.prototype,"error",{enumerable:!0});Object.defineProperty(et.prototype,"message",{enumerable:!0});var Mt=class extends pe{constructor(e,n={}){super(e),this[Ui]=n.data===void 0?null:n.data}get data(){return this[Ui]}};Object.defineProperty(Mt.prototype,"data",{enumerable:!0});var Yu={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Lt]&&s[Lr]===e&&!s[Lt])return;let r;if(t==="message")r=function(i,o){let a=new Mt("message",{data:o?i:i.toString()});a[Ze]=this,wn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ne("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ze]=this,wn(e,this,a)};else if(t==="error")r=function(i){let o=new et("error",{error:i,message:i.message});o[Ze]=this,wn(e,this,o)};else if(t==="open")r=function(){let i=new pe("open");i[Ze]=this,wn(e,this,i)};else return;r[Lt]=!!n[Lt],r[Lr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Lr]===e&&!n[Lt]){this.removeListener(t,n);break}}};zi.exports={CloseEvent:Ne,ErrorEvent:et,Event:pe,EventTarget:Yu,MessageEvent:Mt};function wn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Mr=y((Om,Yi)=>{"use strict";var{tokenChars:Nt}=Ke();function ae(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Ju(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Nt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);c===44?(ae(e,p,n),n=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Nt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),ae(n,t.slice(l,u),!0),c===44&&(ae(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Nt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Nt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Nt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),ae(n,a,p),c===44&&(ae(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?ae(e,f,n):(a===void 0?ae(n,f,!0):r?ae(n,a,f.replace(/\\/g,"")):ae(n,a,f),ae(e,o,n)),e}function Ku(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Yi.exports={format:Ku,parse:Ju}});var Tn=y((Hm,oo)=>{"use strict";var Xu=require("events"),Qu=require("https"),Zu=require("http"),Xi=require("net"),ed=require("tls"),{randomBytes:td,createHash:nd}=require("crypto"),{Duplex:Bm,Readable:Dm}=require("stream"),{URL:Nr}=require("url"),Se=Rt(),rd=Er(),sd=Rr(),{isBlob:id}=Ke(),{BINARY_TYPES:Ji,CLOSE_TIMEOUT:od,EMPTY_BUFFER:In,GUID:ad,kForOnEventAttribute:Or,kListener:ld,kStatusCode:cd,kWebSocket:B,NOOP:Qi}=de(),{EventTarget:{addEventListener:ud,removeEventListener:dd}}=Vi(),{format:fd,parse:pd}=Mr(),{toBuffer:hd}=Ct(),Zi=Symbol("kAborted"),Br=[8,13],he=["CONNECTING","OPEN","CLOSING","CLOSED"],gd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends Xu{constructor(e,n,r){super(),this._binaryType=Ji[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=In,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),eo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ji.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new rd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new sd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[B]=this,i[B]=this,e[B]=this,s.on("conclude",Sd),s.on("drain",vd),s.on("error",_d),s.on("message",bd),s.on("ping",wd),s.on("pong",Id),i.onerror=Ad,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ro),e.on("data",xn),e.on("end",so),e.on("error",io),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Se.extensionName]&&this._extensions[Se.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){V(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),no(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||In,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||In,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Se.extensionName]||(s.compress=!1),this._sender.send(e||In,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){V(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(T,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(T.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(T.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Or])return e[ld];return null},set(e){for(let n of this.listeners(t))if(n[Or]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Or]:!0})}})});T.prototype.addEventListener=ud;T.prototype.removeEventListener=dd;oo.exports=T;function eo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:od,protocolVersion:Br[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(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Br.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Br.join(", ")})`);let i;if(e instanceof Nr)i=e;else try{i=new Nr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let g=new SyntaxError(l);if(t._redirects===0)throw g;An(t,g);return}let c=o?443:80,u=td(16).toString("base64"),d=o?Qu.request:Zu.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?yd:md),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Se(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=fd({[Se.extensionName]:p.offer()})),n.length){for(let g of n){if(typeof g!="string"||!gd.test(g)||f.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(g)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[m,S]of Object.entries(g))r.headers[m.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=d(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=d(s);s.timeout&&h.on("timeout",()=>{V(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[Zi]||(h=t._req=null,An(t,g))}),h.on("response",g=>{let m=g.headers.location,S=g.statusCode;if(m&&s.followRedirects&&S>=300&&S<400){if(++t._redirects>s.maxRedirects){V(t,h,"Maximum redirects exceeded");return}h.abort();let P;try{P=new Nr(m,e)}catch{let E=new SyntaxError(`Invalid URL: ${m}`);An(t,E);return}eo(t,P,n,r)}else t.emit("unexpected-response",h,g)||V(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,m,S)=>{if(t.emit("upgrade",g),t.readyState!==T.CONNECTING)return;h=t._req=null;let P=g.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){V(t,m,"Invalid Upgrade header");return}let ie=nd("sha1").update(u+ad).digest("base64");if(g.headers["sec-websocket-accept"]!==ie){V(t,m,"Invalid Sec-WebSocket-Accept header");return}let E=g.headers["sec-websocket-protocol"],O;if(E!==void 0?f.size?f.has(E)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":f.size&&(O="Server sent no subprotocol"),O){V(t,m,O);return}E&&(t._protocol=E);let K=g.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){V(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let oe;try{oe=pd(K)}catch{V(t,m,"Invalid Sec-WebSocket-Extensions header");return}let ze=Object.keys(oe);if(ze.length!==1||ze[0]!==Se.extensionName){V(t,m,"Server indicated an extension that was not requested");return}try{p.accept(oe[Se.extensionName])}catch{V(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Se.extensionName]=p}t.setSocket(m,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function An(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function md(t){return t.path=t.socketPath,Xi.connect(t)}function yd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Xi.isIP(t.host)?"":t.host),ed.connect(t)}function V(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,V),e.setHeader?(e[Zi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(An,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Dr(t,e,n){if(e){let r=id(e)?e.size:hd(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${he[t.readyState]})`);process.nextTick(n,r)}}function Sd(t,e){let n=this[B];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[B]!==void 0&&(n._socket.removeListener("data",xn),process.nextTick(to,n._socket),t===1005?n.close():n.close(t,e))}function vd(){let t=this[B];t.isPaused||t._socket.resume()}function _d(t){let e=this[B];e._socket[B]!==void 0&&(e._socket.removeListener("data",xn),process.nextTick(to,e._socket),e.close(t[cd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ki(){this[B].emitClose()}function bd(t,e){this[B].emit("message",t,e)}function wd(t){let e=this[B];e._autoPong&&e.pong(t,!this._isServer,Qi),e.emit("ping",t)}function Id(t){this[B].emit("pong",t)}function to(t){t.resume()}function Ad(t){let e=this[B];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,no(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function no(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ro(){let t=this[B];if(this.removeListener("close",ro),this.removeListener("data",xn),this.removeListener("end",so),t._readyState=T.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[B]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ki),t._receiver.on("finish",Ki))}function xn(t){this[B]._receiver.write(t)||this.pause()}function so(){let t=this[B];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function io(){let t=this[B];this.removeListener("error",io),this.on("error",Qi),t&&(t._readyState=T.CLOSING,this.destroy())}});var uo=y((Um,co)=>{"use strict";var Fm=Tn(),{Duplex:xd}=require("stream");function ao(t){t.emit("close")}function Td(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lo(t){this.removeListener("error",lo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function kd(t,e){let n=!0,r=new xd({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(ao,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(ao,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Td),r.on("error",lo),r}co.exports=kd});var po=y((qm,fo)=>{"use strict";var{tokenChars:Ed}=Ke();function Cd(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Ed[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}fo.exports={parse:Cd}});var _o=y((Wm,vo)=>{"use strict";var Pd=require("events"),kn=require("http"),{Duplex:jm}=require("stream"),{createHash:Rd}=require("crypto"),ho=Mr(),Oe=Rt(),Ld=po(),Md=Tn(),{CLOSE_TIMEOUT:Nd,GUID:Od,kWebSocket:Bd}=de(),Dd=/^[+/0-9A-Za-z]{22}==$/,go=0,mo=1,So=2,Hr=class extends Pd{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Nd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Md,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=kn.createServer((r,s)=>{let i=kn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Hd(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=go}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===So){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ot,this);return}if(e&&this.once("close",e),this._state!==mo)if(this._state=mo,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(Ot,this):process.nextTick(Ot,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ot(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",yo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Be(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Be(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Dd.test(i)){Be(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Be(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Bt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ld.parse(l)}catch{Be(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Oe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=ho.parse(u);p[Oe.extensionName]&&(f.accept(p[Oe.extensionName]),d[Oe.extensionName]=f)}catch{Be(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,h,g,m)=>{if(!p)return Bt(n,h||401,g,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Bt(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Bd])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>go)return Bt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Rd("sha1").update(n+Od).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Oe.extensionName]){let d=e[Oe.extensionName].params,f=ho.format({[Oe.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
1
+ "use strict";var yu=Object.create;var mi=Object.defineProperty;var Su=Object.getOwnPropertyDescriptor;var vu=Object.getOwnPropertyNames;var _u=Object.getPrototypeOf,bu=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var wu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vu(e))!bu.call(t,s)&&s!==n&&mi(t,s,{get:()=>e[s],enumerable:!(r=Su(e,s))||r.enumerable});return t};var Ye=(t,e,n)=>(n=t!=null?yu(_u(t)):{},wu(e||!t||!t.__esModule?mi(n,"default",{value:t,enumerable:!0}):n,t));var fe=y((Cm,vi)=>{"use strict";var yi=["nodebuffer","arraybuffer","fragments"],Si=typeof Blob<"u";Si&&yi.push("blob");vi.exports={BINARY_TYPES:yi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Si,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Rt=y((Pm,yn)=>{"use strict";var{EMPTY_BUFFER:Iu}=fe(),vr=Buffer[Symbol.species];function Au(t,e){if(t.length===0)return Iu;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new vr(n.buffer,n.byteOffset,r):n}function _i(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function bi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function xu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function _r(t){if(_r.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new vr(t):ArrayBuffer.isView(t)?e=new vr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),_r.readOnly=!1),e}yn.exports={concat:Au,mask:_i,toArrayBuffer:xu,toBuffer:_r,unmask:bi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");yn.exports.mask=function(e,n,r,s,i){i<48?_i(e,n,r,s,i):t.mask(e,n,r,s,i)},yn.exports.unmask=function(e,n){e.length<32?bi(e,n):t.unmask(e,n)}}catch{}});var Ai=y((Rm,Ii)=>{"use strict";var wi=Symbol("kDone"),br=Symbol("kRun"),wr=class{constructor(e){this[wi]=()=>{this.pending--,this[br]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[br]()}[br](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wi])}}};Ii.exports=wr});var Mt=y((Lm,Ei)=>{"use strict";var Lt=require("zlib"),xi=Rt(),Tu=Ai(),{kStatusCode:Ti}=fe(),ku=Buffer[Symbol.species],Eu=Buffer.from([0,0,255,255]),vn=Symbol("permessage-deflate"),pe=Symbol("total-length"),Je=Symbol("callback"),Se=Symbol("buffers"),Ke=Symbol("error"),Sn,Ir=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Sn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Sn=new Tu(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Je];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Sn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Sn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Lt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Lt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[vn]=this,this._inflate[pe]=0,this._inflate[Se]=[],this._inflate.on("error",Pu),this._inflate.on("data",ki)}this._inflate[Je]=r,this._inflate.write(e),n&&this._inflate.write(Eu),this._inflate.flush(()=>{let i=this._inflate[Ke];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=xi.concat(this._inflate[Se],this._inflate[pe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pe]=0,this._inflate[Se]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Lt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Lt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[pe]=0,this._deflate[Se]=[],this._deflate.on("data",Cu)}this._deflate[Je]=r,this._deflate.write(e),this._deflate.flush(Lt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=xi.concat(this._deflate[Se],this._deflate[pe]);n&&(i=new ku(i.buffer,i.byteOffset,i.length-4)),this._deflate[Je]=null,this._deflate[pe]=0,this._deflate[Se]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ei.exports=Ir;function Cu(t){this[Se].push(t),this[pe]+=t.length}function ki(t){if(this[pe]+=t.length,this[vn]._maxPayload<1||this[pe]<=this[vn]._maxPayload){this[Se].push(t);return}this[Ke]=new RangeError("Max payload size exceeded"),this[Ke].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ke][Ti]=1009,this.removeListener("data",ki),this.reset()}function Pu(t){if(this[vn]._inflate=null,this[Ke]){this[Je](this[Ke]);return}t[Ti]=1007,this[Je](t)}});var Xe=y((Mm,_n)=>{"use strict";var{isUtf8:Ci}=require("buffer"),{hasBlob:Ru}=fe(),Lu=[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 Mu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ar(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Nu(t){return Ru&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}_n.exports={isBlob:Nu,isValidStatusCode:Mu,isValidUTF8:Ar,tokenChars:Lu};if(Ci)_n.exports.isValidUTF8=function(t){return t.length<24?Ar(t):Ci(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");_n.exports.isValidUTF8=function(e){return e.length<32?Ar(e):t(e)}}catch{}});var Cr=y((Nm,Bi)=>{"use strict";var{Writable:Ou}=require("stream"),Pi=Mt(),{BINARY_TYPES:Bu,EMPTY_BUFFER:Ri,kStatusCode:Du,kWebSocket:Hu}=fe(),{concat:xr,toArrayBuffer:Fu,unmask:Uu}=Rt(),{isValidStatusCode:qu,isValidUTF8:Li}=Xe(),bn=Buffer[Symbol.species],X=0,Mi=1,Ni=2,Oi=3,Tr=4,kr=5,wn=6,Er=class extends Ou{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Bu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Hu]=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=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new bn(r.buffer,r.byteOffset+e,r.length-e),new bn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new bn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case Mi:this.getPayloadLength16(e);break;case Ni:this.getPayloadLength64(e);break;case Oi:this.getMask();break;case Tr:this.getData(e);break;case kr:case wn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Pi.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Mi:this._payloadLength===127?this._state=Ni:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Oi:this._state=Tr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Tr}getData(e){let n=Ri;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Uu(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=kr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Pi.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=xr(r,n):this._binaryType==="arraybuffer"?s=Fu(xr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=wn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=xr(r,n);if(!this._skipUTF8Validation&&!Li(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===kr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=wn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ri),this.end();else{let r=e.readUInt16BE(0);if(!qu(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new bn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Li(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=wn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Du]=s,o}};Bi.exports=Er});var Lr=y((Bm,Fi)=>{"use strict";var{Duplex:Om}=require("stream"),{randomFillSync:ju}=require("crypto"),Di=Mt(),{EMPTY_BUFFER:Wu,kWebSocket:$u,NOOP:Gu}=fe(),{isBlob:Ze,isValidStatusCode:zu}=Xe(),{mask:Hi,toBuffer:Me}=Rt(),Z=Symbol("kByteLength"),Vu=Buffer.alloc(4),In=8*1024,Ne,Qe=In,ne=0,Yu=1,Ju=2,Pr=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ne,this.onerror=Gu,this[$u]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Vu,n.generateMask?n.generateMask(r):(Qe===In&&(Ne===void 0&&(Ne=Buffer.alloc(In)),ju(Ne,0,In),Qe=0),r[0]=Ne[Qe++],r[1]=Ne[Qe++],r[2]=Ne[Qe++],r[3]=Ne[Qe++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Hi(e,r,c,i,a),[c]):(Hi(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Wu;else{if(typeof e!="number"||!zu(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ne?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ze(e)?(s=e.size,i=!1):(e=Me(e),s=e.length,i=Me.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ze(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ze(e)?(s=e.size,i=!1):(e=Me(e),s=e.length,i=Me.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ze(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Di.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Ze(e)?(a=e.size,l=!1):(e=Me(e),a=e.length,l=Me.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Ze(e)?this._state!==ne?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ne?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=Ju,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Rr,this,a,s);return}this._bufferedBytes-=r[Z];let o=Me(i);n?this.dispatch(o,n,r,s):(this._state=ne,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ku,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Di.extensionName];this._bufferedBytes+=r[Z],this._state=Yu,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Rr(this,l,s);return}this._bufferedBytes-=r[Z],this._state=ne,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ne&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Fi.exports=Pr;function Rr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ku(t,e,n){Rr(t,e,n),t.onerror(e)}});var Yi=y((Dm,Vi)=>{"use strict";var{kForOnEventAttribute:Nt,kListener:Mr}=fe(),Ui=Symbol("kCode"),qi=Symbol("kData"),ji=Symbol("kError"),Wi=Symbol("kMessage"),$i=Symbol("kReason"),et=Symbol("kTarget"),Gi=Symbol("kType"),zi=Symbol("kWasClean"),he=class{constructor(e){this[et]=null,this[Gi]=e}get target(){return this[et]}get type(){return this[Gi]}};Object.defineProperty(he.prototype,"target",{enumerable:!0});Object.defineProperty(he.prototype,"type",{enumerable:!0});var Oe=class extends he{constructor(e,n={}){super(e),this[Ui]=n.code===void 0?0:n.code,this[$i]=n.reason===void 0?"":n.reason,this[zi]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ui]}get reason(){return this[$i]}get wasClean(){return this[zi]}};Object.defineProperty(Oe.prototype,"code",{enumerable:!0});Object.defineProperty(Oe.prototype,"reason",{enumerable:!0});Object.defineProperty(Oe.prototype,"wasClean",{enumerable:!0});var tt=class extends he{constructor(e,n={}){super(e),this[ji]=n.error===void 0?null:n.error,this[Wi]=n.message===void 0?"":n.message}get error(){return this[ji]}get message(){return this[Wi]}};Object.defineProperty(tt.prototype,"error",{enumerable:!0});Object.defineProperty(tt.prototype,"message",{enumerable:!0});var Ot=class extends he{constructor(e,n={}){super(e),this[qi]=n.data===void 0?null:n.data}get data(){return this[qi]}};Object.defineProperty(Ot.prototype,"data",{enumerable:!0});var Xu={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Nt]&&s[Mr]===e&&!s[Nt])return;let r;if(t==="message")r=function(i,o){let a=new Ot("message",{data:o?i:i.toString()});a[et]=this,An(e,this,a)};else if(t==="close")r=function(i,o){let a=new Oe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[et]=this,An(e,this,a)};else if(t==="error")r=function(i){let o=new tt("error",{error:i,message:i.message});o[et]=this,An(e,this,o)};else if(t==="open")r=function(){let i=new he("open");i[et]=this,An(e,this,i)};else return;r[Nt]=!!n[Nt],r[Mr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Mr]===e&&!n[Nt]){this.removeListener(t,n);break}}};Vi.exports={CloseEvent:Oe,ErrorEvent:tt,Event:he,EventTarget:Xu,MessageEvent:Ot};function An(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Nr=y((Hm,Ji)=>{"use strict";var{tokenChars:Bt}=Xe();function le(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Zu(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Bt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);c===44?(le(e,p,n),n=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Bt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),le(n,t.slice(l,u),!0),c===44&&(le(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Bt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Bt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Bt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),le(n,a,p),c===44&&(le(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?le(e,f,n):(a===void 0?le(n,f,!0):r?le(n,a,f.replace(/\\/g,"")):le(n,a,f),le(e,o,n)),e}function Qu(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ji.exports={format:Qu,parse:Zu}});var En=y((qm,ao)=>{"use strict";var ed=require("events"),td=require("https"),nd=require("http"),Zi=require("net"),rd=require("tls"),{randomBytes:sd,createHash:id}=require("crypto"),{Duplex:Fm,Readable:Um}=require("stream"),{URL:Or}=require("url"),ve=Mt(),od=Cr(),ad=Lr(),{isBlob:ld}=Xe(),{BINARY_TYPES:Ki,CLOSE_TIMEOUT:cd,EMPTY_BUFFER:xn,GUID:ud,kForOnEventAttribute:Br,kListener:dd,kStatusCode:fd,kWebSocket:D,NOOP:Qi}=fe(),{EventTarget:{addEventListener:pd,removeEventListener:hd}}=Yi(),{format:gd,parse:md}=Nr(),{toBuffer:yd}=Rt(),eo=Symbol("kAborted"),Dr=[8,13],ge=["CONNECTING","OPEN","CLOSING","CLOSED"],Sd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends ed{constructor(e,n,r){super(),this._binaryType=Ki[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),to(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ki.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new od({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new ad(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[D]=this,i[D]=this,e[D]=this,s.on("conclude",bd),s.on("drain",wd),s.on("error",Id),s.on("message",Ad),s.on("ping",xd),s.on("pong",Td),i.onerror=kd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",so),e.on("data",kn),e.on("end",io),e.on("error",oo),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ve.extensionName]&&this._extensions[ve.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ro(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||xn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||xn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[ve.extensionName]||(s.compress=!1),this._sender.send(e||xn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(T,"CONNECTING",{enumerable:!0,value:ge.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:ge.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:ge.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:ge.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:ge.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:ge.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:ge.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:ge.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(T.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(T.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Br])return e[dd];return null},set(e){for(let n of this.listeners(t))if(n[Br]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Br]:!0})}})});T.prototype.addEventListener=pd;T.prototype.removeEventListener=hd;ao.exports=T;function to(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:cd,protocolVersion:Dr[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(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Dr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Dr.join(", ")})`);let i;if(e instanceof Or)i=e;else try{i=new Or(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let g=new SyntaxError(l);if(t._redirects===0)throw g;Tn(t,g);return}let c=o?443:80,u=sd(16).toString("base64"),d=o?td.request:nd.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?_d:vd),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new ve(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=gd({[ve.extensionName]:p.offer()})),n.length){for(let g of n){if(typeof g!="string"||!Sd.test(g)||f.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(g)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[m,S]of Object.entries(g))r.headers[m.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=d(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=d(s);s.timeout&&h.on("timeout",()=>{Y(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[eo]||(h=t._req=null,Tn(t,g))}),h.on("response",g=>{let m=g.headers.location,S=g.statusCode;if(m&&s.followRedirects&&S>=300&&S<400){if(++t._redirects>s.maxRedirects){Y(t,h,"Maximum redirects exceeded");return}h.abort();let P;try{P=new Or(m,e)}catch{let E=new SyntaxError(`Invalid URL: ${m}`);Tn(t,E);return}to(t,P,n,r)}else t.emit("unexpected-response",h,g)||Y(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,m,S)=>{if(t.emit("upgrade",g),t.readyState!==T.CONNECTING)return;h=t._req=null;let P=g.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){Y(t,m,"Invalid Upgrade header");return}let oe=id("sha1").update(u+ud).digest("base64");if(g.headers["sec-websocket-accept"]!==oe){Y(t,m,"Invalid Sec-WebSocket-Accept header");return}let E=g.headers["sec-websocket-protocol"],B;if(E!==void 0?f.size?f.has(E)||(B="Server sent an invalid subprotocol"):B="Server sent a subprotocol but none was requested":f.size&&(B="Server sent no subprotocol"),B){Y(t,m,B);return}E&&(t._protocol=E);let K=g.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){Y(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=md(K)}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}let Ve=Object.keys(ae);if(Ve.length!==1||Ve[0]!==ve.extensionName){Y(t,m,"Server indicated an extension that was not requested");return}try{p.accept(ae[ve.extensionName])}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ve.extensionName]=p}t.setSocket(m,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function Tn(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function vd(t){return t.path=t.socketPath,Zi.connect(t)}function _d(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Zi.isIP(t.host)?"":t.host),rd.connect(t)}function Y(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[eo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Tn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Hr(t,e,n){if(e){let r=ld(e)?e.size:yd(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ge[t.readyState]})`);process.nextTick(n,r)}}function bd(t,e){let n=this[D];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[D]!==void 0&&(n._socket.removeListener("data",kn),process.nextTick(no,n._socket),t===1005?n.close():n.close(t,e))}function wd(){let t=this[D];t.isPaused||t._socket.resume()}function Id(t){let e=this[D];e._socket[D]!==void 0&&(e._socket.removeListener("data",kn),process.nextTick(no,e._socket),e.close(t[fd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Xi(){this[D].emitClose()}function Ad(t,e){this[D].emit("message",t,e)}function xd(t){let e=this[D];e._autoPong&&e.pong(t,!this._isServer,Qi),e.emit("ping",t)}function Td(t){this[D].emit("pong",t)}function no(t){t.resume()}function kd(t){let e=this[D];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,ro(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ro(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function so(){let t=this[D];if(this.removeListener("close",so),this.removeListener("data",kn),this.removeListener("end",io),t._readyState=T.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[D]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Xi),t._receiver.on("finish",Xi))}function kn(t){this[D]._receiver.write(t)||this.pause()}function io(){let t=this[D];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function oo(){let t=this[D];this.removeListener("error",oo),this.on("error",Qi),t&&(t._readyState=T.CLOSING,this.destroy())}});var fo=y((Wm,uo)=>{"use strict";var jm=En(),{Duplex:Ed}=require("stream");function lo(t){t.emit("close")}function Cd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function co(t){this.removeListener("error",co),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Pd(t,e){let n=!0,r=new Ed({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(lo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(lo,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Cd),r.on("error",co),r}uo.exports=Pd});var ho=y(($m,po)=>{"use strict";var{tokenChars:Rd}=Xe();function Ld(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Rd[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}po.exports={parse:Ld}});var bo=y((zm,_o)=>{"use strict";var Md=require("events"),Cn=require("http"),{Duplex:Gm}=require("stream"),{createHash:Nd}=require("crypto"),go=Nr(),Be=Mt(),Od=ho(),Bd=En(),{CLOSE_TIMEOUT:Dd,GUID:Hd,kWebSocket:Fd}=fe(),Ud=/^[+/0-9A-Za-z]{22}==$/,mo=0,yo=1,vo=2,Fr=class extends Md{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Dd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Bd,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Cn.createServer((r,s)=>{let i=Cn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=qd(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=mo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===vo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Dt,this);return}if(e&&this.once("close",e),this._state!==yo)if(this._state=yo,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(Dt,this):process.nextTick(Dt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Dt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",So);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){De(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){De(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Ud.test(i)){De(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){De(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ht(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Od.parse(l)}catch{De(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Be(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=go.parse(u);p[Be.extensionName]&&(f.accept(p[Be.extensionName]),d[Be.extensionName]=f)}catch{De(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,h,g,m)=>{if(!p)return Ht(n,h||401,g,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Ht(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Fd])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>mo)return Ht(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Nd("sha1").update(n+Hd).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Be.extensionName]){let d=e[Be.extensionName].params,f=go.format({[Be.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",yo),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ot,this)})),a(u,s)}};vo.exports=Hr;function Hd(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Ot(t){t._state=So,t.emit("close")}function yo(){this.destroy()}function Bt(t,e,n,r){n=n||kn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${kn.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",So),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Dt,this)})),a(u,s)}};_o.exports=Fr;function qd(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Dt(t){t._state=vo,t.emit("close")}function So(){this.destroy()}function Ht(t,e,n,r){n=n||Cn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Cn.STATUS_CODES[e]}\r
4
4
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function Be(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Be),t.emit("wsClientError",o,n,e)}else Bt(n,r,s,i)}});var Ur=y(($m,bo)=>{bo.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ve=y(De=>{var qr,Wd=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];De.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};De.getSymbolTotalCodewords=function(e){return Wd[e]};De.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};De.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');qr=e};De.isKanjiModeEnabled=function(){return typeof qr<"u"};De.toSJIS=function(e){return qr(e)}});var En=y(Z=>{Z.L={bit:1};Z.M={bit:0};Z.Q={bit:3};Z.H={bit:2};function Gd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return Z.L;case"m":case"medium":return Z.M;case"q":case"quartile":return Z.Q;case"h":case"high":return Z.H;default:throw new Error("Unknown EC Level: "+t)}}Z.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};Z.from=function(e,n){if(Z.isValid(e))return e;try{return Gd(e)}catch{return n}}});var Ao=y((Ym,Io)=>{function wo(){this.buffer=[],this.length=0}wo.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Io.exports=wo});var To=y((Jm,xo)=>{function Dt(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Dt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Dt.prototype.get=function(t,e){return this.data[t*this.size+e]};Dt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Dt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};xo.exports=Dt});var ko=y(Cn=>{var $d=ve().getSymbolSize;Cn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=$d(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Cn.getPositions=function(e){let n=[],r=Cn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var Po=y(Co=>{var zd=ve().getSymbolSize,Eo=7;Co.getPositions=function(e){let n=zd(e);return[[0,0],[n-Eo,0],[0,n-Eo]]}});var Ro=y(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var He={N1:3,N2:3,N3:40,N4:10};A.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};A.from=function(e){return A.isValid(e)?parseInt(e,10):void 0};A.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=He.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=He.N1+(i-5)),a=u,i=1)}s>=5&&(r+=He.N1+(s-5)),i>=5&&(r+=He.N1+(i-5))}return r};A.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*He.N2};A.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*He.N3};A.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*He.N4};function Vd(t,e,n){switch(t){case A.Patterns.PATTERN000:return(e+n)%2===0;case A.Patterns.PATTERN001:return e%2===0;case A.Patterns.PATTERN010:return n%3===0;case A.Patterns.PATTERN011:return(e+n)%3===0;case A.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case A.Patterns.PATTERN101:return e*n%2+e*n%3===0;case A.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case A.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}A.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Vd(e,i,s))};A.getBestMask=function(e,n){let r=Object.keys(A.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),A.applyMask(o,e);let a=A.getPenaltyN1(e)+A.getPenaltyN2(e)+A.getPenaltyN3(e)+A.getPenaltyN4(e);A.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Wr=y(jr=>{var _e=En(),Pn=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Rn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];jr.getBlocksCount=function(e,n){switch(n){case _e.L:return Pn[(e-1)*4+0];case _e.M:return Pn[(e-1)*4+1];case _e.Q:return Pn[(e-1)*4+2];case _e.H:return Pn[(e-1)*4+3];default:return}};jr.getTotalCodewordsCount=function(e,n){switch(n){case _e.L:return Rn[(e-1)*4+0];case _e.M:return Rn[(e-1)*4+1];case _e.Q:return Rn[(e-1)*4+2];case _e.H:return Rn[(e-1)*4+3];default:return}}});var Lo=y(Mn=>{var Ht=new Uint8Array(512),Ln=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Ht[n]=e,Ln[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Ht[n]=Ht[n-255]})();Mn.log=function(e){if(e<1)throw new Error("log("+e+")");return Ln[e]};Mn.exp=function(e){return Ht[e]};Mn.mul=function(e,n){return e===0||n===0?0:Ht[Ln[e]+Ln[n]]}});var Mo=y(Ft=>{var Gr=Lo();Ft.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=Gr.mul(e[s],n[i]);return r};Ft.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=Gr.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Ft.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Ft.mul(n,new Uint8Array([1,Gr.exp(r)]));return n}});var Bo=y((ny,Oo)=>{var No=Mo();function $r(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}$r.prototype.initialize=function(e){this.degree=e,this.genPoly=No.generateECPolynomial(this.degree)};$r.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=No.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Oo.exports=$r});var zr=y(Do=>{Do.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Vr=y(ge=>{var Ho="[0-9]+",Yd="[A-Z $%*+\\-./:]+",Ut="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ut=Ut.replace(/u/g,"\\u");var Jd="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ut+`)(?:.|[\r
8
- ]))+`;ge.KANJI=new RegExp(Ut,"g");ge.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ge.BYTE=new RegExp(Jd,"g");ge.NUMERIC=new RegExp(Ho,"g");ge.ALPHANUMERIC=new RegExp(Yd,"g");var Kd=new RegExp("^"+Ut+"$"),Xd=new RegExp("^"+Ho+"$"),Qd=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ge.testKanji=function(e){return Kd.test(e)};ge.testNumeric=function(e){return Xd.test(e)};ge.testAlphanumeric=function(e){return Qd.test(e)}});var be=y(L=>{var Zd=zr(),Yr=Vr();L.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};L.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};L.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};L.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};L.MIXED={bit:-1};L.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Zd.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};L.getBestModeForData=function(e){return Yr.testNumeric(e)?L.NUMERIC:Yr.testAlphanumeric(e)?L.ALPHANUMERIC:Yr.testKanji(e)?L.KANJI:L.BYTE};L.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};L.isValid=function(e){return e&&e.bit&&e.ccBits};function ef(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return L.NUMERIC;case"alphanumeric":return L.ALPHANUMERIC;case"kanji":return L.KANJI;case"byte":return L.BYTE;default:throw new Error("Unknown mode: "+t)}}L.from=function(e,n){if(L.isValid(e))return e;try{return ef(e)}catch{return n}}});var Wo=y(Fe=>{var Nn=ve(),tf=Wr(),Fo=En(),we=be(),Jr=zr(),qo=7973,Uo=Nn.getBCHDigit(qo);function nf(t,e,n){for(let r=1;r<=40;r++)if(e<=Fe.getCapacity(r,n,t))return r}function jo(t,e){return we.getCharCountIndicator(t,e)+4}function rf(t,e){let n=0;return t.forEach(function(r){let s=jo(r.mode,e);n+=s+r.getBitsLength()}),n}function sf(t,e){for(let n=1;n<=40;n++)if(rf(t,n)<=Fe.getCapacity(n,e,we.MIXED))return n}Fe.from=function(e,n){return Jr.isValid(e)?parseInt(e,10):n};Fe.getCapacity=function(e,n,r){if(!Jr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=we.BYTE);let s=Nn.getSymbolTotalCodewords(e),i=tf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===we.MIXED)return o;let a=o-jo(r,e);switch(r){case we.NUMERIC:return Math.floor(a/10*3);case we.ALPHANUMERIC:return Math.floor(a/11*2);case we.KANJI:return Math.floor(a/13);case we.BYTE:default:return Math.floor(a/8)}};Fe.getBestVersionForData=function(e,n){let r,s=Fo.from(n,Fo.M);if(Array.isArray(e)){if(e.length>1)return sf(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return nf(r.mode,r.getLength(),s)};Fe.getEncodedBits=function(e){if(!Jr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Nn.getBCHDigit(n)-Uo>=0;)n^=qo<<Nn.getBCHDigit(n)-Uo;return e<<12|n}});var Vo=y(zo=>{var Kr=ve(),$o=1335,of=21522,Go=Kr.getBCHDigit($o);zo.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Kr.getBCHDigit(s)-Go>=0;)s^=$o<<Kr.getBCHDigit(s)-Go;return(r<<10|s)^of}});var Jo=y((ly,Yo)=>{var af=be();function tt(t){this.mode=af.NUMERIC,this.data=t.toString()}tt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};tt.prototype.getLength=function(){return this.data.length};tt.prototype.getBitsLength=function(){return tt.getBitsLength(this.data.length)};tt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Yo.exports=tt});var Xo=y((cy,Ko)=>{var lf=be(),Xr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function nt(t){this.mode=lf.ALPHANUMERIC,this.data=t}nt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Xr.indexOf(this.data[n])*45;r+=Xr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Xr.indexOf(this.data[n]),6)};Ko.exports=nt});var Zo=y((uy,Qo)=>{var cf=be();function rt(t){this.mode=cf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}rt.getBitsLength=function(e){return e*8};rt.prototype.getLength=function(){return this.data.length};rt.prototype.getBitsLength=function(){return rt.getBitsLength(this.data.length)};rt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Qo.exports=rt});var ta=y((dy,ea)=>{var uf=be(),df=ve();function st(t){this.mode=uf.KANJI,this.data=t}st.getBitsLength=function(e){return e*13};st.prototype.getLength=function(){return this.data.length};st.prototype.getBitsLength=function(){return st.getBitsLength(this.data.length)};st.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=df.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
- Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};ea.exports=st});var na=y((fy,Qr)=>{"use strict";var qt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=qt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,h;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,p=s[l],h=typeof s[l]>"u",(h||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var g=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(g)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=qt.single_source_shortest_paths(t,e,n);return qt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=qt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Qr<"u"&&(Qr.exports=qt)});var ua=y(it=>{var I=be(),ia=Jo(),oa=Xo(),aa=Zo(),la=ta(),jt=Vr(),On=ve(),ff=na();function ra(t){return unescape(encodeURIComponent(t)).length}function Wt(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function ca(t){let e=Wt(jt.NUMERIC,I.NUMERIC,t),n=Wt(jt.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return On.isKanjiModeEnabled()?(r=Wt(jt.BYTE,I.BYTE,t),s=Wt(jt.KANJI,I.KANJI,t)):(r=Wt(jt.BYTE_KANJI,I.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Zr(t,e){switch(e){case I.NUMERIC:return ia.getBitsLength(t);case I.ALPHANUMERIC:return oa.getBitsLength(t);case I.KANJI:return la.getBitsLength(t);case I.BYTE:return aa.getBitsLength(t)}}function pf(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function hf(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case I.NUMERIC:e.push([r,{data:r.data,mode:I.ALPHANUMERIC,length:r.length},{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.ALPHANUMERIC:e.push([r,{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.KANJI:e.push([r,{data:r.data,mode:I.BYTE,length:ra(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:ra(r.data)}])}}return e}function gf(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=Zr(n[f].lastCount+c.length,c.mode)-Zr(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Zr(c.length,c.mode)+4+I.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function sa(t,e){let n,r=I.getBestModeForData(t);if(n=I.from(e,r),n!==I.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(n)+`.
10
- Suggested mode is: `+I.toString(r));switch(n===I.KANJI&&!On.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new ia(t);case I.ALPHANUMERIC:return new oa(t);case I.KANJI:return new la(t);case I.BYTE:return new aa(t)}}it.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(sa(r,null)):r.data&&n.push(sa(r.data,r.mode)),n},[])};it.fromString=function(e,n){let r=ca(e,On.isKanjiModeEnabled()),s=hf(r),i=gf(s,n),o=ff.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return it.fromArray(pf(a))};it.rawSplit=function(e){return it.fromArray(ca(e,On.isKanjiModeEnabled()))}});var is=y(da=>{var Dn=ve(),es=En(),mf=Ao(),yf=To(),Sf=ko(),vf=Po(),rs=Ro(),ss=Wr(),_f=Bo(),Bn=Wo(),bf=Vo(),wf=be(),ts=ua();function If(t,e){let n=t.size,r=vf.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function Af(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function xf(t,e){let n=Sf.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function Tf(t,e){let n=t.size,r=Bn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function ns(t,e,n){let r=t.size,s=bf.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function kf(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Ef(t,e,n){let r=new mf;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),wf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Dn.getSymbolTotalCodewords(t),i=ss.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Cf(r,t,e)}function Cf(t,e,n){let r=Dn.getSymbolTotalCodewords(e),s=ss.getTotalCodewordsCount(e,n),i=r-s,o=ss.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,p=new _f(f),h=0,g=new Array(o),m=new Array(o),S=0,P=new Uint8Array(t.buffer);for(let oe=0;oe<o;oe++){let ze=oe<l?u:d;g[oe]=P.slice(h,h+ze),m[oe]=p.encode(g[oe]),h+=ze,S=Math.max(S,ze)}let ie=new Uint8Array(r),E=0,O,K;for(O=0;O<S;O++)for(K=0;K<o;K++)O<g[K].length&&(ie[E++]=g[K][O]);for(O=0;O<f;O++)for(K=0;K<o;K++)ie[E++]=m[K][O];return ie}function Pf(t,e,n,r){let s;if(Array.isArray(t))s=ts.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=ts.rawSplit(t);c=Bn.getBestVersionForData(u,n)}s=ts.fromString(t,c||40)}else throw new Error("Invalid data");let i=Bn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
7
+ `+n)}function De(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,De),t.emit("wsClientError",o,n,e)}else Ht(n,r,s,i)}});var qr=y((Ym,wo)=>{wo.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var _e=y(He=>{var jr,zd=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];He.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};He.getSymbolTotalCodewords=function(e){return zd[e]};He.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};He.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');jr=e};He.isKanjiModeEnabled=function(){return typeof jr<"u"};He.toSJIS=function(e){return jr(e)}});var Pn=y(Q=>{Q.L={bit:1};Q.M={bit:0};Q.Q={bit:3};Q.H={bit:2};function Vd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return Q.L;case"m":case"medium":return Q.M;case"q":case"quartile":return Q.Q;case"h":case"high":return Q.H;default:throw new Error("Unknown EC Level: "+t)}}Q.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};Q.from=function(e,n){if(Q.isValid(e))return e;try{return Vd(e)}catch{return n}}});var xo=y((Xm,Ao)=>{function Io(){this.buffer=[],this.length=0}Io.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Ao.exports=Io});var ko=y((Zm,To)=>{function Ft(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Ft.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Ft.prototype.get=function(t,e){return this.data[t*this.size+e]};Ft.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Ft.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};To.exports=Ft});var Eo=y(Rn=>{var Yd=_e().getSymbolSize;Rn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Yd(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Rn.getPositions=function(e){let n=[],r=Rn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var Ro=y(Po=>{var Jd=_e().getSymbolSize,Co=7;Po.getPositions=function(e){let n=Jd(e);return[[0,0],[n-Co,0],[0,n-Co]]}});var Lo=y(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Fe={N1:3,N2:3,N3:40,N4:10};A.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};A.from=function(e){return A.isValid(e)?parseInt(e,10):void 0};A.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=Fe.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=Fe.N1+(i-5)),a=u,i=1)}s>=5&&(r+=Fe.N1+(s-5)),i>=5&&(r+=Fe.N1+(i-5))}return r};A.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*Fe.N2};A.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*Fe.N3};A.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*Fe.N4};function Kd(t,e,n){switch(t){case A.Patterns.PATTERN000:return(e+n)%2===0;case A.Patterns.PATTERN001:return e%2===0;case A.Patterns.PATTERN010:return n%3===0;case A.Patterns.PATTERN011:return(e+n)%3===0;case A.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case A.Patterns.PATTERN101:return e*n%2+e*n%3===0;case A.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case A.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}A.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Kd(e,i,s))};A.getBestMask=function(e,n){let r=Object.keys(A.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),A.applyMask(o,e);let a=A.getPenaltyN1(e)+A.getPenaltyN2(e)+A.getPenaltyN3(e)+A.getPenaltyN4(e);A.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var $r=y(Wr=>{var be=Pn(),Ln=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Mn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Wr.getBlocksCount=function(e,n){switch(n){case be.L:return Ln[(e-1)*4+0];case be.M:return Ln[(e-1)*4+1];case be.Q:return Ln[(e-1)*4+2];case be.H:return Ln[(e-1)*4+3];default:return}};Wr.getTotalCodewordsCount=function(e,n){switch(n){case be.L:return Mn[(e-1)*4+0];case be.M:return Mn[(e-1)*4+1];case be.Q:return Mn[(e-1)*4+2];case be.H:return Mn[(e-1)*4+3];default:return}}});var Mo=y(On=>{var Ut=new Uint8Array(512),Nn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Ut[n]=e,Nn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Ut[n]=Ut[n-255]})();On.log=function(e){if(e<1)throw new Error("log("+e+")");return Nn[e]};On.exp=function(e){return Ut[e]};On.mul=function(e,n){return e===0||n===0?0:Ut[Nn[e]+Nn[n]]}});var No=y(qt=>{var Gr=Mo();qt.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=Gr.mul(e[s],n[i]);return r};qt.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=Gr.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};qt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=qt.mul(n,new Uint8Array([1,Gr.exp(r)]));return n}});var Do=y((iy,Bo)=>{var Oo=No();function zr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}zr.prototype.initialize=function(e){this.degree=e,this.genPoly=Oo.generateECPolynomial(this.degree)};zr.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=Oo.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Bo.exports=zr});var Vr=y(Ho=>{Ho.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Yr=y(me=>{var Fo="[0-9]+",Xd="[A-Z $%*+\\-./:]+",jt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";jt=jt.replace(/u/g,"\\u");var Zd="(?:(?![A-Z0-9 $%*+\\-./:]|"+jt+`)(?:.|[\r
8
+ ]))+`;me.KANJI=new RegExp(jt,"g");me.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");me.BYTE=new RegExp(Zd,"g");me.NUMERIC=new RegExp(Fo,"g");me.ALPHANUMERIC=new RegExp(Xd,"g");var Qd=new RegExp("^"+jt+"$"),ef=new RegExp("^"+Fo+"$"),tf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");me.testKanji=function(e){return Qd.test(e)};me.testNumeric=function(e){return ef.test(e)};me.testAlphanumeric=function(e){return tf.test(e)}});var we=y(L=>{var nf=Vr(),Jr=Yr();L.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};L.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};L.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};L.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};L.MIXED={bit:-1};L.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!nf.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};L.getBestModeForData=function(e){return Jr.testNumeric(e)?L.NUMERIC:Jr.testAlphanumeric(e)?L.ALPHANUMERIC:Jr.testKanji(e)?L.KANJI:L.BYTE};L.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};L.isValid=function(e){return e&&e.bit&&e.ccBits};function rf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return L.NUMERIC;case"alphanumeric":return L.ALPHANUMERIC;case"kanji":return L.KANJI;case"byte":return L.BYTE;default:throw new Error("Unknown mode: "+t)}}L.from=function(e,n){if(L.isValid(e))return e;try{return rf(e)}catch{return n}}});var $o=y(Ue=>{var Bn=_e(),sf=$r(),Uo=Pn(),Ie=we(),Kr=Vr(),jo=7973,qo=Bn.getBCHDigit(jo);function of(t,e,n){for(let r=1;r<=40;r++)if(e<=Ue.getCapacity(r,n,t))return r}function Wo(t,e){return Ie.getCharCountIndicator(t,e)+4}function af(t,e){let n=0;return t.forEach(function(r){let s=Wo(r.mode,e);n+=s+r.getBitsLength()}),n}function lf(t,e){for(let n=1;n<=40;n++)if(af(t,n)<=Ue.getCapacity(n,e,Ie.MIXED))return n}Ue.from=function(e,n){return Kr.isValid(e)?parseInt(e,10):n};Ue.getCapacity=function(e,n,r){if(!Kr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Ie.BYTE);let s=Bn.getSymbolTotalCodewords(e),i=sf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Ie.MIXED)return o;let a=o-Wo(r,e);switch(r){case Ie.NUMERIC:return Math.floor(a/10*3);case Ie.ALPHANUMERIC:return Math.floor(a/11*2);case Ie.KANJI:return Math.floor(a/13);case Ie.BYTE:default:return Math.floor(a/8)}};Ue.getBestVersionForData=function(e,n){let r,s=Uo.from(n,Uo.M);if(Array.isArray(e)){if(e.length>1)return lf(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return of(r.mode,r.getLength(),s)};Ue.getEncodedBits=function(e){if(!Kr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Bn.getBCHDigit(n)-qo>=0;)n^=jo<<Bn.getBCHDigit(n)-qo;return e<<12|n}});var Yo=y(Vo=>{var Xr=_e(),zo=1335,cf=21522,Go=Xr.getBCHDigit(zo);Vo.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Xr.getBCHDigit(s)-Go>=0;)s^=zo<<Xr.getBCHDigit(s)-Go;return(r<<10|s)^cf}});var Ko=y((dy,Jo)=>{var uf=we();function nt(t){this.mode=uf.NUMERIC,this.data=t.toString()}nt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Jo.exports=nt});var Zo=y((fy,Xo)=>{var df=we(),Zr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function rt(t){this.mode=df.ALPHANUMERIC,this.data=t}rt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};rt.prototype.getLength=function(){return this.data.length};rt.prototype.getBitsLength=function(){return rt.getBitsLength(this.data.length)};rt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Zr.indexOf(this.data[n])*45;r+=Zr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Zr.indexOf(this.data[n]),6)};Xo.exports=rt});var ea=y((py,Qo)=>{var ff=we();function st(t){this.mode=ff.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}st.getBitsLength=function(e){return e*8};st.prototype.getLength=function(){return this.data.length};st.prototype.getBitsLength=function(){return st.getBitsLength(this.data.length)};st.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Qo.exports=st});var na=y((hy,ta)=>{var pf=we(),hf=_e();function it(t){this.mode=pf.KANJI,this.data=t}it.getBitsLength=function(e){return e*13};it.prototype.getLength=function(){return this.data.length};it.prototype.getBitsLength=function(){return it.getBitsLength(this.data.length)};it.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=hf.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};ta.exports=it});var ra=y((gy,Qr)=>{"use strict";var Wt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Wt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,h;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,p=s[l],h=typeof s[l]>"u",(h||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var g=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(g)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Wt.single_source_shortest_paths(t,e,n);return Wt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Wt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Qr<"u"&&(Qr.exports=Wt)});var da=y(ot=>{var I=we(),oa=Ko(),aa=Zo(),la=ea(),ca=na(),$t=Yr(),Dn=_e(),gf=ra();function sa(t){return unescape(encodeURIComponent(t)).length}function Gt(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function ua(t){let e=Gt($t.NUMERIC,I.NUMERIC,t),n=Gt($t.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return Dn.isKanjiModeEnabled()?(r=Gt($t.BYTE,I.BYTE,t),s=Gt($t.KANJI,I.KANJI,t)):(r=Gt($t.BYTE_KANJI,I.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function es(t,e){switch(e){case I.NUMERIC:return oa.getBitsLength(t);case I.ALPHANUMERIC:return aa.getBitsLength(t);case I.KANJI:return ca.getBitsLength(t);case I.BYTE:return la.getBitsLength(t)}}function mf(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function yf(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case I.NUMERIC:e.push([r,{data:r.data,mode:I.ALPHANUMERIC,length:r.length},{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.ALPHANUMERIC:e.push([r,{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.KANJI:e.push([r,{data:r.data,mode:I.BYTE,length:sa(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:sa(r.data)}])}}return e}function Sf(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=es(n[f].lastCount+c.length,c.mode)-es(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=es(c.length,c.mode)+4+I.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function ia(t,e){let n,r=I.getBestModeForData(t);if(n=I.from(e,r),n!==I.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(n)+`.
10
+ Suggested mode is: `+I.toString(r));switch(n===I.KANJI&&!Dn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new oa(t);case I.ALPHANUMERIC:return new aa(t);case I.KANJI:return new ca(t);case I.BYTE:return new la(t)}}ot.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(ia(r,null)):r.data&&n.push(ia(r.data,r.mode)),n},[])};ot.fromString=function(e,n){let r=ua(e,Dn.isKanjiModeEnabled()),s=yf(r),i=Sf(s,n),o=gf.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return ot.fromArray(mf(a))};ot.rawSplit=function(e){return ot.fromArray(ua(e,Dn.isKanjiModeEnabled()))}});var os=y(fa=>{var Fn=_e(),ts=Pn(),vf=xo(),_f=ko(),bf=Eo(),wf=Ro(),ss=Lo(),is=$r(),If=Do(),Hn=$o(),Af=Yo(),xf=we(),ns=da();function Tf(t,e){let n=t.size,r=wf.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function kf(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function Ef(t,e){let n=bf.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function Cf(t,e){let n=t.size,r=Hn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function rs(t,e,n){let r=t.size,s=Af.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function Pf(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Rf(t,e,n){let r=new vf;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),xf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Fn.getSymbolTotalCodewords(t),i=is.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Lf(r,t,e)}function Lf(t,e,n){let r=Fn.getSymbolTotalCodewords(e),s=is.getTotalCodewordsCount(e,n),i=r-s,o=is.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,p=new If(f),h=0,g=new Array(o),m=new Array(o),S=0,P=new Uint8Array(t.buffer);for(let ae=0;ae<o;ae++){let Ve=ae<l?u:d;g[ae]=P.slice(h,h+Ve),m[ae]=p.encode(g[ae]),h+=Ve,S=Math.max(S,Ve)}let oe=new Uint8Array(r),E=0,B,K;for(B=0;B<S;B++)for(K=0;K<o;K++)B<g[K].length&&(oe[E++]=g[K][B]);for(B=0;B<f;B++)for(K=0;K<o;K++)oe[E++]=m[K][B];return oe}function Mf(t,e,n,r){let s;if(Array.isArray(t))s=ns.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=ns.rawSplit(t);c=Hn.getBestVersionForData(u,n)}s=ns.fromString(t,c||40)}else throw new Error("Invalid data");let i=Hn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
12
  Minimum version required to store current data is: `+i+`.
13
- `);let o=Ef(e,n,s),a=Dn.getSymbolSize(e),l=new yf(a);return If(l,e),Af(l),xf(l,e),ns(l,n,0),e>=7&&Tf(l,e),kf(l,o),isNaN(r)&&(r=rs.getBestMask(l,ns.bind(null,l,n))),rs.applyMask(r,l),ns(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}da.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=es.M,s,i;return typeof n<"u"&&(r=es.from(n.errorCorrectionLevel,es.M),s=Bn.from(n.version),i=rs.from(n.maskPattern),n.toSJISFunc&&Dn.setToSJISFunction(n.toSJISFunc)),Pf(e,s,r,i)}});var os=y((gy,pa)=>{"use strict";var Rf=require("util"),fa=require("stream"),re=pa.exports=function(){fa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Rf.inherits(re,fa);re.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};re.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};re.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};re.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};re.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ls=y(as=>{"use strict";var Ie=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];as.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Ie.length;a++){let l=Ie[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};as.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ie[r].x.length,i=(e-s)/Ie[r].x.length*8+Ie[r].x[s],o=n%Ie[r].y.length,a=(n-o)/Ie[r].y.length*8+Ie[r].y[o];return i*4+a*t*4}}});var cs=y((yy,ha)=>{"use strict";ha.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var us=y((Sy,ma)=>{"use strict";var Lf=ls(),Mf=cs();function ga(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var ot=ma.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Lf.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:ga(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:ga(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};ot.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ot.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};ot.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};ot.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};ot.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Mf(c,l,u);e[o]=a+d}};ot.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var va=y((vy,Sa)=>{"use strict";var Nf=require("util"),ya=os(),Of=us(),Bf=Sa.exports=function(t){ya.call(this);let e=[],n=this;this._filter=new Of(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Nf.inherits(Bf,ya)});var at=y((_y,_a)=>{"use strict";_a.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var ps=y((by,ba)=>{"use strict";var ds=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;ds[t]=e}})();var fs=ba.exports=function(){this._crc=-1};fs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ds[(this._crc^t[e])&255]^this._crc>>>8;return!0};fs.prototype.crc32=function(){return this._crc^-1};fs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ds[(e^t[n])&255]^e>>>8;return e^-1}});var hs=y((wy,wa)=>{"use strict";var N=at(),Df=ps(),D=wa.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[N.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[N.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[N.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[N.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[N.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[N.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};D.prototype.start=function(){this.read(N.PNG_SIGNATURE.length,this._parseSignature.bind(this))};D.prototype._parseSignature=function(t){let e=N.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};D.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==N.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Df,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};D.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};D.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};D.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};D.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};D.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in N.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=N.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&N.COLORTYPE_PALETTE),color:!!(s&N.COLORTYPE_COLOR),alpha:!!(s&N.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};D.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};D.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};D.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};D.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===N.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===N.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===N.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};D.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};D.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/N.GAMMA_DIVISION),this._handleChunkEnd()};D.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};D.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===N.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};D.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};D.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var gs=y(Aa=>{"use strict";var Ia=ls(),Hf=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Ff=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Uf(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function qf(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);Hf[r](e,s,d,i),i+=r}return i}function jf(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);Ff[r](e,d,f,i)}s.resetAfterLine()}}Aa.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Uf(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=Ia.getImagePasses(n,r),f=Ia.getInterlaceIterator(n,r);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=qf(d[p],l,f,i,t,u):jf(d[p],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var ms=y((Ay,xa)=>{"use strict";function Wf(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function Gf(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function $f(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}xa.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Wf(t,l,r,s,a):(o&&Gf(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),$f(t,l,r,s,n))),l}});var Ea=y((xy,ka)=>{"use strict";var zf=require("util"),ys=require("zlib"),Ta=os(),Vf=va(),Yf=hs(),Jf=gs(),Kf=ms(),le=ka.exports=function(t){Ta.call(this),this._parser=new Yf(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};zf.inherits(le,Ta);le.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};le.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ys.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,ys.Z_MIN_CHUNK);this._inflate=ys.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};le.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Vf(this._bitmapInfo)};le.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};le.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};le.prototype._simpleTransparency=function(){this._metaData.alpha=!0};le.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};le.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};le.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Jf.dataToBitMap(t,this._bitmapInfo);e=Kf(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Pa=y((Ty,Ca)=>{"use strict";var ee=at();Ca.exports=function(t,e,n,r){let s=[ee.COLORTYPE_COLOR_ALPHA,ee.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&h)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ee.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=ee.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function p(){let h,g,m,S=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:S=i[u+3],h=i[u],g=i[u+1],m=i[u+2];break;case ee.COLORTYPE_COLOR:h=i[u],g=i[u+1],m=i[u+2];break;case ee.COLORTYPE_ALPHA:S=i[u+1],h=i[u],g=h,m=h;break;case ee.COLORTYPE_GRAYSCALE:h=i[u],g=h,m=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(S/=o,h=Math.min(Math.max(Math.round((1-S)*f.red+S*h),0),o),g=Math.min(Math.max(Math.round((1-S)*f.green+S*g),0),o),m=Math.min(Math.max(Math.round((1-S)*f.blue+S*m),0),o))),{red:h,green:g,blue:m,alpha:S}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let m=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,s&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),s&&c.writeUInt16BE(m.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let S=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=S,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(S,d),s&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var Ma=y((ky,La)=>{"use strict";var Ra=cs();function Xf(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Qf(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Zf(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function ep(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function tp(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function np(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function rp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function sp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function ip(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-Ra(a,l,c);r[s+o]=u}}function op(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-Ra(o,a,l);s+=Math.abs(c)}return s}var ap={0:Xf,1:Zf,2:tp,3:rp,4:ip},lp={0:Qf,1:ep,2:np,3:sp,4:op};La.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let h=lp[i[p]](t,l,o,s);h<f&&(u=i[p],f=h)}}c[a]=u,a++,ap[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Ss=y((Ey,Na)=>{"use strict";var U=at(),cp=ps(),up=Pa(),dp=Ma(),fp=require("zlib"),Ae=Na.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||fp.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:U.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:U.COLORTYPE_COLOR_ALPHA,[U.COLORTYPE_GRAYSCALE,U.COLORTYPE_COLOR,U.COLORTYPE_COLOR_ALPHA,U.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([U.COLORTYPE_GRAYSCALE,U.COLORTYPE_COLOR,U.COLORTYPE_COLOR_ALPHA,U.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Ae.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ae.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ae.prototype.filterData=function(t,e,n){let r=up(t,e,n,this._options),s=U.COLORTYPE_TO_BPP_MAP[this._options.colorType];return dp(r,e,n,this._options,s)};Ae.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(cp.crc32(r.slice(4,r.length-4)),r.length-4),r};Ae.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*U.GAMMA_DIVISION),0),this._packChunk(U.TYPE_gAMA,e)};Ae.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(U.TYPE_IHDR,n)};Ae.prototype.packIDAT=function(t){return this._packChunk(U.TYPE_IDAT,t)};Ae.prototype.packIEND=function(){return this._packChunk(U.TYPE_IEND,null)}});var Ha=y((Cy,Da)=>{"use strict";var pp=require("util"),Oa=require("stream"),hp=at(),gp=Ss(),Ba=Da.exports=function(t){Oa.call(this);let e=t||{};this._packer=new gp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};pp.inherits(Ba,Oa);Ba.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(hp.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Ga=y((Gt,Wa)=>{"use strict";var Fa=require("assert").ok,lt=require("zlib"),mp=require("util"),Ua=require("buffer").kMaxLength;function Ue(t){if(!(this instanceof Ue))return new Ue(t);t&&t.chunkSize<lt.Z_MIN_CHUNK&&(t.chunkSize=lt.Z_MIN_CHUNK),lt.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function yp(t){return new Ue(t)}function qa(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ue.prototype._processChunk=function(t,e,n){if(typeof n=="function")return lt.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(h){u=h});function d(h,g){if(r._hadError)return;let m=i-g;if(Fa(m>=0,"have should not go down"),m>0){let S=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.length,o===0)return!1}return(g===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Fa(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Ua)throw qa(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ua.toString(16)+" bytes");let p=Buffer.concat(l,c);return qa(this),p};mp.inherits(Ue,lt.Inflate);function Sp(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=lt.Z_FINISH),t._processChunk(e,n)}function ja(t,e){return Sp(new Ue(e),t)}Wa.exports=Gt=ja;Gt.Inflate=Ue;Gt.createInflate=yp;Gt.inflateSync=ja});var vs=y((Py,za)=>{"use strict";var $a=za.exports=function(t){this._buffer=t,this._reads=[]};$a.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};$a.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Ya=y(Va=>{"use strict";var vp=vs(),_p=us();Va.process=function(t,e){let n=[],r=new vp(t);return new _p(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Qa=y((Ly,Xa)=>{"use strict";var Ja=!0,Ka=require("zlib"),bp=Ga();Ka.deflateSync||(Ja=!1);var wp=vs(),Ip=Ya(),Ap=hs(),xp=gs(),Tp=ms();Xa.exports=function(t,e){if(!Ja)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(E){n=E}let s;function i(E){s=E}function o(E){s.transColor=E}function a(E){s.palette=E}function l(){s.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let p=new wp(t);if(new Ap(e,{read:p.read.bind(p),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Ka.inflateSync(g);else{let O=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=bp(g,{chunkSize:O,maxLength:O})}if(g=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=Ip.process(m,s);g=null;let P=xp.dataToBitMap(S,s);S=null;let ie=Tp(P,s);return s.data=ie,s.gamma=c||0,s}});var nl=y((My,tl)=>{"use strict";var Za=!0,el=require("zlib");el.deflateSync||(Za=!1);var kp=at(),Ep=Ss();tl.exports=function(t,e){if(!Za)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new Ep(n),s=[];s.push(Buffer.from(kp.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=el.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var rl=y(_s=>{"use strict";var Cp=Qa(),Pp=nl();_s.read=function(t,e){return Cp(t,e||{})};_s.write=function(t,e){return Pp(t,e)}});var ol=y(il=>{"use strict";var Rp=require("util"),sl=require("stream"),Lp=Ea(),Mp=Ha(),Np=rl(),q=il.PNG=function(t){sl.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Lp(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Mp(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Rp.inherits(q,sl);q.sync=Np;q.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};q.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};q.prototype.write=function(t){return this._parser.write(t),!0};q.prototype.end=function(t){this._parser.end(t)};q.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};q.prototype._gamma=function(t){this.gamma=t};q.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};q.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};q.prototype.bitblt=function(t,e,n,r,s,i,o){return q.bitblt(this,t,e,n,r,s,i,o),this};q.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};q.prototype.adjustGamma=function(){q.adjustGamma(this)}});var $t=y(qe=>{function al(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}qe.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:al(e.color.dark||"#000000ff"),light:al(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};qe.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};qe.getImageWidth=function(e,n){let r=qe.getScale(e,n);return Math.floor((e+n.margin*2)*r)};qe.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=qe.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,p=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let h=Math.floor((u-l)/o),g=Math.floor((d-l)/o);p=c[i[h*s+g]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var ll=y(ce=>{var Op=require("fs"),Bp=ol().PNG,bs=$t();ce.render=function(e,n){let r=bs.getOptions(n),s=r.rendererOpts,i=bs.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Bp(s);return bs.qrToImageData(o.data,e,r),o};ce.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ce.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};ce.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=ce.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};ce.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Op.createWriteStream(e);a.on("error",o),a.on("close",o),ce.renderToFileStream(a,n,r)};ce.renderToFileStream=function(e,n,r){ce.render(n,r).pack().pipe(e)}});var cl=y(Hn=>{var Dp=$t(),Hp={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Fp={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Up(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Hn.render=function(t,e,n){let r=Dp.getOptions(e),s=Hp;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Fp);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
- `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],p=o[(u+1)*i+d];a+=Up(f,p,s)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Hn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Hn.render(n,r);i.writeFile(e,o,s)}});var dl=y(ul=>{ul.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
13
+ `);let o=Rf(e,n,s),a=Fn.getSymbolSize(e),l=new _f(a);return Tf(l,e),kf(l),Ef(l,e),rs(l,n,0),e>=7&&Cf(l,e),Pf(l,o),isNaN(r)&&(r=ss.getBestMask(l,rs.bind(null,l,n))),ss.applyMask(r,l),rs(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}fa.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ts.M,s,i;return typeof n<"u"&&(r=ts.from(n.errorCorrectionLevel,ts.M),s=Hn.from(n.version),i=ss.from(n.maskPattern),n.toSJISFunc&&Fn.setToSJISFunction(n.toSJISFunc)),Mf(e,s,r,i)}});var as=y((Sy,ha)=>{"use strict";var Nf=require("util"),pa=require("stream"),re=ha.exports=function(){pa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Nf.inherits(re,pa);re.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};re.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};re.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};re.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};re.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var cs=y(ls=>{"use strict";var Ae=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];ls.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Ae.length;a++){let l=Ae[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};ls.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ae[r].x.length,i=(e-s)/Ae[r].x.length*8+Ae[r].x[s],o=n%Ae[r].y.length,a=(n-o)/Ae[r].y.length*8+Ae[r].y[o];return i*4+a*t*4}}});var us=y((_y,ga)=>{"use strict";ga.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var ds=y((by,ya)=>{"use strict";var Of=cs(),Bf=us();function ma(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var at=ya.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Of.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:ma(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:ma(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};at.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};at.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};at.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};at.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};at.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Bf(c,l,u);e[o]=a+d}};at.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var _a=y((wy,va)=>{"use strict";var Df=require("util"),Sa=as(),Hf=ds(),Ff=va.exports=function(t){Sa.call(this);let e=[],n=this;this._filter=new Hf(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Df.inherits(Ff,Sa)});var lt=y((Iy,ba)=>{"use strict";ba.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var hs=y((Ay,wa)=>{"use strict";var fs=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;fs[t]=e}})();var ps=wa.exports=function(){this._crc=-1};ps.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=fs[(this._crc^t[e])&255]^this._crc>>>8;return!0};ps.prototype.crc32=function(){return this._crc^-1};ps.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=fs[(e^t[n])&255]^e>>>8;return e^-1}});var gs=y((xy,Ia)=>{"use strict";var O=lt(),Uf=hs(),H=Ia.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[O.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[O.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[O.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[O.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[O.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[O.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};H.prototype.start=function(){this.read(O.PNG_SIGNATURE.length,this._parseSignature.bind(this))};H.prototype._parseSignature=function(t){let e=O.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};H.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==O.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Uf,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};H.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};H.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};H.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};H.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};H.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in O.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=O.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&O.COLORTYPE_PALETTE),color:!!(s&O.COLORTYPE_COLOR),alpha:!!(s&O.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};H.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};H.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};H.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};H.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===O.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===O.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===O.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};H.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};H.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/O.GAMMA_DIVISION),this._handleChunkEnd()};H.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};H.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===O.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};H.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};H.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ms=y(xa=>{"use strict";var Aa=cs(),qf=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],jf=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Wf(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function $f(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);qf[r](e,s,d,i),i+=r}return i}function Gf(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);jf[r](e,d,f,i)}s.resetAfterLine()}}xa.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Wf(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=Aa.getImagePasses(n,r),f=Aa.getInterlaceIterator(n,r);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=$f(d[p],l,f,i,t,u):Gf(d[p],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var ys=y((ky,Ta)=>{"use strict";function zf(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function Vf(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function Yf(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}Ta.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?zf(t,l,r,s,a):(o&&Vf(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Yf(t,l,r,s,n))),l}});var Ca=y((Ey,Ea)=>{"use strict";var Jf=require("util"),Ss=require("zlib"),ka=as(),Kf=_a(),Xf=gs(),Zf=ms(),Qf=ys(),ce=Ea.exports=function(t){ka.call(this),this._parser=new Xf(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Jf.inherits(ce,ka);ce.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};ce.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ss.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Ss.Z_MIN_CHUNK);this._inflate=Ss.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ce.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Kf(this._bitmapInfo)};ce.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ce.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ce.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ce.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ce.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ce.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Zf.dataToBitMap(t,this._bitmapInfo);e=Qf(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ra=y((Cy,Pa)=>{"use strict";var ee=lt();Pa.exports=function(t,e,n,r){let s=[ee.COLORTYPE_COLOR_ALPHA,ee.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&h)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ee.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=ee.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function p(){let h,g,m,S=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:S=i[u+3],h=i[u],g=i[u+1],m=i[u+2];break;case ee.COLORTYPE_COLOR:h=i[u],g=i[u+1],m=i[u+2];break;case ee.COLORTYPE_ALPHA:S=i[u+1],h=i[u],g=h,m=h;break;case ee.COLORTYPE_GRAYSCALE:h=i[u],g=h,m=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(S/=o,h=Math.min(Math.max(Math.round((1-S)*f.red+S*h),0),o),g=Math.min(Math.max(Math.round((1-S)*f.green+S*g),0),o),m=Math.min(Math.max(Math.round((1-S)*f.blue+S*m),0),o))),{red:h,green:g,blue:m,alpha:S}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let m=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,s&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),s&&c.writeUInt16BE(m.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let S=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=S,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(S,d),s&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var Na=y((Py,Ma)=>{"use strict";var La=us();function ep(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function tp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function np(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function rp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function sp(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function ip(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function op(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function ap(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function lp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-La(a,l,c);r[s+o]=u}}function cp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-La(o,a,l);s+=Math.abs(c)}return s}var up={0:ep,1:np,2:sp,3:op,4:lp},dp={0:tp,1:rp,2:ip,3:ap,4:cp};Ma.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let h=dp[i[p]](t,l,o,s);h<f&&(u=i[p],f=h)}}c[a]=u,a++,up[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var vs=y((Ry,Oa)=>{"use strict";var q=lt(),fp=hs(),pp=Ra(),hp=Na(),gp=require("zlib"),xe=Oa.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||gp.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:q.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:q.COLORTYPE_COLOR_ALPHA,[q.COLORTYPE_GRAYSCALE,q.COLORTYPE_COLOR,q.COLORTYPE_COLOR_ALPHA,q.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([q.COLORTYPE_GRAYSCALE,q.COLORTYPE_COLOR,q.COLORTYPE_COLOR_ALPHA,q.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};xe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};xe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};xe.prototype.filterData=function(t,e,n){let r=pp(t,e,n,this._options),s=q.COLORTYPE_TO_BPP_MAP[this._options.colorType];return hp(r,e,n,this._options,s)};xe.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(fp.crc32(r.slice(4,r.length-4)),r.length-4),r};xe.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*q.GAMMA_DIVISION),0),this._packChunk(q.TYPE_gAMA,e)};xe.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(q.TYPE_IHDR,n)};xe.prototype.packIDAT=function(t){return this._packChunk(q.TYPE_IDAT,t)};xe.prototype.packIEND=function(){return this._packChunk(q.TYPE_IEND,null)}});var Fa=y((Ly,Ha)=>{"use strict";var mp=require("util"),Ba=require("stream"),yp=lt(),Sp=vs(),Da=Ha.exports=function(t){Ba.call(this);let e=t||{};this._packer=new Sp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};mp.inherits(Da,Ba);Da.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(yp.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Ga=y((zt,$a)=>{"use strict";var Ua=require("assert").ok,ct=require("zlib"),vp=require("util"),qa=require("buffer").kMaxLength;function qe(t){if(!(this instanceof qe))return new qe(t);t&&t.chunkSize<ct.Z_MIN_CHUNK&&(t.chunkSize=ct.Z_MIN_CHUNK),ct.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function _p(t){return new qe(t)}function ja(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}qe.prototype._processChunk=function(t,e,n){if(typeof n=="function")return ct.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(h){u=h});function d(h,g){if(r._hadError)return;let m=i-g;if(Ua(m>=0,"have should not go down"),m>0){let S=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.length,o===0)return!1}return(g===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Ua(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=qa)throw ja(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+qa.toString(16)+" bytes");let p=Buffer.concat(l,c);return ja(this),p};vp.inherits(qe,ct.Inflate);function bp(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=ct.Z_FINISH),t._processChunk(e,n)}function Wa(t,e){return bp(new qe(e),t)}$a.exports=zt=Wa;zt.Inflate=qe;zt.createInflate=_p;zt.inflateSync=Wa});var _s=y((My,Va)=>{"use strict";var za=Va.exports=function(t){this._buffer=t,this._reads=[]};za.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};za.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Ja=y(Ya=>{"use strict";var wp=_s(),Ip=ds();Ya.process=function(t,e){let n=[],r=new wp(t);return new Ip(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Qa=y((Oy,Za)=>{"use strict";var Ka=!0,Xa=require("zlib"),Ap=Ga();Xa.deflateSync||(Ka=!1);var xp=_s(),Tp=Ja(),kp=gs(),Ep=ms(),Cp=ys();Za.exports=function(t,e){if(!Ka)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(E){n=E}let s;function i(E){s=E}function o(E){s.transColor=E}function a(E){s.palette=E}function l(){s.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let p=new xp(t);if(new kp(e,{read:p.read.bind(p),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let g=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Xa.inflateSync(g);else{let B=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=Ap(g,{chunkSize:B,maxLength:B})}if(g=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=Tp.process(m,s);g=null;let P=Ep.dataToBitMap(S,s);S=null;let oe=Cp(P,s);return s.data=oe,s.gamma=c||0,s}});var rl=y((By,nl)=>{"use strict";var el=!0,tl=require("zlib");tl.deflateSync||(el=!1);var Pp=lt(),Rp=vs();nl.exports=function(t,e){if(!el)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new Rp(n),s=[];s.push(Buffer.from(Pp.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=tl.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var sl=y(bs=>{"use strict";var Lp=Qa(),Mp=rl();bs.read=function(t,e){return Lp(t,e||{})};bs.write=function(t,e){return Mp(t,e)}});var al=y(ol=>{"use strict";var Np=require("util"),il=require("stream"),Op=Ca(),Bp=Fa(),Dp=sl(),j=ol.PNG=function(t){il.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Op(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Bp(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Np.inherits(j,il);j.sync=Dp;j.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};j.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};j.prototype.write=function(t){return this._parser.write(t),!0};j.prototype.end=function(t){this._parser.end(t)};j.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};j.prototype._gamma=function(t){this.gamma=t};j.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};j.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};j.prototype.bitblt=function(t,e,n,r,s,i,o){return j.bitblt(this,t,e,n,r,s,i,o),this};j.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};j.prototype.adjustGamma=function(){j.adjustGamma(this)}});var Vt=y(je=>{function ll(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}je.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:ll(e.color.dark||"#000000ff"),light:ll(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};je.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};je.getImageWidth=function(e,n){let r=je.getScale(e,n);return Math.floor((e+n.margin*2)*r)};je.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=je.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,p=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let h=Math.floor((u-l)/o),g=Math.floor((d-l)/o);p=c[i[h*s+g]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var cl=y(ue=>{var Hp=require("fs"),Fp=al().PNG,ws=Vt();ue.render=function(e,n){let r=ws.getOptions(n),s=r.rendererOpts,i=ws.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Fp(s);return ws.qrToImageData(o.data,e,r),o};ue.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ue.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};ue.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=ue.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};ue.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Hp.createWriteStream(e);a.on("error",o),a.on("close",o),ue.renderToFileStream(a,n,r)};ue.renderToFileStream=function(e,n,r){ue.render(n,r).pack().pipe(e)}});var ul=y(Un=>{var Up=Vt(),qp={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},jp={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Wp(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Un.render=function(t,e,n){let r=Up.getOptions(e),s=qp;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=jp);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
+ `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],p=o[(u+1)*i+d];a+=Wp(f,p,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Un.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Un.render(n,r);i.writeFile(e,o,s)}});var fl=y(dl=>{dl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
16
16
  `;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=s[u*r+d]?i:o;a+=c+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var gl=y(hl=>{var qp="\x1B[47m",jp="\x1B[40m",ws="\x1B[37m",Is="\x1B[30m",je="\x1B[0m",Wp=qp+Is,Gp=jp+ws,$p=function(t,e,n){return{"00":je+" "+t,"01":je+e+"\u2584"+t,"02":je+n+"\u2584"+t,10:je+e+"\u2580"+t,11:" ",12:"\u2584",20:je+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},fl=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},pl=function(t,e,n,r){return fl(t,e,n,r)+fl(t,e,n,r+1)};hl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Gp:Wp,c=$p(o,i?Is:ws,i?ws:Is),u=je+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[pl(s,r,p,f)];d+=c[pl(s,r,r,f)]+u}return d+=je,typeof n=="function"&&n(null,d),d}});var yl=y(ml=>{var zp=dl(),Vp=gl();ml.render=function(t,e,n){return e&&e.small?Vp.render(t,e,n):zp.render(t,e,n)}});var xs=y(vl=>{var Yp=$t();function Sl(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function As(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Jp(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?As("M",l+n,.5+c+n):As("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=As("h",o),o=0)):s++}return r}vl.render=function(e,n,r){let s=Yp.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+Sl(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Sl(s.color.dark,"stroke")+' d="'+Jp(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
- `;return typeof r=="function"&&r(null,f),f}});var _l=y(Fn=>{var Kp=xs();Fn.render=Kp.render;Fn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+Fn.render(n,r);i.writeFile(e,a,s)}});var bl=y(Un=>{var Ts=$t();function Xp(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function Qp(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Un.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Qp()),s=Ts.getOptions(s);let o=Ts.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Ts.qrToImageData(l.data,e,s),Xp(a,i,o),a.putImageData(l,0,0),i};Un.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Un.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Il=y(zt=>{var Zp=Ur(),ks=is(),wl=bl(),eh=xs();function Es(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Zp())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=ks.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=ks.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}zt.create=ks.create;zt.toCanvas=Es.bind(null,wl.render);zt.toDataURL=Es.bind(null,wl.renderToDataURL);zt.toString=Es.bind(null,function(t,e,n){return eh.render(t,n)})});var kl=y(xe=>{var Al=Ur(),Cs=is(),th=ll(),xl=cl(),nh=yl(),Tl=_l();function Vt(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(Al())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function rh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function qn(t){switch(t){case"svg":return Tl;case"txt":case"utf8":return xl;case"png":case"image/png":default:return th}}function sh(t){switch(t){case"svg":return Tl;case"terminal":return nh;case"utf8":default:return xl}}function Yt(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=Cs.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=Cs.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}xe.create=Cs.create;xe.toCanvas=Il().toCanvas;xe.toString=function(e,n,r){let s=Vt(e,n,r),i=s.opts?s.opts.type:void 0,o=sh(i);return Yt(o.render,e,s)};xe.toDataURL=function(e,n,r){let s=Vt(e,n,r),i=qn(s.opts.type);return Yt(i.renderToDataURL,e,s)};xe.toBuffer=function(e,n,r){let s=Vt(e,n,r),i=qn(s.opts.type);return Yt(i.renderToBuffer,e,s)};xe.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Al())throw new Error("Too few arguments provided");let i=Vt(n,r,s),o=i.opts.type||rh(e),l=qn(o).renderToFile.bind(null,e);return Yt(l,n,i)};xe.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Vt(n,r,e.emit.bind(e,"error")),o=qn("png").renderToFileStream.bind(null,e);Yt(o,n,s)}});var Cl=y((Vy,El)=>{El.exports=kl()});var au=require("http");var Fd=Ve(uo(),1),Ud=Ve(Er(),1),qd=Ve(Rr(),1),jd=Ve(Tn(),1),Fr=Ve(_o(),1);var Ge=require("fs/promises"),mr=require("path"),lu=require("os"),cu=Ve(Cl(),1);var dt=require("child_process"),jl=require("fs"),j=require("path"),Qt=require("os");var Yn=require("fs");var Pl=require("os"),Y=require("path"),Jt=(0,Y.join)((0,Pl.homedir)(),".vibelet"),jn=(0,Y.join)(Jt,"logs"),Ps=(0,Y.join)(Jt,"data"),ih=(0,Y.join)(Jt,"runtime"),Yy=(0,Y.join)(ih,"current"),Rl=(0,Y.join)(Jt,"identity.json"),Ll=(0,Y.join)(Jt,"pairings.json"),Ml=(0,Y.join)(Ps,"push-subscriptions.json"),Wn=(0,Y.join)(Ps,"sessions.json"),ct=(0,Y.join)(Ps,"audit.jsonl"),Gn=(0,Y.join)(jn,"daemon.stdout.log"),$n=(0,Y.join)(jn,"daemon.stderr.log");var zn={stdout:!1,stderr:!1};function Nl(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function oh(t){return!t.destroyed&&t.writable!==!1}function Ol(t,e){if(zn[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!oh(n))return zn[t]=!0,!1;try{return n.write(e,r=>{Nl(r)&&(zn[t]=!0)}),!0}catch(r){return Nl(r)&&(zn[t]=!0),!1}}function Kt(t){return Ol("stdout",t)}function Vn(t){return Ol("stderr",t)}var Bl={debug:10,info:20,warn:30,error:40},ah=process.env.VIBE_LOG_LEVEL||"info";function lh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function ch(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Hl=!lh()&&!ch();if(Hl)try{(0,Yn.mkdirSync)(jn,{recursive:!0})}catch{}function Dl(t,e,n){if(Bl[t]<Bl[ah])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?Vn(s+`
21
- `):Kt(s+`
22
- `),Hl){let i=t==="error"||t==="warn"?$n:Gn;try{(0,Yn.appendFileSync)(i,s+`
23
- `)}catch{}}}function Fl(t={}){function e(n,r,s){typeof r=="string"?Dl(n,t,r):Dl(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Fl({...t,...n})}}var R=Fl({module:"daemon"});var uh=["fnm_multishells"],dh=6e4,fh=R.child({module:"config"});function Te(t){return uh.some(e=>t.includes(e))}function Ls(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var ut=null;function Wl(){if(ut&&!Te(ut.PATH??""))return ut;for(let t of Ls())try{let e=(0,dt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
- `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return Te(n.PATH??"")?ut=null:ut=n,n}catch{}return ut={},{}}function ph(t=Wl()){let e=(0,Qt.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,j.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,j.join)(e,".npm-global","bin"),(0,j.join)(e,".local","bin"),(0,j.join)(e,".claude","bin"),n],i=r.split(j.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(j.delimiter)}function Rs(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function Ul(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Jn(){let t=Wl(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=ph(t),e.HOME||(e.HOME=(0,Qt.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Xt(t,e=3e3){try{return(0,dt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Jn()}).trim()||null}catch{return null}}function hh(t){for(let e of Ls())try{let n=(0,dt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function gh(){let t=(0,Qt.homedir)();return[(0,j.join)(t,".local","bin","claude"),(0,j.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,j.join)(t,".npm-global","bin","claude")]}function mh(){for(let t of gh())if(Xt(t))return t;try{let t=(0,dt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Jn()}).trim();if(t&&!t.includes("cmux")&&Xt(t))return t}catch{}}function yh(){let t=(0,Qt.homedir)(),e=[process.env.PNPM_HOME,(0,j.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,j.join)(t,".npm-global","bin","codex"),(0,j.join)(t,".local","bin","codex"),...e.map(n=>(0,j.join)(n,"codex"))]}function Sh(){let t;for(let n of yh())if(Xt(n)){if(!Te(n))return n;t=n}try{let n=(0,dt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Jn()}).trim();if(n&&Xt(n)){if(!Te(n))return n;t=t??n}}catch{}let e=hh("codex");if(e&&Xt(e)){if(!Te(e))return e;t=t??e}return t}function Gl(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();return(!n||i-r>dh||!(0,jl.existsSync)(n)||Te(n))&&(n=t()??e,r=i,fh.info({name:e,path:n,transient:Te(n)},"binary resolved")),n}}var vh=Gl(mh,"claude"),_h=Gl(Sh,"codex");function bh(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var ql=bh();function wh(t,e){return{command:Ls()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var v={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:ql.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:ql["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ul("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Ul("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Rs("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Rs("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Rs("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return vh()},get codexPath(){return _h()},isTransientPath:Te,execViaLoginShell:wh,buildSanitizedEnv:Jn};var ii=require("crypto"),qc=require("fs/promises");var Zl=require("child_process"),ec=require("fs");var Kn=require("fs"),Vl=require("path");var G=require("fs");function Ih(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function Zt(t,e){if(!(0,G.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,G.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=Ih(r,e.maxBytes,s,e.retainBytes),o=(0,G.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,G.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,G.ftruncateSync)(o,0),a.length>0&&(0,G.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,G.closeSync)(o)}}function $l(t){let e=[Zt(t.auditPath,{maxBytes:t.auditMaxBytes}),Zt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Zt(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var zl=!1,Ah=new Set(["ts","event","source","appEvent","level"]);function xh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Th(t={}){let e={};for(let[n,r]of Object.entries(t))Ah.has(n)||(e[n]=r);return e}function kh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Th(n)}}function Eh(){zl||((0,Kn.mkdirSync)((0,Vl.dirname)(ct),{recursive:!0}),zl=!0)}var Ms=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(kh(e,n,r,s))}write(e){if(!xh()){Eh();try{let n=JSON.stringify(e)+`
25
- `;Zt(ct,{maxBytes:v.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Kn.appendFileSync)(ct,n)}catch{}}}},_=new Ms;var ke=require("fs"),Yl=require("os"),en=require("path"),Jl=require("crypto"),Ns="claude-hook:",tn="x-vibelet-claude-hook-secret",nn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Ch(t,e){return`#!/usr/bin/env node
18
+ `,typeof n=="function"&&n(null,a),a}});var ml=y(gl=>{var $p="\x1B[47m",Gp="\x1B[40m",Is="\x1B[37m",As="\x1B[30m",We="\x1B[0m",zp=$p+As,Vp=Gp+Is,Yp=function(t,e,n){return{"00":We+" "+t,"01":We+e+"\u2584"+t,"02":We+n+"\u2584"+t,10:We+e+"\u2580"+t,11:" ",12:"\u2584",20:We+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},pl=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},hl=function(t,e,n,r){return pl(t,e,n,r)+pl(t,e,n,r+1)};gl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Vp:zp,c=Yp(o,i?As:Is,i?Is:As),u=We+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[hl(s,r,p,f)];d+=c[hl(s,r,r,f)]+u}return d+=We,typeof n=="function"&&n(null,d),d}});var Sl=y(yl=>{var Jp=fl(),Kp=ml();yl.render=function(t,e,n){return e&&e.small?Kp.render(t,e,n):Jp.render(t,e,n)}});var Ts=y(_l=>{var Xp=Vt();function vl(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function xs(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Zp(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?xs("M",l+n,.5+c+n):xs("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=xs("h",o),o=0)):s++}return r}_l.render=function(e,n,r){let s=Xp.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+vl(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+vl(s.color.dark,"stroke")+' d="'+Zp(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
+ `;return typeof r=="function"&&r(null,f),f}});var bl=y(qn=>{var Qp=Ts();qn.render=Qp.render;qn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+qn.render(n,r);i.writeFile(e,a,s)}});var wl=y(jn=>{var ks=Vt();function eh(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function th(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}jn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=th()),s=ks.getOptions(s);let o=ks.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ks.qrToImageData(l.data,e,s),eh(a,i,o),a.putImageData(l,0,0),i};jn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=jn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Al=y(Yt=>{var nh=qr(),Es=os(),Il=wl(),rh=Ts();function Cs(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!nh())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=Es.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Es.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Yt.create=Es.create;Yt.toCanvas=Cs.bind(null,Il.render);Yt.toDataURL=Cs.bind(null,Il.renderToDataURL);Yt.toString=Cs.bind(null,function(t,e,n){return rh.render(t,n)})});var El=y(Te=>{var xl=qr(),Ps=os(),sh=cl(),Tl=ul(),ih=Sl(),kl=bl();function Jt(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(xl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function oh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Wn(t){switch(t){case"svg":return kl;case"txt":case"utf8":return Tl;case"png":case"image/png":default:return sh}}function ah(t){switch(t){case"svg":return kl;case"terminal":return ih;case"utf8":default:return Tl}}function Kt(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=Ps.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=Ps.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Te.create=Ps.create;Te.toCanvas=Al().toCanvas;Te.toString=function(e,n,r){let s=Jt(e,n,r),i=s.opts?s.opts.type:void 0,o=ah(i);return Kt(o.render,e,s)};Te.toDataURL=function(e,n,r){let s=Jt(e,n,r),i=Wn(s.opts.type);return Kt(i.renderToDataURL,e,s)};Te.toBuffer=function(e,n,r){let s=Jt(e,n,r),i=Wn(s.opts.type);return Kt(i.renderToBuffer,e,s)};Te.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!xl())throw new Error("Too few arguments provided");let i=Jt(n,r,s),o=i.opts.type||oh(e),l=Wn(o).renderToFile.bind(null,e);return Kt(l,n,i)};Te.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Jt(n,r,e.emit.bind(e,"error")),o=Wn("png").renderToFileStream.bind(null,e);Kt(o,n,s)}});var Pl=y((Ky,Cl)=>{Cl.exports=El()});var cu=require("http");var jd=Ye(fo(),1),Wd=Ye(Cr(),1),$d=Ye(Lr(),1),Gd=Ye(En(),1),Ur=Ye(bo(),1);var ie=require("fs/promises"),uu=require("crypto"),Ge=require("path"),du=require("os"),fu=Ye(Pl(),1);var ft=require("child_process"),Wl=require("fs"),W=require("path"),en=require("os");var Xn=require("fs");var Rl=require("os"),$=require("path"),Xt=(0,$.join)((0,Rl.homedir)(),".vibelet"),$n=(0,$.join)(Xt,"logs"),Gn=(0,$.join)(Xt,"data"),lh=(0,$.join)(Xt,"runtime"),Xy=(0,$.join)(lh,"current"),Ll=(0,$.join)(Xt,"identity.json"),Ml=(0,$.join)(Xt,"pairings.json"),Nl=(0,$.join)(Gn,"push-subscriptions.json"),zn=(0,$.join)(Gn,"sessions.json"),ut=(0,$.join)(Gn,"audit.jsonl"),Rs=(0,$.join)(Gn,"uploads"),Vn=(0,$.join)($n,"daemon.stdout.log"),Yn=(0,$.join)($n,"daemon.stderr.log");var Jn={stdout:!1,stderr:!1};function Ol(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function ch(t){return!t.destroyed&&t.writable!==!1}function Bl(t,e){if(Jn[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!ch(n))return Jn[t]=!0,!1;try{return n.write(e,r=>{Ol(r)&&(Jn[t]=!0)}),!0}catch(r){return Ol(r)&&(Jn[t]=!0),!1}}function Zt(t){return Bl("stdout",t)}function Kn(t){return Bl("stderr",t)}var Dl={debug:10,info:20,warn:30,error:40},uh=process.env.VIBE_LOG_LEVEL||"info";function dh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function fh(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Fl=!dh()&&!fh();if(Fl)try{(0,Xn.mkdirSync)($n,{recursive:!0})}catch{}function Hl(t,e,n){if(Dl[t]<Dl[uh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?Kn(s+`
21
+ `):Zt(s+`
22
+ `),Fl){let i=t==="error"||t==="warn"?Yn:Vn;try{(0,Xn.appendFileSync)(i,s+`
23
+ `)}catch{}}}function Ul(t={}){function e(n,r,s){typeof r=="string"?Hl(n,t,r):Hl(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Ul({...t,...n})}}var R=Ul({module:"daemon"});var ph=["fnm_multishells"],hh=6e4,gh=R.child({module:"config"});function ke(t){return ph.some(e=>t.includes(e))}function Ms(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var dt=null;function $l(){if(dt&&!ke(dt.PATH??""))return dt;for(let t of Ms())try{let e=(0,ft.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
+ `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return ke(n.PATH??"")?dt=null:dt=n,n}catch{}return dt={},{}}function mh(t=$l()){let e=(0,en.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,W.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,W.join)(e,".npm-global","bin"),(0,W.join)(e,".local","bin"),(0,W.join)(e,".claude","bin"),n],i=r.split(W.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(W.delimiter)}function Ls(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function ql(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Zn(){let t=$l(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=mh(t),e.HOME||(e.HOME=(0,en.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Qt(t,e=3e3){try{return(0,ft.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Zn()}).trim()||null}catch{return null}}function yh(t){for(let e of Ms())try{let n=(0,ft.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Sh(){let t=(0,en.homedir)();return[(0,W.join)(t,".local","bin","claude"),(0,W.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,W.join)(t,".npm-global","bin","claude")]}function vh(){for(let t of Sh())if(Qt(t))return t;try{let t=(0,ft.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Zn()}).trim();if(t&&!t.includes("cmux")&&Qt(t))return t}catch{}}function _h(){let t=(0,en.homedir)(),e=[process.env.PNPM_HOME,(0,W.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,W.join)(t,".npm-global","bin","codex"),(0,W.join)(t,".local","bin","codex"),...e.map(n=>(0,W.join)(n,"codex"))]}function bh(){let t;for(let n of _h())if(Qt(n)){if(!ke(n))return n;t=n}try{let n=(0,ft.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Zn()}).trim();if(n&&Qt(n)){if(!ke(n))return n;t=t??n}}catch{}let e=yh("codex");if(e&&Qt(e)){if(!ke(e))return e;t=t??e}return t}function Gl(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();return(!n||i-r>hh||!(0,Wl.existsSync)(n)||ke(n))&&(n=t()??e,r=i,gh.info({name:e,path:n,transient:ke(n)},"binary resolved")),n}}var wh=Gl(vh,"claude"),Ih=Gl(bh,"codex");function Ah(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var jl=Ah();function xh(t,e){return{command:Ms()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var v={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:jl.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:jl["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:ql("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:ql("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Ls("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Ls("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Ls("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return wh()},get codexPath(){return Ih()},isTransientPath:ke,execViaLoginShell:xh,buildSanitizedEnv:Zn};var oi=require("crypto"),Wc=require("fs/promises");var ec=require("child_process"),tc=require("fs");var Qn=require("fs"),Yl=require("path");var G=require("fs");function Th(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function tn(t,e){if(!(0,G.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,G.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=Th(r,e.maxBytes,s,e.retainBytes),o=(0,G.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,G.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,G.ftruncateSync)(o,0),a.length>0&&(0,G.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,G.closeSync)(o)}}function zl(t){let e=[tn(t.auditPath,{maxBytes:t.auditMaxBytes}),tn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),tn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Vl=!1,kh=new Set(["ts","event","source","appEvent","level"]);function Eh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Ch(t={}){let e={};for(let[n,r]of Object.entries(t))kh.has(n)||(e[n]=r);return e}function Ph(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Ch(n)}}function Rh(){Vl||((0,Qn.mkdirSync)((0,Yl.dirname)(ut),{recursive:!0}),Vl=!0)}var Ns=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(Ph(e,n,r,s))}write(e){if(!Eh()){Rh();try{let n=JSON.stringify(e)+`
25
+ `;tn(ut,{maxBytes:v.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Qn.appendFileSync)(ut,n)}catch{}}}},_=new Ns;var Ee=require("fs"),Jl=require("os"),nn=require("path"),Kl=require("crypto"),Os="claude-hook:",rn="x-vibelet-claude-hook-secret",sn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Lh(t,e){return`#!/usr/bin/env node
26
26
  const http = require('http');
27
27
  const chunks = [];
28
28
  process.stdin.on('data', (chunk) => chunks.push(chunk));
@@ -36,16 +36,16 @@ process.stdin.on('end', () => {
36
36
  headers: {
37
37
  'Content-Type': 'application/json',
38
38
  'Content-Length': body.length,
39
- '${tn}': ${JSON.stringify(e)}
39
+ '${rn}': ${JSON.stringify(e)}
40
40
  }
41
41
  }, (res) => { res.resume(); });
42
42
  req.on('error', () => {});
43
43
  req.end(body);
44
44
  });
45
45
  process.stdin.resume();
46
- `}function Ph(t,e){return`#!/usr/bin/env node
46
+ `}function Mh(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
- const fallback = ${JSON.stringify(JSON.stringify(nn))};
48
+ const fallback = ${JSON.stringify(JSON.stringify(sn))};
49
49
  const chunks = [];
50
50
  process.stdin.on('data', (chunk) => chunks.push(chunk));
51
51
  process.stdin.on('end', () => {
@@ -58,7 +58,7 @@ process.stdin.on('end', () => {
58
58
  headers: {
59
59
  'Content-Type': 'application/json',
60
60
  'Content-Length': body.length,
61
- '${tn}': ${JSON.stringify(e)}
61
+ '${rn}': ${JSON.stringify(e)}
62
62
  }
63
63
  }, (res) => {
64
64
  const responseChunks = [];
@@ -79,30 +79,33 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function Kl(t,e){let n=(0,en.join)((0,Yl.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Jl.randomUUID)()}`);(0,ke.mkdirSync)(n,{recursive:!0});let r=(0,en.join)(n,"settings.json"),s=(0,en.join)(n,"session_hook_forwarder.cjs"),i=(0,en.join)(n,"permission_hook_forwarder.cjs");return(0,ke.writeFileSync)(s,Ch(t,e),"utf8"),(0,ke.writeFileSync)(i,Ph(t,e),"utf8"),(0,ke.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function Xn(t){if(t)try{(0,ke.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var te=R.child({module:"claude"}),tc="claude-permission-denial:",Rh=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Lh(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Os(t){Lh()&&Vn(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
- `)}function Mh(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
84
- `):""}function Nh(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Oh(t){if(typeof t=="string")return t;let e=Mh(t);return e||(Nh(t)?"":JSON.stringify(t))}function Bh(t){return/requested permissions|haven't granted/i.test(t)}function Xl(t){return t.replace(Rh,"").replace(/\s+/g," ").trim()}function Dh(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Hh(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function Fh(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Ql(t){let e=Xl(t.resultText??""),n=(t.stderrLines??[]).map(Xl).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&Hh(i));if(r)return Fh(r);let s=[e,...n].find(i=>!!i&&!Dh(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Qn(t){return t.startsWith(tc)}var rn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=v.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),te.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),Xn(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Kl(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;te.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Os(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0,this.proc=(0,Zl.spawn)(v.claudePath,n,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,ec.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),te.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
85
- `);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{te.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(te.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{te.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,Xn(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(te.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Ql({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,n){if(te.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return te.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
86
- `),!0}setApprovalMode(e){this.approvalMode=e,te.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),te.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Xn(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(te.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=Oh(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&Bh(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){Os("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Ql({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${tc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;Os("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var ic=require("child_process"),oc=require("fs");var Bs=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();R.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new Bs;var nc=require("node:fs"),Ds=require("node:path"),Uh="@vibelet/cli";function qh(t){try{let e=JSON.parse((0,nc.readFileSync)(t,"utf8"));if(e.name===Uh&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function jh(){return"0.1.14"}var ft=jh();var x=R.child({module:"codex"});function Wh(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function Gh(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function $(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var $h=new Set(["aborted","interrupted","cancelled","canceled"]);function zh(t){let e=k(t);return e?e.toLowerCase():null}function Vh(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Hs(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function Fs(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function ac(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function lc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Yh(t){if(!Array.isArray(t))return null;for(let e of t){let n=$(e);if(!n)continue;let r=k(n.id),s=Array.isArray(n.options)?n.options.map(l=>$(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>k(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>ac(l))??i[0],a=i.find(l=>lc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Jh(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>$(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>$(o)).filter(o=>!!o).map(o=>k(o.label)).filter(o=>!!o)),n=e.some(s=>ac(s)),r=e.some(s=>lc(s));return n&&r}function rc(t){let e=Vh(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Fs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Fs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=k(t.server),r=k(t.tool)??k(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:$(t.arguments)??$(t.input)??{}}:null}return null}function Kh(t){if(!Array.isArray(t))return"";for(let e of t){let n=$(e);if(!n)continue;let r=k(n.question)??k(n.header);if(r)return r}return""}function sc(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Zn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let s=v.codexPath,i,o=this.buildSpawnArgs();if(v.isTransientPath(s)){let c=v.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,ic.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:v.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,oc.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),x.error({error:u,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
87
- `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{x.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(x.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=w.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ft},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=sc(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=sc(this.approvalMode,this.cwd||process.cwd());x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result")).catch(r=>{x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
- `),!0}restorePendingApproval(e){let n=Gh(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=w.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
82
+ `}function Xl(t,e){let n=(0,nn.join)((0,Jl.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Kl.randomUUID)()}`);(0,Ee.mkdirSync)(n,{recursive:!0});let r=(0,nn.join)(n,"settings.json"),s=(0,nn.join)(n,"session_hook_forwarder.cjs"),i=(0,nn.join)(n,"permission_hook_forwarder.cjs");return(0,Ee.writeFileSync)(s,Lh(t,e),"utf8"),(0,Ee.writeFileSync)(i,Mh(t,e),"utf8"),(0,Ee.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function er(t){if(t)try{(0,Ee.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var te=R.child({module:"claude"}),nc="claude-permission-denial:",Nh=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Oh(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Bs(t){Oh()&&Kn(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
+ `)}function Bh(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
84
+ `):""}function Dh(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Hh(t){if(typeof t=="string")return t;let e=Bh(t);return e||(Dh(t)?"":JSON.stringify(t))}function Fh(t){return/requested permissions|haven't granted/i.test(t)}function Zl(t){return t.replace(Nh,"").replace(/\s+/g," ").trim()}function Uh(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function qh(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function jh(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Ql(t){let e=Zl(t.resultText??""),n=(t.stderrLines??[]).map(Zl).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&qh(i));if(r)return jh(r);let s=[e,...n].find(i=>!!i&&!Uh(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function tr(t){return t.startsWith(nc)}var on=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=v.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),te.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),er(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Xl(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;te.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Bs(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0,this.proc=(0,ec.spawn)(v.claudePath,n,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,tc.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),te.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
85
+ `);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{te.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(te.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{te.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,er(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(te.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Ql({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,n){if(te.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return te.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
86
+ `),!0}setApprovalMode(e){this.approvalMode=e,te.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),te.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,er(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(te.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=Hh(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&Fh(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){Bs("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Ql({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${nc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;Bs("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var oc=require("child_process"),ac=require("fs");var Ds=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();R.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new Ds;var rc=require("node:fs"),Hs=require("node:path"),Wh="@vibelet/cli";function $h(t){try{let e=JSON.parse((0,rc.readFileSync)(t,"utf8"));if(e.name===Wh&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Gh(){return"0.1.16"}var pt=Gh();var x=R.child({module:"codex"});function zh(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function Vh(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function z(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var Yh=new Set(["aborted","interrupted","cancelled","canceled"]);function Jh(t){let e=k(t);return e?e.toLowerCase():null}function Kh(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Fs(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function Us(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function lc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function cc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Xh(t){if(!Array.isArray(t))return null;for(let e of t){let n=z(e);if(!n)continue;let r=k(n.id),s=Array.isArray(n.options)?n.options.map(l=>z(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>k(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>lc(l))??i[0],a=i.find(l=>cc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Zh(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>z(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>z(o)).filter(o=>!!o).map(o=>k(o.label)).filter(o=>!!o)),n=e.some(s=>lc(s)),r=e.some(s=>cc(s));return n&&r}function sc(t){let e=Kh(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Us(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Us(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=k(t.server),r=k(t.tool)??k(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:z(t.arguments)??z(t.input)??{}}:null}return null}function Qh(t){if(!Array.isArray(t))return"";for(let e of t){let n=z(e);if(!n)continue;let r=k(n.question)??k(n.header);if(r)return r}return""}function ic(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var nr=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let s=v.codexPath,i,o=this.buildSpawnArgs();if(v.isTransientPath(s)){let c=v.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,oc.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:v.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,ac.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),x.error({error:u,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
87
+ `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{x.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(x.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=w.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:pt},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=ic(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=ic(this.approvalMode,this.cwd||process.cwd());x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result")).catch(r=>{x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
+ `),!0}restorePendingApproval(e){let n=Vh(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=w.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
89
89
  `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),x.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
90
90
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
91
- `)}resolveToolContext(e){let n=$(e?.item)??e??null,r=Hs(n);if(!r)return null;let s=n?rc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?Fs(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),_.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){x.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:Wh(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Jh(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Yh(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},Kh(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/permissions/requestApproval"){x.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}x.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(x.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=$(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||x.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=$(r?.item),i=Hs(s),o=s?rc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=$(r?.item)??r,i=Hs(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{let s=k(r?.reason)??k($(r?.turn)?.reason);x.info({threadId:this.threadId,reason:s},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{let s=$(r?.turn),i=zh(s?.status),o=$(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&$h.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),_.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var M=require("fs/promises"),Qs=require("fs"),Zs=require("readline"),C=require("path"),me=require("os");var Xh=new Set(["New session","Resumed session","Untitled session"]),Qh=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Zh(t){return t.replace(/\s+/g," ").trim()}function er(t){return typeof t!="string"?void 0:Zh(t)||void 0}function cc(t){let e=er(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function pt(t){let e=er(t);return!e||Xh.has(e)||cc(e)}function eg(t){for(let e of t.replace(/\r/g,"").split(`
92
- `)){let n=er(e);if(n&&!tg(n)&&!ng(n))return n}}function tg(t){return Qh.some(e=>t.startsWith(e))}function ng(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function rg(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function Us(t,e=80){if(typeof t!="string")return;let n=eg(t);if(!n)return;let r=rg(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||cc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function We(t,e){for(let n of t){let r=er(n);if(!(!r||pt(r)))return r}return Us(e)}var fc=require("child_process"),ht=require("fs/promises"),Ee=require("path"),qs=require("os"),pc=require("util");var sg=(0,pc.promisify)(fc.execFile),ig=R.child({module:"process-scanner"}),uc=1500,og=15e3,on=null,sn=null;function nr(){on=null}function ag(t){return t.replace(/^['"]|['"]$/g,"")}function lg(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(ag)}function js(t){let e=lg(t);for(let n=0;n<e.length;n+=1){let r=e[n],s=(0,Ee.basename)(r);if(s==="claude"||s==="codex")return{agent:s,args:e.slice(n+1)}}return null}function cg(t,e){let n=js(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function tr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function ug(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function dg(t,e){let n=js(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function fg(t){let e=cg(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(s=>ug(t.agent,s));if(n.length!==1)return null;let r=gt(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function pg(t,e){let n=t,r=e;return(tr(e.confidence)>tr(t.confidence)||tr(e.confidence)===tr(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function hg(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?pg(s,n):n)}return[...e.values()]}async function Ws(t,e){try{let{stdout:n}=await sg(t,e,{maxBuffer:8388608,timeout:uc});return n}catch(n){return ig.warn({file:t,args:e,timeoutMs:uc,error:String(n)},"process scan command failed"),""}}async function dc(t){if(!t.sessionFilePath)return t;let e=await an(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function gg(t){return(await Ws("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
- `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function mg(t){let n=(await Ws("lsof",["-p",String(t),"-Fn"])).split(`
94
- `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function yg(){return(await Ws("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
95
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2],i=js(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function Sg(){let t=await yg();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await gg(e.pid),sessionFiles:await mg(e.pid)})))}function vg(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function _g(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ee.join)((0,qs.homedir)(),".claude","projects",vg(e)),l=(await(0,ht.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let p=await(0,ht.stat)((0,Ee.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Ee.join)(o,c.name),d=gt(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ee.join)((0,qs.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,ht.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ee.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,ht.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await an(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function bg(){let t=await Sg(),e=await Promise.all(t.map(async r=>{let s=fg(r);if(s)return dc(s);if(dg(r.agent,r.command))return null;let i=await _g(r.agent,r.cwd);return i?dc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=hg(e.filter(r=>r!==null));return on={value:n,expiresAt:Date.now()+og},n}async function hc(){return on&&Date.now()<on.expiresAt?on.value:sn||(sn=bg().finally(()=>{sn=null}),sn)}var rr=R.child({module:"inventory"}),wg=6e3,Ig={listScannedSessions:ln,scanRunningSessions:hc,searchSessionContent:yc},mt={daemonActive:3,externalRunning:2,idle:1},gc={high:3,medium:2,low:1};function mc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Ag(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||mt[e.runtime.state]-mt[t.runtime.state]||mc(t,e)}function xg(t,e){return mt[e.state]>mt[t.state]?e:mt[e.state]<mt[t.state]?t:gc[e.confidence]>gc[t.confidence]?e:t}function Tg(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function kg(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Eg(t,e){return e?t?!(pt(e)&&!pt(t)):!0:!1}function $s(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Cg(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...$s()},managed:t.managed,approvalMode:t.approvalMode}}function Pg(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",pid:t.pid,command:t.command}}}function Rg(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function Lg(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Eg(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=xg(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:kg(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:Tg(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode})}}function Mg(...t){let e=new Map;for(let n of t)Lg(e,n);return[...e.values()]}function Ng(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&rr.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function Og(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Bg(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=Mg(t.sessionRecords.map(Cg),t.scannedSessions,t.runningSessions.map(S=>Pg(S,t.scannedAt)),t.activeSessions.map(Rg)),c=t.deletedSessionIds?.size?l.filter(S=>!t.deletedSessionIds?.has(S.sessionId)):l,u=Ng(c,r,s,i,o),d=u.filter(S=>S.runtime.state!=="idle"||S.managed).sort(Ag),f=u.filter(S=>S.runtime.state==="idle"&&!S.managed).sort(mc),p=Og(f,n),h=f.slice(p,p+a),m=p+h.length<f.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...d,...h],nextCursor:m}}function Gs(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;rr.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||rr.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}async function sr(t){let e=new Date().toISOString(),n={...Ig,...t.loaders??{}},r=Math.max(250,t.sourceTimeoutMs??wg),s=[],[i,o,a]=await Promise.all([Gs("scanner.sessions",()=>n.listScannedSessions(t.agent,t.cwd,s),[],r,s),Gs("process.running_sessions",()=>n.scanRunningSessions(),[],r),t.search?Gs("scanner.search_content",()=>n.searchSessionContent(t.search,t.agent),void 0,r):Promise.resolve(void 0)]);return t.search&&rr.info({search:t.search,contentMatches:a?.size??0,scanned:i.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Bg({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:i,runningSessions:o,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,a)}var Ce=R.child({module:"scanner"});function wc(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Ic=3e4,Js=wc(Ic),Ks=wc(Ic),zs=new Map,Vs=new Map,yt=24;function or(){Js.clear(),Ks.clear()}function Xs(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function St(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*Ac(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
96
- `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Ys=512*1024;async function xc(t,e){if(e<=Ys)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Buffer.alloc(Ys),{bytesRead:s}=await n.read(r,0,Ys,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function ei(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function Tc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?ei(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function ti(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var Dg=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function Hg(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Dg.some(r=>n.startsWith(r)):!1}function ni(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=ti(t.message.content);return Hg(t,e)?"":e}function kc(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function ir(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:$s()}}function gt(t,e){let n=(0,C.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function Fg(t,e){let n=await xc(t,e),r=Ac(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=We([u.customTitle,u.summary])),!l){let d=ni(u),f=We([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("claude",t)||(0,C.basename)(t,".jsonl"),cwd:s,title:o??l??We([],a)}:null}async function Ug(t,e){let n=await xc(t,e),r=Ac(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=We([u.payload?.title,u.title])),!l){let d=Tc(u),f=d&&!kc(d)?We([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("codex",t)||(0,C.basename)(t,".jsonl"),cwd:s,title:o??l??We([],a)}:null}async function an(t,e){let n=await(0,M.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Fg(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Ug(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Sc(t,e){let n=(0,C.join)((0,me.homedir)(),".claude","projects");try{let r;t?r=[Xs(t)]:r=(await(0,M.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,C.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,C.join)(c,d))}let i=await St(s,yt,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await St(i,yt,async l=>{let c=await an(l.path,"claude");return c&&e&&e.push(ir(c)),c})).filter(l=>l!==null).map(l=>ir(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Ce.warn({error:String(r)},"failed to list claude sessions"),[]}}async function vc(t,e){let n=(0,C.join)((0,me.homedir)(),".codex","sessions");try{let r=await(0,M.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,C.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,C.join)(c,d),p=await(0,M.readdir)(f).catch(()=>[]);for(let h of p){let g=(0,C.join)(f,h),m=await(0,M.readdir)(g).catch(()=>[]);for(let S of m)S.endsWith(".jsonl")&&s.push((0,C.join)(g,S))}}}let i=await St(s,yt,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await St(i,yt,async l=>{let c=await an(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(ir(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>ir(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Ce.warn({error:String(r)},"failed to list codex sessions"),[]}}async function ln(t,e,n){let s=`list:${(0,me.homedir)()}:${t??"all"}:${e??""}`,i=Js.get(s);if(i)return i;let o=zs.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Sc(e,n);else if(t==="codex")l=await vc(e,n);else{let[c,u]=await Promise.all([Sc(e,n),vc(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return Js.set(s,l),l})();return zs.set(s,a),a.finally(()=>zs.delete(s)),a}async function yc(t,e){let r=`search:${(0,me.homedir)()}:${t}:${e??"all"}`,s=Ks.get(r);if(s)return s;let i=Vs.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,C.join)((0,me.homedir)(),".claude","projects");try{let f=await(0,M.readdir)(d,{withFileTypes:!0}),p=[];for(let g of f){if(!g.isDirectory())continue;let m=(0,C.join)(d,g.name),S=await(0,M.readdir)(m).catch(()=>[]);for(let P of S)P.endsWith(".jsonl")&&p.push((0,C.join)(m,P))}let h=await St(p,yt,g=>_c(g,l,"claude"));for(let g of h)g&&a.add(g)}catch(f){Ce.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,C.join)((0,me.homedir)(),".codex","sessions");try{let f=[];async function p(g){let m=await(0,M.readdir)(g,{withFileTypes:!0}).catch(()=>[]);for(let S of m){let P=(0,C.join)(g,S.name);S.isDirectory()?await p(P):S.name.endsWith(".jsonl")&&f.push(P)}}await p(d);let h=await St(f,yt,g=>_c(g,l,"codex"));for(let g of h)g&&a.add(g)}catch(f){Ce.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Ks.set(r,a),a})();return Vs.set(r,o),o.finally(()=>Vs.delete(r)),o}async function _c(t,e,n){let r=(0,Qs.createReadStream)(t,{encoding:"utf-8"}),s=(0,Zs.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?qg:jg,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||gt(n,t):null}function qg(t){return t?.type==="user"&&t.message?.role==="user"?ni(t):t?.type==="assistant"&&t.message?.role==="assistant"?ti(t.message.content):""}function jg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return ei(t.payload.content)}let e=Tc(t);return e||""}async function bc(t,e){let n=(0,Qs.createReadStream)(t,{encoding:"utf-8"}),r=(0,Zs.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function cn(t,e,n){let r=[];if(e==="claude"){let s=(0,C.join)((0,me.homedir)(),".claude","projects");try{let i=n?[Xs(n)]:[],o=await(0,M.readdir)(s).catch(()=>[]),a=n?[...i,...o.filter(l=>l!==Xs(n))]:o;for(let l of a){let c=(0,C.join)(s,l,`${t}.jsonl`);try{if(await bc(c,u=>{if(u.type==="user"&&u.message?.role==="user"){let d=ni(u);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=ti(u.message.content);d&&r.push({role:"assistant",content:d})}}),r.length>0)break}catch(u){u.code!=="ENOENT"&&Ce.warn({error:String(u)},"failed to read claude session file")}}}catch(i){Ce.warn({error:String(i)},"failed to read claude session history")}}else if(e==="codex"){let s=(0,C.join)((0,me.homedir)(),".codex","sessions");try{let i=await Ec(s,t);i&&await bc(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=ei(o.payload.content);l&&(a==="user"&&kc(l)||r.push({role:a,content:l}))})}catch(i){Ce.warn({error:String(i)},"failed to read codex session history")}}return r}async function Ec(t,e){try{let n=await(0,M.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,C.join)(t,r.name);if(r.isDirectory()){let i=await Ec(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Ce.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var vt=require("fs"),Rc=require("path");var Wg=500,Cc=200;function Gg(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Cc?e:e.slice(-Cc)}function $g(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function zg(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Pc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Gg(t.acceptedClientMessageIds),pendingApproval:zg(t.pendingApproval)}}function Vg(t){if(Array.isArray(t))return{records:t.map(Pc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Pc):[],deletedSessionIds:$g(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var ar=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},Wg)}loadFromDisk(){try{let e=(0,vt.readFileSync)(Wn,"utf-8");return Vg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,vt.mkdirSync)((0,Rc.dirname)(Wn),{recursive:!0}),(0,vt.writeFileSync)(Wn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var _t=require("path"),Lc=require("os");function lr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,_t.join)((0,Lc.homedir)(),t.slice(2)):t}function Yg(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function Mc(t,e){let n=lr(Yg(t));if(!n||(0,_t.isAbsolute)(n))return n;let r=lr(e??"");return r?(0,_t.resolve)(r,n):n}var Nc={approvalRequestV1:"vibelet.approvalRequest.v1"};var bt=require("fs"),Oc=require("path");function Jg(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function Kg(t){try{let e=(0,bt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Jg):[]}catch{return[]}}function un(t,e){(0,bt.mkdirSync)((0,Oc.dirname)(t),{recursive:!0}),(0,bt.writeFileSync)(t,JSON.stringify(e,null,2)+`
97
- `,"utf8")}var cr=class{constructor(e=Ml){this.pushSubscriptionsPath=e;this.records=Kg(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],un(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,un(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,un(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&un(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],un(this.pushSubscriptionsPath,this.records)}};var z=R.child({module:"push"}),Xg="https://exp.host/--/api/v2/push/send",Qg="https://exp.host/--/api/v2/push/getReceipts",Zg=[0,1e3,3e3],dn=new cr;function em(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function tm(t){return new Promise(e=>{setTimeout(e,t)})}function Bc(t){return t==="DeviceNotRegistered"}function nm(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function rm(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function sm(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function im(t,e,n,r){let s=new Map(t);for(let i of Zg){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Qg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){z.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){z.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){z.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=sm(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(z.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Bc(f)){let p=r.unregisterToken(u);z.info({token:u,errorCode:f,removed:p},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&z.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function om(t){let e=t?.pushStore??dn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??tm;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,...em(a)&&a.eventType==="approval_request"?{categoryId:Nc.approvalRequestV1}:{}}));try{let u=await n(Xg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){z.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){z.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=nm(d,l),h=rm(d,l);for(let{token:g,ticket:m}of p){let S=m.details?.error;if(z.error({token:g,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),Bc(S)){let P=e.unregisterToken(g);z.info({token:g,errorCode:S,removed:P},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),h.size>0&&await im(h,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function ri(t,e){dn.register(t,e),z.info({deviceId:t,token:e,total:dn.count()},"push token registered")}function si(t,e){let n=dn.unregister(t,e);z.info({deviceId:t,token:e,total:dn.count(),removed:n},"push token unregistered")}var ur=om();var b=R.child({module:"manager"}),am="Done.",lm="Approval required",Dc=180,fr=200;function dr(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>fr&&e.splice(0,e.length-fr));return e}function ue(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:dr(t.acceptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function Hc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Qn(e)}function Fc(t,e,n){return{sessionId:t,agent:e,...n}}function cm(t){return t.startsWith(Ns)}function Uc(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var pr=class{constructor(e=ur){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new ar;idleSweepInterval=null;globalClients=new Set;startIdleSweep(){v.idleTimeoutMs<=0&&v.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=v.idleTimeoutMs,r=v.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(b.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),w.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;b.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),w.increment("driver.stall_timeout",{agent:o.agent}),_.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.isResponding=!1,o.currentReplyText="",this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId);continue}o.pendingApproval||n<=0||a<n||(b.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),w.increment("driver.idle_timeout",{agent:o.agent}),_.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(b.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!Hc(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(i.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:i.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId);return}b.warn({sessionId:e.sessionId,requestId:i.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description,...i.approvalContext?{approvalContext:i.approvalContext}:{}},this.pushSender(lm,this.buildPushBody(`${e.title||e.sessionId}: ${i.description||i.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:i.requestId,eventType:"approval_request"})}n==="claude"&&i.type==="approval.request"&&Qn(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:b.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{b.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),w.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=!!(e.pendingApproval&&(e.agent==="codex"||i===0&&Hc(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(ue(e)),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),e.driver.sendPrompt(r),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=w.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof rn))return;let s=r??(0,ii.randomUUID)().replace(/-/g,"");return n.configureHookBridge(v.port,s),s}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=nn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&cm(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),nn;if(r.approvalMode==="autoApprove")return Uc(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return nn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${Ns}${l.trim()||(0,ii.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(h=>{f=h});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:h=>{r.pendingClaudeHookApprovals.delete(c),f(h)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=dr(r?.acceptedClientMessageIds),p=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.pendingApproval??l,c=h.title||c,u=h.createdAt||u,d=h.lastActivityAt||d,f=dr(h.acceptedClientMessageIds,f),p="record";else if(!r){let m=(await ln(n??i)).find(S=>S.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p="scanner")}if(!i&&n&&(i=n,p=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:p,managed:r?.managed??h?.managed,isResponding:r?.isResponding||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Fc(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Fc(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(ue(e)),this.updateGauges(),this.touchSession(e.sessionId),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Dc?n:`${n.slice(0,Math.max(1,Dc-3)).trimEnd()}...`:am}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(ue(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;w.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return ln(e,n)}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){sr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,s,i,o){s=lr(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,qc.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return b.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(a){b.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=this.createDriver(r),l=this.configureDriverBeforeStart(r,a);if(r==="codex"){let p=`pending_${Date.now()}`;b.info({sessionId:p,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:p,agent:r,cwd:s,approvalMode:i});let h={sessionId:p,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(p,h),this.registerClaudeHookSession(h),this.store.upsert(ue(h)),this.updateGauges(),or(),nr(),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:p}),this.startPendingCodexSession(h,e);return}let c=w.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();b.info({sessionId:u,agent:r,spawnMs:d},"session created"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(ue(f)),this.updateGauges(),or(),nr(),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){b.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await cn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(h))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=w.startTimer("driver.spawn"),p=this.createDriver(s),h=this.configureDriverBeforeStart(s,p),g=await p.start(c,r,u),m=f();b.info({sessionId:g,agent:s,spawnMs:m},"session resumed"),w.increment("session.resume",{agent:s}),_.emit("session.resume",{sessionId:g,agent:s,cwd:c});let S={sessionId:g,agent:s,cwd:c,approvalMode:u,driver:p,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:h,pendingClaudeHookApprovals:new Map};this.sessions.set(g,S),this.registerClaudeHookSession(S),this.store.upsert(ue(S)),this.updateGauges(),this.bindDriverLifecycle(S,s," (resumed)",e),this.restoreDriverPendingApproval(p,S.pendingApproval);let P=await cn(r,s,c);if(P.length>0||S.pendingApproval){b.info({sessionId:r,historyCount:P.length},"sending history messages");let ie={type:"session.history",sessionId:g,messages:P,approvalMode:u,pendingApproval:S.pendingApproval};e.readyState===1&&e.send(JSON.stringify(ie))}this.reply(e,n,!0,{sessionId:g})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>fr&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-fr))}async sendMessage(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(!a||!a.driver){let l=await this.resolveReconnectSession(r,i,a);if(!l){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:l.agent,source:l.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:l.agent,source:l.source}),_.emit("session.reconnect",{sessionId:r,agent:l.agent,source:l.source});try{let c=this.createDriver(l.agent),u=this.configureDriverBeforeStart(l.agent,c,a?.claudeHookSecret);await c.start(l.cwd,r,l.approvalMode),this.restoreDriverPendingApproval(c,l.pendingApproval),a?(a.approvalMode=l.approvalMode,a.pendingApproval=l.pendingApproval,a.driver=c,a.active=!0,a.clients.add(e),a.lastActivityAt=l.lastActivityAt,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=dr(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{},a.startupInProgress=!1,a.bufferedPrompts=a.bufferedPrompts??[],a.startupToken=a.startupToken??0,a.claudeHookSecret=u??a.claudeHookSecret,a.pendingClaudeHookApprovals=a.pendingClaudeHookApprovals??new Map):(a={sessionId:r,agent:l.agent,cwd:l.cwd,approvalMode:l.approvalMode,driver:c,clients:new Set([e]),title:l.title,createdAt:l.createdAt,lastActivityAt:l.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l.managed,pendingApproval:l.pendingApproval,claudeHookSecret:u,pendingClaudeHookApprovals:new Map},this.sessions.set(r,a)),this.registerClaudeHookSession(a),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(ue(a)),this.updateGauges()}catch(c){this.reply(e,n,!1,void 0,`Failed to reconnect: ${c}`);return}}if(a.clients.add(e),a.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),_.emit("session.send",{sessionId:r,agent:a.agent,messagePreview:s.slice(0,100)}),pt(a.title)){let l=Us(s,50);l&&l!==a.title&&(a.title=l),this.store.upsert(ue(a))}if(o&&this.rememberAcceptedClientMessage(a,o),this.touchSession(a.sessionId),a.startupInProgress){a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=s,a.bufferedPrompts.push(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(a.isResponding){a.bufferedPrompts.push(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=s,a.driver.sendPrompt(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await sr({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(f){b.warn({error:String(f)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let f=a??c.sessions.find(g=>g.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let h=await this.resolveReconnectSession(o,f,p);if(h){let g=await cn(o,h.agent,p?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:g,isResponding:p?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(p),approvalMode:p?.approvalMode??h.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{}}}}let d=this.collectReconnectPendingApprovals();w.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{},...d.length>0?{pendingApprovals:d}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),l.resolve(Uc(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&Qn(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(ue(e)),this.updateGauges(),this.touchSession(e.sessionId),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(a.approvalMode=s,this.store.upsert(a),b.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(ue(i)),b.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}_.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:s.agent},"stopping session"),_.emit("session.stop",{sessionId:r,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(b.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),_.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),or(),nr(),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r);if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(r)?.cwd??"",a=this.store.find(r),l=await cn(r,s,o);b.info({sessionId:r,historyCount:l.length,isResponding:i?.isResponding,approvalMode:i?.approvalMode},"sending history");let c={type:"session.history",sessionId:r,messages:l,isResponding:i?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(i),approvalMode:i?.approvalMode??a?.approvalMode,pendingApproval:i?.pendingApproval??a?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(c)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await sr({agent:r,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new rn;case"codex":return new Zn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&w.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function oi(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var jc=require("child_process");function um(t,e){return(0,jc.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function dm(t){let e=t.split(`
98
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Wc(t,e=um){let n;try{n=dm(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var wt=require("fs"),ai=require("os"),$c=require("crypto"),zc=require("path");function Vc(t){return(0,$c.randomBytes)(t).toString("base64url")}function fm(){return`d_${Vc(12)}`}function pm(){return(0,ai.hostname)()}function hm(){let t=(0,ai.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function gm(t){return{daemonId:fm(),daemonSecret:Vc(32),displayName:pm(),canonicalHost:hm(),port:t,createdAt:new Date().toISOString()}}function Gc(t,e){(0,wt.mkdirSync)((0,zc.dirname)(e),{recursive:!0}),(0,wt.writeFileSync)(e,JSON.stringify(t,null,2)+`
99
- `,"utf8")}function Yc(t,e=Rl){try{let r=(0,wt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,Gc(i,e)),i}}catch{}let n=gm(t);return Gc(n,e),n}var It=require("crypto"),At=require("fs"),Kc=require("path");function li(t){return(0,It.randomBytes)(t).toString("base64url")}function ci(t){return(0,It.createHash)("sha256").update(t).digest("hex")}function Jc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,It.timingSafeEqual)(n,r)}function mm(t){try{let e=(0,At.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function fn(t,e){(0,At.mkdirSync)((0,Kc.dirname)(t),{recursive:!0}),(0,At.writeFileSync)(t,JSON.stringify(e,null,2)+`
100
- `,"utf8")}var hr=class{constructor(e=Ll){this.pairingsPath=e;this.records=mm(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${li(8)}`,r=li(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=li(32),i={deviceId:e,deviceName:n,tokenHash:ci(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),fn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=ci(n);return Jc(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),fn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=ci(e),s=this.records.find(i=>!i.revokedAt&&Jc(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),fn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),fn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),fn(this.pairingsPath,this.records)}};function xt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function ym(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Xc(t,e){return ym(t)??e}function ui(t,e){return!!(t&&e&&t===e)}function Qc(t,e,n,r=!0){return t?ui(t,e)?!0:!!n(t,r):!1}var eu=require("child_process");function di(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function tu(t){if(!di(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Sm(t){if(!di(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function vm(t){if(!di(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function fi(t){return!!t&&!Sm(t)&&!vm(t)}function Tt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function nu(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function _m(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||fi(s.address)&&(tu(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function Zc(t){let e=JSON.parse(t),n=Tt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>Tt(o)).filter(o=>!!o).filter(o=>tu(o)&&fi(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function ru(t=eu.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Zc(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Zc(n)}catch{return{fallbackHosts:[]}}}function su(t){let e=Tt(t.canonicalHost),n=Tt(t.configuredCanonicalHost)||Tt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],..._m(t.interfaces)].map(s=>Tt(s)).filter(s=>!!s).filter(s=>fi(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function iu(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=R.child({module:"daemon"}),pn=R.child({module:"ws"}),H=Yc(v.port),J=new pr((t,e,n)=>ur(t,e,{daemonId:H.daemonId,canonicalHost:H.canonicalHost,...n??{}})),Re=new hr,gr=new Set,Pe=new WeakMap,ou=!1,uu=Date.now(),kt=null;function Et(){let t=ru();return su({canonicalHost:H.canonicalHost,configuredCanonicalHost:v.canonicalHost,configuredFallbackHosts:nu(v.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,lu.networkInterfaces)()})}async function pi(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function F(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function bm(t){let e=(0,mr.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function du(){let t=Re.openWindow(),e=Et(),n=e.canonicalHost,r=H.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(v.relayUrl)try{let i=new URL(v.relayUrl);n=i.hostname,r=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{W.warn({relayUrl:v.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:H.daemonId,displayName:H.displayName,canonicalHost:n,fallbackHosts:s,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function wm(t){let e=await(0,Ge.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let s=await(0,Ge.stat)((0,mr.join)(t,r)).catch(()=>null);s&&n.push({name:r,isDirectory:s.isDirectory()})}return n.sort((r,s)=>r.isDirectory!==s.isDirectory?r.isDirectory?-1:1:r.name.localeCompare(s.name)),{entries:n}}var hn=(0,au.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${v.port}`);if(n.pathname==="/health"){let s=Et(),i={status:"ok",version:ft,daemonId:H.daemonId,displayName:H.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-uu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:Re.pairedCount(),wsClients:se.clients.size,drivers:J.getDriverCounts(),metrics:w.snapshot()};v.relayUrl&&(i.relayUrl=v.relayUrl),F(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!xt(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}F(e,200,du());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!xt(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}Re.reset(),F(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!xt(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}F(e,200,{status:"stopping"}),setTimeout(()=>$e("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!xt(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}try{let s=await pi(t),i=t.headers[tn],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),F(e,200,{ok:!0})}catch(s){F(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!xt(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}try{let s=await pi(t),i=t.headers[tn],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);F(e,200,a)}catch(s){F(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await pi(t);if(s.daemonId!==H.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){F(e,400,{error:"invalid_pair_request"});return}if(!Re.consumeWindow(s.pairNonce)){F(e,401,{error:"pair_window_expired"});return}let o=Re.issuePairToken(s.deviceId,s.deviceName),a=Et();F(e,200,{daemonId:H.daemonId,displayName:H.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:H.port,deviceId:s.deviceId,pairToken:o})}catch(s){F(e,400,{error:String(s)})}return}let r=Xc(t.headers.authorization,n.searchParams.get("token"));if(!Qc(r,v.legacyToken,(s,i)=>Re.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=Mc(s,i);if(!(await(0,Ge.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=bm(o),c=await(0,Ge.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${ft}`)}),se=new Fr.default({server:hn});hn.on("connection",t=>{gr.add(t),t.on("close",()=>{gr.delete(t)})});se.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${v.port}`).searchParams.get("token");if(r&&ui(r,v.legacyToken))Pe.set(t,{authMode:"query_token"}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=Re.validateAnyPairToken(r);if(s)Pe.set(t,{authMode:"query_token",deviceId:s.deviceId}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{w.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}pn.info({clients:se.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",se.clients.size),_.emit("ws.connect",{clients:se.clients.size,authMode:Pe.get(t)?.authMode??"pending",deviceId:Pe.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(iu(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Pe.has(t)){if(o.action==="auth.hello"&&o.daemonId===H.daemonId&&Re.validatePairToken(o.deviceId,o.pairToken)){Pe.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),w.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:H.daemonId,displayName:H.displayName}}));return}if(o.action==="auth.hello"){w.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}w.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)_.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?W.error:a.level==="warn"?W.warn:W.info).call(W,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await wm(o.path);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=Pe.get(t);oi(i,{deviceId:a?.deviceId,registerToken:ri,unregisterToken:si,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Pe.get(t);oi(i,{deviceId:a?.deviceId,registerToken:ri,unregisterToken:si,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){pn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{pn.info({clients:se.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",se.clients.size),_.emit("ws.disconnect",{clients:se.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{pn.error({error:s.message},"websocket error")})});function hi(){for(let t of gr)try{t.destroy()}catch{}gr.clear()}function fu(){let t=$l({auditPath:ct,stdoutLogPath:Gn,stderrLogPath:$n,auditMaxBytes:v.auditMaxBytes,logMaxBytes:v.daemonLogMaxBytes});t.trimmedFiles>0&&W.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function Im(){kt||(kt=setInterval(fu,v.storageHousekeepingIntervalMs),kt.unref())}function Am(){kt&&(clearInterval(kt),kt=null)}function $e(t,e=0){if(!ou){ou=!0,W.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-uu)/1e3)}),w.stopPeriodicLog(),Am(),J.shutdown();for(let n of se.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}se.close(n=>{n&&W.error({error:String(n)},"websocket close error")}),hn.close(n=>{if(n){W.error({error:String(n)},"http close error"),hi(),process.exit(1);return}hi(),process.exit(e)}),setTimeout(()=>{W.error("force exiting after shutdown timeout"),hi(),process.exit(e||1)},3e3).unref()}}se.on("error",t=>{pn.error({error:t.message},"wss error")});hn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Wc(v.port).filter(n=>n.pid!==process.pid);W.error({port:v.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else W.error({error:String(t)},"server error");$e(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>$e("SIGINT"));process.once("SIGTERM",()=>$e("SIGTERM"));process.once("SIGHUP",()=>$e("SIGHUP"));process.once("SIGTTIN",()=>$e("SIGTTIN"));process.once("SIGTSTP",()=>$e("SIGTSTP"));process.on("uncaughtException",t=>{W.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{W.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});hn.listen(v.port,async()=>{fu(),_.emit("daemon.start",{port:v.port}),w.startPeriodicLog(),Im(),W.info({port:v.port,daemonId:H.daemonId,displayName:H.displayName,canonicalHost:Et().canonicalHost,fallbackHosts:Et().fallbackHosts,claudePath:v.claudePath,codexPath:v.codexPath,auditMaxBytes:v.auditMaxBytes,daemonLogMaxBytes:v.daemonLogMaxBytes,storageHousekeepingIntervalMs:v.storageHousekeepingIntervalMs,turnStallTimeoutMs:v.turnStallTimeoutMs},"daemon started");let t=Et(),e=du();Kt(`
91
+ `)}resolveToolContext(e){let n=z(e?.item)??e??null,r=Fs(n);if(!r)return null;let s=n?sc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?Us(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),_.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){x.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:zh(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Zh(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Xh(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},Qh(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/permissions/requestApproval"){x.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}x.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(x.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=z(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||x.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=z(r?.item),i=Fs(s),o=s?sc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=z(r?.item)??r,i=Fs(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{let s=k(r?.reason)??k(z(r?.turn)?.reason);x.info({threadId:this.threadId,reason:s},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{let s=z(r?.turn),i=Jh(s?.status),o=z(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&Yh.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),_.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var M=require("fs/promises"),Qs=require("fs"),ei=require("readline"),C=require("path"),ye=require("os");var eg=new Set(["New session","Resumed session","Untitled session"]),tg=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function ng(t){return t.replace(/\s+/g," ").trim()}function rr(t){return typeof t!="string"?void 0:ng(t)||void 0}function uc(t){let e=rr(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function ht(t){let e=rr(t);return!e||eg.has(e)||uc(e)}function rg(t){for(let e of t.replace(/\r/g,"").split(`
92
+ `)){let n=rr(e);if(n&&!sg(n)&&!ig(n))return n}}function sg(t){return tg.some(e=>t.startsWith(e))}function ig(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function og(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function qs(t,e=80){if(typeof t!="string")return;let n=rg(t);if(!n)return;let r=og(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||uc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function $e(t,e){for(let n of t){let r=rr(n);if(!(!r||ht(r)))return r}return qs(e)}var hc=require("child_process"),gt=require("fs/promises"),Ce=require("path"),js=require("os"),gc=require("util");var ag=(0,gc.promisify)(hc.execFile),dc=R.child({module:"process-scanner"}),fc=1500,lg=15e3,ln=null,an=null;function ir(){ln=null}function cg(t){return t.replace(/^['"]|['"]$/g,"")}function ug(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(cg)}function Ws(t){let e=ug(t);for(let n=0;n<e.length;n+=1){let r=e[n],s=(0,Ce.basename)(r);if(s==="claude"||s==="codex")return{agent:s,args:e.slice(n+1)}}return null}function dg(t,e){let n=Ws(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function sr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function fg(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function pg(t,e){let n=Ws(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function hg(t){let e=dg(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(s=>fg(t.agent,s));if(n.length!==1)return null;let r=mt(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function gg(t,e){let n=t,r=e;return(sr(e.confidence)>sr(t.confidence)||sr(e.confidence)===sr(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function mg(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?gg(s,n):n)}return[...e.values()]}function yg(t){try{return process.kill(t,0),!0}catch{return!1}}async function $s(t,e){try{let{stdout:n}=await ag(t,e,{maxBuffer:8388608,timeout:fc});return n}catch(n){let r=String(n);return r.includes("ESRCH")||r.includes("No such process")?dc.debug({file:t,args:e,error:r},"process scan command skipped \u2014 process exited"):dc.warn({file:t,args:e,timeoutMs:fc,error:r},"process scan command failed"),""}}async function pc(t){if(!t.sessionFilePath)return t;let e=await cn(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function Sg(t){return(await $s("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function vg(t){let n=(await $s("lsof",["-p",String(t),"-Fn"])).split(`
94
+ `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function _g(){return(await $s("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
95
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2],i=Ws(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function bg(){let e=(await _g()).filter(n=>yg(n.pid));return Promise.all(e.map(async n=>({pid:n.pid,agent:n.agent,command:n.command,cwd:await Sg(n.pid),sessionFiles:await vg(n.pid)})))}function wg(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Ig(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ce.join)((0,js.homedir)(),".claude","projects",wg(e)),l=(await(0,gt.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let p=await(0,gt.stat)((0,Ce.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Ce.join)(o,c.name),d=mt(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ce.join)((0,js.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,gt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ce.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,gt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await cn(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function Ag(){let t=await bg(),e=await Promise.all(t.map(async r=>{let s=hg(r);if(s)return pc(s);if(pg(r.agent,r.command))return null;let i=await Ig(r.agent,r.cwd);return i?pc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=mg(e.filter(r=>r!==null));return ln={value:n,expiresAt:Date.now()+lg},n}async function mc(){return ln&&Date.now()<ln.expiresAt?ln.value:an||(an=Ag().finally(()=>{an=null}),an)}var or=R.child({module:"inventory"}),xg=6e3,Tg={listScannedSessions:un,scanRunningSessions:mc,searchSessionContent:vc},yt={daemonActive:3,externalRunning:2,idle:1},yc={high:3,medium:2,low:1};function Sc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function kg(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||yt[e.runtime.state]-yt[t.runtime.state]||Sc(t,e)}function Eg(t,e){return yt[e.state]>yt[t.state]?e:yt[e.state]<yt[t.state]?t:yc[e.confidence]>yc[t.confidence]?e:t}function Cg(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Pg(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Rg(t,e){return e?t?!(ht(e)&&!ht(t)):!0:!1}function zs(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Lg(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...zs()},managed:t.managed,approvalMode:t.approvalMode}}function Mg(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",pid:t.pid,command:t.command}}}function Ng(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function Og(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Rg(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=Eg(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:Pg(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:Cg(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode})}}function Bg(...t){let e=new Map;for(let n of t)Og(e,n);return[...e.values()]}function Dg(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&or.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function Hg(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Fg(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=Bg(t.sessionRecords.map(Lg),t.scannedSessions,t.runningSessions.map(S=>Mg(S,t.scannedAt)),t.activeSessions.map(Ng)),c=t.deletedSessionIds?.size?l.filter(S=>!t.deletedSessionIds?.has(S.sessionId)):l,u=Dg(c,r,s,i,o),d=u.filter(S=>S.runtime.state!=="idle"||S.managed).sort(kg),f=u.filter(S=>S.runtime.state==="idle"&&!S.managed).sort(Sc),p=Hg(f,n),h=f.slice(p,p+a),m=p+h.length<f.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...d,...h],nextCursor:m}}function Gs(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;or.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||or.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}async function ar(t){let e=new Date().toISOString(),n={...Tg,...t.loaders??{}},r=Math.max(250,t.sourceTimeoutMs??xg),s=[],[i,o,a]=await Promise.all([Gs("scanner.sessions",()=>n.listScannedSessions(t.agent,t.cwd,s),[],r,s),Gs("process.running_sessions",()=>n.scanRunningSessions(),[],r),t.search?Gs("scanner.search_content",()=>n.searchSessionContent(t.search,t.agent),void 0,r):Promise.resolve(void 0)]);return t.search&&or.info({search:t.search,contentMatches:a?.size??0,scanned:i.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Fg({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:i,runningSessions:o,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,a)}var Pe=R.child({module:"scanner"});function Ac(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var xc=3e4,Ks=Ac(xc),Xs=Ac(xc),Vs=new Map,Ys=new Map,St=24;function cr(){Ks.clear(),Xs.clear()}function Zs(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function vt(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*Tc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
96
+ `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Js=512*1024;async function kc(t,e){if(e<=Js)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Buffer.alloc(Js),{bytesRead:s}=await n.read(r,0,Js,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function ti(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function Ec(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?ti(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function ni(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var Ug=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function qg(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Ug.some(r=>n.startsWith(r)):!1}function ri(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=ni(t.message.content);return qg(t,e)?"":e}function Cc(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function lr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:zs()}}function mt(t,e){let n=(0,C.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function jg(t,e){let n=await kc(t,e),r=Tc(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=$e([u.customTitle,u.summary])),!l){let d=ri(u),f=$e([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||mt("claude",t)||(0,C.basename)(t,".jsonl"),cwd:s,title:o??l??$e([],a)}:null}async function Wg(t,e){let n=await kc(t,e),r=Tc(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=$e([u.payload?.title,u.title])),!l){let d=Ec(u),f=d&&!Cc(d)?$e([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||mt("codex",t)||(0,C.basename)(t,".jsonl"),cwd:s,title:o??l??$e([],a)}:null}async function cn(t,e){let n=await(0,M.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await jg(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Wg(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function _c(t,e){let n=(0,C.join)((0,ye.homedir)(),".claude","projects");try{let r;t?r=[Zs(t)]:r=(await(0,M.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,C.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,C.join)(c,d))}let i=await vt(s,St,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await vt(i,St,async l=>{let c=await cn(l.path,"claude");return c&&e&&e.push(lr(c)),c})).filter(l=>l!==null).map(l=>lr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Pe.warn({error:String(r)},"failed to list claude sessions"),[]}}async function bc(t,e){let n=(0,C.join)((0,ye.homedir)(),".codex","sessions");try{let r=await(0,M.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,C.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,C.join)(c,d),p=await(0,M.readdir)(f).catch(()=>[]);for(let h of p){let g=(0,C.join)(f,h),m=await(0,M.readdir)(g).catch(()=>[]);for(let S of m)S.endsWith(".jsonl")&&s.push((0,C.join)(g,S))}}}let i=await vt(s,St,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await vt(i,St,async l=>{let c=await cn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(lr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>lr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Pe.warn({error:String(r)},"failed to list codex sessions"),[]}}async function un(t,e,n){let s=`list:${(0,ye.homedir)()}:${t??"all"}:${e??""}`,i=Ks.get(s);if(i)return i;let o=Vs.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await _c(e,n);else if(t==="codex")l=await bc(e,n);else{let[c,u]=await Promise.all([_c(e,n),bc(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return Ks.set(s,l),l})();return Vs.set(s,a),a.finally(()=>Vs.delete(s)),a}async function vc(t,e){let r=`search:${(0,ye.homedir)()}:${t}:${e??"all"}`,s=Xs.get(r);if(s)return s;let i=Ys.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,C.join)((0,ye.homedir)(),".claude","projects");try{let f=await(0,M.readdir)(d,{withFileTypes:!0}),p=[];for(let g of f){if(!g.isDirectory())continue;let m=(0,C.join)(d,g.name),S=await(0,M.readdir)(m).catch(()=>[]);for(let P of S)P.endsWith(".jsonl")&&p.push((0,C.join)(m,P))}let h=await vt(p,St,g=>wc(g,l,"claude"));for(let g of h)g&&a.add(g)}catch(f){Pe.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,C.join)((0,ye.homedir)(),".codex","sessions");try{let f=[];async function p(g){let m=await(0,M.readdir)(g,{withFileTypes:!0}).catch(()=>[]);for(let S of m){let P=(0,C.join)(g,S.name);S.isDirectory()?await p(P):S.name.endsWith(".jsonl")&&f.push(P)}}await p(d);let h=await vt(f,St,g=>wc(g,l,"codex"));for(let g of h)g&&a.add(g)}catch(f){Pe.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Xs.set(r,a),a})();return Ys.set(r,o),o.finally(()=>Ys.delete(r)),o}async function wc(t,e,n){let r=(0,Qs.createReadStream)(t,{encoding:"utf-8"}),s=(0,ei.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?$g:Gg,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||mt(n,t):null}function $g(t){return t?.type==="user"&&t.message?.role==="user"?ri(t):t?.type==="assistant"&&t.message?.role==="assistant"?ni(t.message.content):""}function Gg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return ti(t.payload.content)}let e=Ec(t);return e||""}async function Ic(t,e){let n=(0,Qs.createReadStream)(t,{encoding:"utf-8"}),r=(0,ei.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function dn(t,e,n){let r=[];if(e==="claude"){let s=(0,C.join)((0,ye.homedir)(),".claude","projects");try{let i=n?[Zs(n)]:[],o=await(0,M.readdir)(s).catch(()=>[]),a=n?[...i,...o.filter(l=>l!==Zs(n))]:o;for(let l of a){let c=(0,C.join)(s,l,`${t}.jsonl`);try{if(await Ic(c,u=>{if(u.type==="user"&&u.message?.role==="user"){let d=ri(u);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=ni(u.message.content);d&&r.push({role:"assistant",content:d})}}),r.length>0)break}catch(u){u.code!=="ENOENT"&&Pe.warn({error:String(u)},"failed to read claude session file")}}}catch(i){Pe.warn({error:String(i)},"failed to read claude session history")}}else if(e==="codex"){let s=(0,C.join)((0,ye.homedir)(),".codex","sessions");try{let i=await Pc(s,t);i&&await Ic(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=ti(o.payload.content);l&&(a==="user"&&Cc(l)||r.push({role:a,content:l}))})}catch(i){Pe.warn({error:String(i)},"failed to read codex session history")}}return r}async function Pc(t,e){try{let n=await(0,M.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,C.join)(t,r.name);if(r.isDirectory()){let i=await Pc(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Pe.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var _t=require("fs"),Mc=require("path");var zg=500,Rc=200;function Vg(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Rc?e:e.slice(-Rc)}function Yg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function Jg(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Lc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Vg(t.acceptedClientMessageIds),pendingApproval:Jg(t.pendingApproval)}}function Kg(t){if(Array.isArray(t))return{records:t.map(Lc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Lc):[],deletedSessionIds:Yg(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var ur=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},zg)}loadFromDisk(){try{let e=(0,_t.readFileSync)(zn,"utf-8");return Kg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,_t.mkdirSync)((0,Mc.dirname)(zn),{recursive:!0}),(0,_t.writeFileSync)(zn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var wt=require("path"),Nc=require("os");function bt(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,wt.join)((0,Nc.homedir)(),t.slice(2)):t}function Xg(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function Oc(t,e){let n=bt(Xg(t));if(!n||(0,wt.isAbsolute)(n))return n;let r=bt(e??"");return r?(0,wt.resolve)(r,n):n}var Bc={approvalRequestV1:"vibelet.approvalRequest.v1"};var It=require("fs"),Dc=require("path");function Zg(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function Qg(t){try{let e=(0,It.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Zg):[]}catch{return[]}}function fn(t,e){(0,It.mkdirSync)((0,Dc.dirname)(t),{recursive:!0}),(0,It.writeFileSync)(t,JSON.stringify(e,null,2)+`
97
+ `,"utf8")}var dr=class{constructor(e=Nl){this.pushSubscriptionsPath=e;this.records=Qg(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],fn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,fn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,fn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&fn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],fn(this.pushSubscriptionsPath,this.records)}};var V=R.child({module:"push"}),em="https://exp.host/--/api/v2/push/send",tm="https://exp.host/--/api/v2/push/getReceipts",nm=[0,1e3,3e3],pn=new dr;function rm(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function sm(t){return new Promise(e=>{setTimeout(e,t)})}function Hc(t){return t==="DeviceNotRegistered"}function im(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function om(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function am(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function lm(t,e,n,r){let s=new Map(t);for(let i of nm){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(tm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){V.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){V.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){V.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=am(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(V.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Hc(f)){let p=r.unregisterToken(u);V.info({token:u,errorCode:f,removed:p},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&V.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function cm(t){let e=t?.pushStore??pn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??sm;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...rm(a)&&a.eventType==="approval_request"?{categoryId:Bc.approvalRequestV1}:{}}));try{let u=await n(em,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){V.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){V.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=im(d,l),h=om(d,l);for(let{token:g,ticket:m}of p){let S=m.details?.error;if(V.error({token:g,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),Hc(S)){let P=e.unregisterToken(g);V.info({token:g,errorCode:S,removed:P},"push token removed after ticket rejection")}}f.length>0&&(V.debug({count:f.length},"push sent"),e.markSent(f)),h.size>0&&await lm(h,n,r,e)}catch(u){V.error({error:String(u)},"push send error")}}}function si(t,e){pn.register(t,e),V.info({deviceId:t,token:e,total:pn.count()},"push token registered")}function ii(t,e){let n=pn.unregister(t,e);V.info({deviceId:t,token:e,total:pn.count(),removed:n},"push token unregistered")}var fr=cm();var b=R.child({module:"manager"}),um="Done.",dm="Approval required",Fc=180,hr=200;function pr(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>hr&&e.splice(0,e.length-hr));return e}function de(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:pr(t.acceptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function Uc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&tr(e)}function qc(t,e,n){return{sessionId:t,agent:e,...n}}function fm(t){return t.startsWith(Os)}function jc(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var gr=class{constructor(e=fr){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new ur;idleSweepInterval=null;globalClients=new Set;startIdleSweep(){v.idleTimeoutMs<=0&&v.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=v.idleTimeoutMs,r=v.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(b.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),w.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;b.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),w.increment("driver.stall_timeout",{agent:o.agent}),_.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId);continue}o.pendingApproval||n<=0||a<n||(b.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),w.increment("driver.idle_timeout",{agent:o.agent}),_.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(b.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!Uc(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(i.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:i.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId);return}b.warn({sessionId:e.sessionId,requestId:i.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description,...i.approvalContext?{approvalContext:i.approvalContext}:{}},this.pushSender(dm,this.buildPushBody(`${e.title||e.sessionId}: ${i.description||i.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:i.requestId,eventType:"approval_request"})}n==="claude"&&i.type==="approval.request"&&tr(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:b.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{b.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),w.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=!!(e.pendingApproval&&(e.agent==="codex"||i===0&&Uc(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(de(e)),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),e.driver.sendPrompt(r),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=w.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof on))return;let s=r??(0,oi.randomUUID)().replace(/-/g,"");return n.configureHookBridge(v.port,s),s}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=sn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&fm(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),sn;if(r.approvalMode==="autoApprove")return jc(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return sn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${Os}${l.trim()||(0,oi.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(h=>{f=h});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:h=>{r.pendingClaudeHookApprovals.delete(c),f(h)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=pr(r?.acceptedClientMessageIds),p=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.pendingApproval??l,c=h.title||c,u=h.createdAt||u,d=h.lastActivityAt||d,f=pr(h.acceptedClientMessageIds,f),p="record";else if(!r){let m=(await un(n??i)).find(S=>S.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p="scanner")}if(!i&&n&&(i=n,p=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:p,managed:r?.managed??h?.managed,isResponding:r?.isResponding||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(qc(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(qc(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(de(e)),this.updateGauges(),this.touchSession(e.sessionId),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Fc?n:`${n.slice(0,Math.max(1,Fc-3)).trimEnd()}...`:um}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(de(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;w.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return un(e,n)}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){ar({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,s,i,o){s=bt(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Wc.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return b.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(a){b.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=this.createDriver(r),l=this.configureDriverBeforeStart(r,a);if(r==="codex"){let p=`pending_${Date.now()}`;b.info({sessionId:p,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:p,agent:r,cwd:s,approvalMode:i});let h={sessionId:p,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(p,h),this.registerClaudeHookSession(h),this.store.upsert(de(h)),this.updateGauges(),cr(),ir(),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:p}),this.startPendingCodexSession(h,e);return}let c=w.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();b.info({sessionId:u,agent:r,spawnMs:d},"session created"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(de(f)),this.updateGauges(),cr(),ir(),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){b.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await dn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(h))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=w.startTimer("driver.spawn"),p=this.createDriver(s),h=this.configureDriverBeforeStart(s,p),g=await p.start(c,r,u),m=f();b.info({sessionId:g,agent:s,spawnMs:m},"session resumed"),w.increment("session.resume",{agent:s}),_.emit("session.resume",{sessionId:g,agent:s,cwd:c});let S={sessionId:g,agent:s,cwd:c,approvalMode:u,driver:p,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:h,pendingClaudeHookApprovals:new Map};this.sessions.set(g,S),this.registerClaudeHookSession(S),this.store.upsert(de(S)),this.updateGauges(),this.bindDriverLifecycle(S,s," (resumed)",e),this.restoreDriverPendingApproval(p,S.pendingApproval);let P=await dn(r,s,c);if(P.length>0||S.pendingApproval){b.info({sessionId:r,historyCount:P.length},"sending history messages");let oe={type:"session.history",sessionId:g,messages:P,approvalMode:u,pendingApproval:S.pendingApproval};e.readyState===1&&e.send(JSON.stringify(oe))}this.reply(e,n,!0,{sessionId:g})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>hr&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-hr))}async sendMessage(e,n,r,s,i,o,a){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(r);if(!l||!l.driver){let d=await this.resolveReconnectSession(r,i,l);if(!d){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:d.agent,source:d.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:d.agent,source:d.source}),_.emit("session.reconnect",{sessionId:r,agent:d.agent,source:d.source});try{let f=this.createDriver(d.agent),p=this.configureDriverBeforeStart(d.agent,f,l?.claudeHookSecret);await f.start(d.cwd,r,d.approvalMode),this.restoreDriverPendingApproval(f,d.pendingApproval),l?(l.approvalMode=d.approvalMode,l.pendingApproval=d.pendingApproval,l.driver=f,l.active=!0,l.clients.add(e),l.lastActivityAt=d.lastActivityAt,l.lastActivityTs=Date.now(),l.isResponding=!1,l.currentReplyText="",l.acceptedClientMessageIds=pr(l.acceptedClientMessageIds,d.acceptedClientMessageIds),l.syntheticApprovalRetries=l.syntheticApprovalRetries??{},l.startupInProgress=!1,l.bufferedPrompts=l.bufferedPrompts??[],l.startupToken=l.startupToken??0,l.claudeHookSecret=p??l.claudeHookSecret,l.pendingClaudeHookApprovals=l.pendingClaudeHookApprovals??new Map):(l={sessionId:r,agent:d.agent,cwd:d.cwd,approvalMode:d.approvalMode,driver:f,clients:new Set([e]),title:d.title,createdAt:d.createdAt,lastActivityAt:d.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:d.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:d.managed,pendingApproval:d.pendingApproval,claudeHookSecret:p,pendingClaudeHookApprovals:new Map},this.sessions.set(r,l)),this.registerClaudeHookSession(l),this.bindDriverLifecycle(l,d.agent," (reconnected)"),this.store.upsert(de(l)),this.updateGauges()}catch(f){this.reply(e,n,!1,void 0,`Failed to reconnect: ${f}`);return}}if(l.clients.add(e),l.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(l,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:l.clients.size,hasDriver:!!l.driver,active:l.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:r,agent:l.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),ht(l.title)){let d=qs(s,50);d&&d!==l.title&&(l.title=d),this.store.upsert(de(l))}o&&this.rememberAcceptedClientMessage(l,o),this.touchSession(l.sessionId);let c=a?.length?a.map(d=>`[Attached image: ${d}]`).join(`
98
+ `):"",u=c?s?`${s}
99
+
100
+ ${c}`:c:s;if(l.startupInProgress){l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,l.bufferedPrompts.push(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(l.isResponding){l.bufferedPrompts.push(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,l.driver.sendPrompt(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await ar({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(f){b.warn({error:String(f)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let f=a??c.sessions.find(g=>g.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let h=await this.resolveReconnectSession(o,f,p);if(h){let g=await dn(o,h.agent,p?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:g,isResponding:p?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(p),approvalMode:p?.approvalMode??h.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{}}}}let d=this.collectReconnectPendingApprovals();w.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{},...d.length>0?{pendingApprovals:d}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),l.resolve(jc(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&tr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(de(e)),this.updateGauges(),this.touchSession(e.sessionId),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(a.approvalMode=s,this.store.upsert(a),b.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(de(i)),b.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}_.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:s.agent},"stopping session"),_.emit("session.stop",{sessionId:r,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(b.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),_.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),cr(),ir(),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r);if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(r)?.cwd??"",a=this.store.find(r),l=await dn(r,s,o);b.info({sessionId:r,historyCount:l.length,isResponding:i?.isResponding,approvalMode:i?.approvalMode},"sending history");let c={type:"session.history",sessionId:r,messages:l,isResponding:i?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(i),approvalMode:i?.approvalMode??a?.approvalMode,pendingApproval:i?.pendingApproval??a?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(c)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await ar({agent:r,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new on;case"codex":return new nr;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&w.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function ai(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var $c=require("child_process");function pm(t,e){return(0,$c.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function hm(t){let e=t.split(`
101
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Gc(t,e=pm){let n;try{n=hm(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var At=require("fs"),li=require("os"),Vc=require("crypto"),Yc=require("path");function Jc(t){return(0,Vc.randomBytes)(t).toString("base64url")}function gm(){return`d_${Jc(12)}`}function mm(){return(0,li.hostname)()}function ym(){let t=(0,li.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Sm(t){return{daemonId:gm(),daemonSecret:Jc(32),displayName:mm(),canonicalHost:ym(),port:t,createdAt:new Date().toISOString()}}function zc(t,e){(0,At.mkdirSync)((0,Yc.dirname)(e),{recursive:!0}),(0,At.writeFileSync)(e,JSON.stringify(t,null,2)+`
102
+ `,"utf8")}function Kc(t,e=Ll){try{let r=(0,At.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,zc(i,e)),i}}catch{}let n=Sm(t);return zc(n,e),n}var xt=require("crypto"),Tt=require("fs"),Zc=require("path");function ci(t){return(0,xt.randomBytes)(t).toString("base64url")}function ui(t){return(0,xt.createHash)("sha256").update(t).digest("hex")}function Xc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,xt.timingSafeEqual)(n,r)}function vm(t){try{let e=(0,Tt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function hn(t,e){(0,Tt.mkdirSync)((0,Zc.dirname)(t),{recursive:!0}),(0,Tt.writeFileSync)(t,JSON.stringify(e,null,2)+`
103
+ `,"utf8")}var mr=class{constructor(e=Ml){this.pairingsPath=e;this.records=vm(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${ci(8)}`,r=ci(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=ci(32),i={deviceId:e,deviceName:n,tokenHash:ui(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),hn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=ui(n);return Xc(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),hn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=ui(e),s=this.records.find(i=>!i.revokedAt&&Xc(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),hn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),hn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),hn(this.pairingsPath,this.records)}};function kt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function _m(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Qc(t,e){return _m(t)??e}function di(t,e){return!!(t&&e&&t===e)}function eu(t,e,n,r=!0){return t?di(t,e)?!0:!!n(t,r):!1}var nu=require("child_process");function fi(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function ru(t){if(!fi(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function bm(t){if(!fi(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function wm(t){if(!fi(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function pi(t){return!!t&&!bm(t)&&!wm(t)}function Et(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function su(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Im(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||pi(s.address)&&(ru(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function tu(t){let e=JSON.parse(t),n=Et(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>Et(o)).filter(o=>!!o).filter(o=>ru(o)&&pi(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function iu(t=nu.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return tu(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return tu(n)}catch{return{fallbackHosts:[]}}}function ou(t){let e=Et(t.canonicalHost),n=Et(t.configuredCanonicalHost)||Et(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Im(t.interfaces)].map(s=>Et(s)).filter(s=>!!s).filter(s=>pi(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function au(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var U=R.child({module:"daemon"}),gn=R.child({module:"ws"}),F=Kc(v.port),J=new gr((t,e,n)=>fr(t,e,{daemonId:F.daemonId,canonicalHost:F.canonicalHost,...n??{}})),Le=new mr,yr=new Set,Re=new WeakMap,lu=!1,pu=Date.now(),Ct=null;function Pt(){let t=iu();return ou({canonicalHost:F.canonicalHost,configuredCanonicalHost:v.canonicalHost,configuredFallbackHosts:su(v.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,du.networkInterfaces)()})}async function hi(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function N(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function Am(t){let e=(0,Ge.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function hu(){let t=Le.openWindow(),e=Pt(),n=e.canonicalHost,r=F.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(v.relayUrl)try{let i=new URL(v.relayUrl);n=i.hostname,r=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{U.warn({relayUrl:v.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:n,fallbackHosts:s,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function xm(t){let e=(0,Ge.resolve)(bt(t.trim())),n=await(0,ie.readdir)(e),r=[];for(let s of n){if(s.startsWith("."))continue;let i=await(0,ie.stat)((0,Ge.join)(e,s)).catch(()=>null);i&&r.push({name:s,isDirectory:i.isDirectory()})}return r.sort((s,i)=>s.isDirectory!==i.isDirectory?s.isDirectory?-1:1:s.name.localeCompare(i.name)),{entries:r}}var mn=(0,cu.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${v.port}`);if(n.pathname==="/health"){let s=Pt(),i={status:"ok",version:pt,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-pu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:Le.pairedCount(),wsClients:se.clients.size,drivers:J.getDriverCounts(),metrics:w.snapshot()};v.relayUrl&&(i.relayUrl=v.relayUrl),N(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!kt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,hu());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!kt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}Le.reset(),N(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!kt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,{status:"stopping"}),setTimeout(()=>ze("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!kt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await hi(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),N(e,200,{ok:!0})}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!kt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await hi(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);N(e,200,a)}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await hi(t);if(s.daemonId!==F.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){N(e,400,{error:"invalid_pair_request"});return}if(!Le.consumeWindow(s.pairNonce)){N(e,401,{error:"pair_window_expired"});return}let o=Le.issuePairToken(s.deviceId,s.deviceName),a=Pt();N(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=Qc(t.headers.authorization,n.searchParams.get("token"));if(!eu(r,v.legacyToken,(s,i)=>Le.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){N(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,ie.mkdir)(Rs,{recursive:!0});let u=`${Date.now()}_${(0,uu.randomBytes)(8).toString("hex")}${o}`,d=(0,Ge.join)(Rs,u);await(0,ie.writeFile)(d,Buffer.concat(l)),U.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){U.error({error:String(u)},"upload failed"),N(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=Oc(s,i);if(!(await(0,ie.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=Am(o),c=await(0,ie.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${pt}`)}),se=new Ur.default({server:mn});mn.on("connection",t=>{yr.add(t),t.on("close",()=>{yr.delete(t)})});se.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${v.port}`).searchParams.get("token");if(r&&di(r,v.legacyToken))Re.set(t,{authMode:"query_token"}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=Le.validateAnyPairToken(r);if(s)Re.set(t,{authMode:"query_token",deviceId:s.deviceId}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{w.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}gn.info({clients:se.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",se.clients.size),_.emit("ws.connect",{clients:se.clients.size,authMode:Re.get(t)?.authMode??"pending",deviceId:Re.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(au(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Re.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Le.validatePairToken(o.deviceId,o.pairToken)){Re.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),w.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){w.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}w.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)_.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?U.error:a.level==="warn"?U.warn:U.info).call(U,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await xm(o.path);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=Re.get(t);ai(i,{deviceId:a?.deviceId,registerToken:si,unregisterToken:ii,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Re.get(t);ai(i,{deviceId:a?.deviceId,registerToken:si,unregisterToken:ii,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){gn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{gn.info({clients:se.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",se.clients.size),_.emit("ws.disconnect",{clients:se.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{gn.error({error:s.message},"websocket error")})});function gi(){for(let t of yr)try{t.destroy()}catch{}yr.clear()}function gu(){let t=zl({auditPath:ut,stdoutLogPath:Vn,stderrLogPath:Yn,auditMaxBytes:v.auditMaxBytes,logMaxBytes:v.daemonLogMaxBytes});t.trimmedFiles>0&&U.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function Tm(){Ct||(Ct=setInterval(gu,v.storageHousekeepingIntervalMs),Ct.unref())}function km(){Ct&&(clearInterval(Ct),Ct=null)}function ze(t,e=0){if(!lu){lu=!0,U.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-pu)/1e3)}),w.stopPeriodicLog(),km(),J.shutdown();for(let n of se.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}se.close(n=>{n&&U.error({error:String(n)},"websocket close error")}),mn.close(n=>{if(n){U.error({error:String(n)},"http close error"),gi(),process.exit(1);return}gi(),process.exit(e)}),setTimeout(()=>{U.error("force exiting after shutdown timeout"),gi(),process.exit(e||1)},3e3).unref()}}se.on("error",t=>{gn.error({error:t.message},"wss error")});mn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Gc(v.port).filter(n=>n.pid!==process.pid);U.error({port:v.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else U.error({error:String(t)},"server error");ze(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ze("SIGINT"));process.once("SIGTERM",()=>ze("SIGTERM"));process.once("SIGHUP",()=>ze("SIGHUP"));process.once("SIGTTIN",()=>ze("SIGTTIN"));process.once("SIGTSTP",()=>ze("SIGTSTP"));process.on("uncaughtException",t=>{U.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{U.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});mn.listen(v.port,async()=>{gu(),_.emit("daemon.start",{port:v.port}),w.startPeriodicLog(),Tm(),U.info({port:v.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:Pt().canonicalHost,fallbackHosts:Pt().fallbackHosts,claudePath:v.claudePath,codexPath:v.codexPath,auditMaxBytes:v.auditMaxBytes,daemonLogMaxBytes:v.daemonLogMaxBytes,storageHousekeepingIntervalMs:v.storageHousekeepingIntervalMs,turnStallTimeoutMs:v.turnStallTimeoutMs},"daemon started");let t=Pt(),e=hu();Zt(`
101
104
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
102
- \u2551 Vibelet Daemon v${ft} \u2551
105
+ \u2551 Vibelet Daemon v${pt} \u2551
103
106
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
104
107
  \u2551 Port: ${String(v.port).padEnd(28)}\u2551
105
- \u2551 ID: ${H.daemonId.slice(0,28).padEnd(28)}\u2551
108
+ \u2551 ID: ${F.daemonId.slice(0,28).padEnd(28)}\u2551
106
109
  \u2551 Host: ${t.canonicalHost.slice(0,28).padEnd(28)}\u2551
107
110
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
108
111
 
@@ -112,7 +115,7 @@ Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
112
115
 
113
116
  Claude: ${v.claudePath}
114
117
  Codex: ${v.codexPath}
115
- `);try{let n=await cu.default.toString(JSON.stringify(e),{type:"terminal",small:!0});Kt(`
118
+ `);try{let n=await fu.default.toString(JSON.stringify(e),{type:"terminal",small:!0});Zt(`
116
119
  Scan this QR code with Vibelet app:
117
120
 
118
121
  ${n}