vibelet 1.0.0 → 1.0.2

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 Vu=Object.create;var Ni=Object.defineProperty;var $u=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Yu=Object.getPrototypeOf,Ju=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ku=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zu(e))!Ju.call(t,s)&&s!==n&&Ni(t,s,{get:()=>e[s],enumerable:!(r=$u(e,s))||r.enumerable});return t};var et=(t,e,n)=>(n=t!=null?Vu(Yu(t)):{},Ku(e||!t||!t.__esModule?Ni(n,"default",{value:t,enumerable:!0}):n,t));var pe=v((Py,Di)=>{"use strict";var Oi=["nodebuffer","arraybuffer","fragments"],Bi=typeof Blob<"u";Bi&&Oi.push("blob");Di.exports={BINARY_TYPES:Oi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Bi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ot=v((My,xn)=>{"use strict";var{EMPTY_BUFFER:Xu}=pe(),Nr=Buffer[Symbol.species];function Qu(t,e){if(t.length===0)return Xu;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 Nr(n.buffer,n.byteOffset,r):n}function Hi(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Fi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Zu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Or(t){if(Or.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Nr(t):ArrayBuffer.isView(t)?e=new Nr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Or.readOnly=!1),e}xn.exports={concat:Qu,mask:Hi,toArrayBuffer:Zu,toBuffer:Or,unmask:Fi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");xn.exports.mask=function(e,n,r,s,i){i<48?Hi(e,n,r,s,i):t.mask(e,n,r,s,i)},xn.exports.unmask=function(e,n){e.length<32?Fi(e,n):t.unmask(e,n)}}catch{}});var Wi=v((Ly,qi)=>{"use strict";var Ui=Symbol("kDone"),Br=Symbol("kRun"),Dr=class{constructor(e){this[Ui]=()=>{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[Ui])}}};qi.exports=Dr});var Dt=v((Ny,$i)=>{"use strict";var Bt=require("zlib"),ji=Ot(),ed=Wi(),{kStatusCode:Gi}=pe(),td=Buffer[Symbol.species],nd=Buffer.from([0,0,255,255]),kn=Symbol("permessage-deflate"),he=Symbol("total-length"),tt=Symbol("callback"),we=Symbol("buffers"),nt=Symbol("error"),Tn,Hr=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,!Tn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Tn=new ed(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[tt];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){Tn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Tn.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"?Bt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[kn]=this,this._inflate[he]=0,this._inflate[we]=[],this._inflate.on("error",sd),this._inflate.on("data",Vi)}this._inflate[tt]=r,this._inflate.write(e),n&&this._inflate.write(nd),this._inflate.flush(()=>{let i=this._inflate[nt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ji.concat(this._inflate[we],this._inflate[he]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[he]=0,this._inflate[we]=[],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"?Bt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[he]=0,this._deflate[we]=[],this._deflate.on("data",rd)}this._deflate[tt]=r,this._deflate.write(e),this._deflate.flush(Bt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ji.concat(this._deflate[we],this._deflate[he]);n&&(i=new td(i.buffer,i.byteOffset,i.length-4)),this._deflate[tt]=null,this._deflate[he]=0,this._deflate[we]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};$i.exports=Hr;function rd(t){this[we].push(t),this[he]+=t.length}function Vi(t){if(this[he]+=t.length,this[kn]._maxPayload<1||this[he]<=this[kn]._maxPayload){this[we].push(t);return}this[nt]=new RangeError("Max payload size exceeded"),this[nt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[nt][Gi]=1009,this.removeListener("data",Vi),this.reset()}function sd(t){if(this[kn]._inflate=null,this[nt]){this[tt](this[nt]);return}t[Gi]=1007,this[tt](t)}});var rt=v((Oy,Cn)=>{"use strict";var{isUtf8:zi}=require("buffer"),{hasBlob:id}=pe(),od=[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 ad(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Fr(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 ld(t){return id&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Cn.exports={isBlob:ld,isValidStatusCode:ad,isValidUTF8:Fr,tokenChars:od};if(zi)Cn.exports.isValidUTF8=function(t){return t.length<24?Fr(t):zi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Cn.exports.isValidUTF8=function(e){return e.length<32?Fr(e):t(e)}}catch{}});var Gr=v((By,eo)=>{"use strict";var{Writable:cd}=require("stream"),Yi=Dt(),{BINARY_TYPES:ud,EMPTY_BUFFER:Ji,kStatusCode:dd,kWebSocket:fd}=pe(),{concat:Ur,toArrayBuffer:pd,unmask:hd}=Ot(),{isValidStatusCode:gd,isValidUTF8:Ki}=rt(),En=Buffer[Symbol.species],X=0,Xi=1,Qi=2,Zi=3,qr=4,Wr=5,Rn=6,jr=class extends cd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ud[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[fd]=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 En(r.buffer,r.byteOffset+e,r.length-e),new En(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 En(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 Xi:this.getPayloadLength16(e);break;case Qi:this.getPayloadLength64(e);break;case Zi:this.getMask();break;case qr:this.getData(e);break;case Wr:case Rn: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[Yi.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=Xi:this._payloadLength===127?this._state=Qi: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=Zi:this._state=qr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=qr}getData(e){let n=Ji;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&&hd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Wr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Yi.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=Ur(r,n):this._binaryType==="arraybuffer"?s=pd(Ur(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=Rn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Ur(r,n);if(!this._skipUTF8Validation&&!Ki(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Wr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=Rn,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,Ji),this.end();else{let r=e.readUInt16BE(0);if(!gd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new En(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ki(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=Rn,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[dd]=s,o}};eo.exports=jr});var zr=v((Hy,ro)=>{"use strict";var{Duplex:Dy}=require("stream"),{randomFillSync:md}=require("crypto"),to=Dt(),{EMPTY_BUFFER:yd,kWebSocket:vd,NOOP:Sd}=pe(),{isBlob:st,isValidStatusCode:_d}=rt(),{mask:no,toBuffer:De}=Ot(),Q=Symbol("kByteLength"),bd=Buffer.alloc(4),Pn=8*1024,He,it=Pn,re=0,wd=1,Id=2,Vr=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=re,this.onerror=Sd,this[vd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||bd,n.generateMask?n.generateMask(r):(it===Pn&&(He===void 0&&(He=Buffer.alloc(Pn)),md(He,0,Pn),it=0),r[0]=He[it++],r[1]=He[it++],r[2]=He[it++],r[3]=He[it++]),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?(no(e,r,c,i,a),[c]):(no(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=yd;else{if(typeof e!="number"||!_d(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!==re?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):st(e)?(s=e.size,i=!1):(e=De(e),s=e.length,i=De.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};st(e)?this._state!==re?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==re?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):st(e)?(s=e.size,i=!1):(e=De(e),s=e.length,i=De.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};st(e)?this._state!==re?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==re?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[to.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):st(e)?(a=e.size,l=!1):(e=De(e),a=e.length,l=De.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};st(e)?this._state!==re?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==re?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=Id,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick($r,this,a,s);return}this._bufferedBytes-=r[Q];let o=De(i);n?this.dispatch(o,n,r,s):(this._state=re,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ad,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[to.extensionName];this._bufferedBytes+=r[Q],this._state=wd,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");$r(this,l,s);return}this._bufferedBytes-=r[Q],this._state=re,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===re&&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)}};ro.exports=Vr;function $r(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 Ad(t,e,n){$r(t,e,n),t.onerror(e)}});var po=v((Fy,fo)=>{"use strict";var{kForOnEventAttribute:Ht,kListener:Yr}=pe(),so=Symbol("kCode"),io=Symbol("kData"),oo=Symbol("kError"),ao=Symbol("kMessage"),lo=Symbol("kReason"),ot=Symbol("kTarget"),co=Symbol("kType"),uo=Symbol("kWasClean"),ge=class{constructor(e){this[ot]=null,this[co]=e}get target(){return this[ot]}get type(){return this[co]}};Object.defineProperty(ge.prototype,"target",{enumerable:!0});Object.defineProperty(ge.prototype,"type",{enumerable:!0});var Fe=class extends ge{constructor(e,n={}){super(e),this[so]=n.code===void 0?0:n.code,this[lo]=n.reason===void 0?"":n.reason,this[uo]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[so]}get reason(){return this[lo]}get wasClean(){return this[uo]}};Object.defineProperty(Fe.prototype,"code",{enumerable:!0});Object.defineProperty(Fe.prototype,"reason",{enumerable:!0});Object.defineProperty(Fe.prototype,"wasClean",{enumerable:!0});var at=class extends ge{constructor(e,n={}){super(e),this[oo]=n.error===void 0?null:n.error,this[ao]=n.message===void 0?"":n.message}get error(){return this[oo]}get message(){return this[ao]}};Object.defineProperty(at.prototype,"error",{enumerable:!0});Object.defineProperty(at.prototype,"message",{enumerable:!0});var Ft=class extends ge{constructor(e,n={}){super(e),this[io]=n.data===void 0?null:n.data}get data(){return this[io]}};Object.defineProperty(Ft.prototype,"data",{enumerable:!0});var xd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ht]&&s[Yr]===e&&!s[Ht])return;let r;if(t==="message")r=function(i,o){let a=new Ft("message",{data:o?i:i.toString()});a[ot]=this,Mn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Fe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ot]=this,Mn(e,this,a)};else if(t==="error")r=function(i){let o=new at("error",{error:i,message:i.message});o[ot]=this,Mn(e,this,o)};else if(t==="open")r=function(){let i=new ge("open");i[ot]=this,Mn(e,this,i)};else return;r[Ht]=!!n[Ht],r[Yr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Yr]===e&&!n[Ht]){this.removeListener(t,n);break}}};fo.exports={CloseEvent:Fe,ErrorEvent:at,Event:ge,EventTarget:xd,MessageEvent:Ft};function Mn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jr=v((Uy,ho)=>{"use strict";var{tokenChars:Ut}=rt();function ce(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Td(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&&Ut[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?(ce(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&&Ut[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),ce(n,t.slice(l,u),!0),c===44&&(ce(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(Ut[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Ut[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&&Ut[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),ce(n,a,p),c===44&&(ce(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?ce(e,f,n):(a===void 0?ce(n,f,!0):r?ce(n,a,f.replace(/\\/g,"")):ce(n,a,f),ce(e,o,n)),e}function kd(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(", ")}ho.exports={format:kd,parse:Td}});var Bn=v((jy,To)=>{"use strict";var Cd=require("events"),Ed=require("https"),Rd=require("http"),yo=require("net"),Pd=require("tls"),{randomBytes:Md,createHash:Ld}=require("crypto"),{Duplex:qy,Readable:Wy}=require("stream"),{URL:Kr}=require("url"),Ie=Dt(),Nd=Gr(),Od=zr(),{isBlob:Bd}=rt(),{BINARY_TYPES:go,CLOSE_TIMEOUT:Dd,EMPTY_BUFFER:Ln,GUID:Hd,kForOnEventAttribute:Xr,kListener:Fd,kStatusCode:Ud,kWebSocket:H,NOOP:vo}=pe(),{EventTarget:{addEventListener:qd,removeEventListener:Wd}}=po(),{format:jd,parse:Gd}=Jr(),{toBuffer:Vd}=Ot(),So=Symbol("kAborted"),Qr=[8,13],me=["CONNECTING","OPEN","CLOSING","CLOSED"],$d=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends Cd{constructor(e,n,r){super(),this._binaryType=go[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ln,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]),_o(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){go.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 Nd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Od(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[H]=this,i[H]=this,e[H]=this,s.on("conclude",Jd),s.on("drain",Kd),s.on("error",Xd),s.on("message",Qd),s.on("ping",Zd),s.on("pong",ef),i.onerror=tf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Io),e.on("data",On),e.on("end",Ao),e.on("error",xo),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[Ie.extensionName]&&this._extensions[Ie.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())}),wo(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){Zr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ln,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){Zr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ln,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){Zr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ie.extensionName]||(s.compress=!1),this._sender.send(e||Ln,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:me.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:me.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:me.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:me.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[Xr])return e[Fd];return null},set(e){for(let n of this.listeners(t))if(n[Xr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Xr]:!0})}})});T.prototype.addEventListener=qd;T.prototype.removeEventListener=Wd;To.exports=T;function _o(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Dd,protocolVersion:Qr[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,!Qr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Qr.join(", ")})`);let i;if(e instanceof Kr)i=e;else try{i=new Kr(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 h=new SyntaxError(l);if(t._redirects===0)throw h;Nn(t,h);return}let c=o?443:80,u=Md(16).toString("base64"),d=o?Ed.request:Rd.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Yd:zd),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 Ie(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=jd({[Ie.extensionName]:p.offer()})),n.length){for(let h of n){if(typeof h!="string"||!$d.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}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 h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[y,m]of Object.entries(h))r.headers[y.toLowerCase()]=m}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[So]||(g=t._req=null,Nn(t,h))}),g.on("response",h=>{let y=h.headers.location,m=h.statusCode;if(y&&s.followRedirects&&m>=300&&m<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new Kr(y,e)}catch{let R=new SyntaxError(`Invalid URL: ${y}`);Nn(t,R);return}_o(t,C,n,r)}else t.emit("unexpected-response",g,h)||Y(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,y,m)=>{if(t.emit("upgrade",h),t.readyState!==T.CONNECTING)return;g=t._req=null;let C=h.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Y(t,y,"Invalid Upgrade header");return}let ae=Ld("sha1").update(u+Hd).digest("base64");if(h.headers["sec-websocket-accept"]!==ae){Y(t,y,"Invalid Sec-WebSocket-Accept header");return}let R=h.headers["sec-websocket-protocol"],D;if(R!==void 0?f.size?f.has(R)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":f.size&&(D="Server sent no subprotocol"),D){Y(t,y,D);return}R&&(t._protocol=R);let K=h.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){Y(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let le;try{le=Gd(K)}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ze=Object.keys(le);if(Ze.length!==1||Ze[0]!==Ie.extensionName){Y(t,y,"Server indicated an extension that was not requested");return}try{p.accept(le[Ie.extensionName])}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ie.extensionName]=p}t.setSocket(y,m,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Nn(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function zd(t){return t.path=t.socketPath,yo.connect(t)}function Yd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=yo.isIP(t.host)?"":t.host),Pd.connect(t)}function Y(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[So]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Nn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Zr(t,e,n){if(e){let r=Bd(e)?e.size:Vd(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${me[t.readyState]})`);process.nextTick(n,r)}}function Jd(t,e){let n=this[H];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[H]!==void 0&&(n._socket.removeListener("data",On),process.nextTick(bo,n._socket),t===1005?n.close():n.close(t,e))}function Kd(){let t=this[H];t.isPaused||t._socket.resume()}function Xd(t){let e=this[H];e._socket[H]!==void 0&&(e._socket.removeListener("data",On),process.nextTick(bo,e._socket),e.close(t[Ud])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function mo(){this[H].emitClose()}function Qd(t,e){this[H].emit("message",t,e)}function Zd(t){let e=this[H];e._autoPong&&e.pong(t,!this._isServer,vo),e.emit("ping",t)}function ef(t){this[H].emit("pong",t)}function bo(t){t.resume()}function tf(t){let e=this[H];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,wo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function wo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Io(){let t=this[H];if(this.removeListener("close",Io),this.removeListener("data",On),this.removeListener("end",Ao),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[H]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",mo),t._receiver.on("finish",mo))}function On(t){this[H]._receiver.write(t)||this.pause()}function Ao(){let t=this[H];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function xo(){let t=this[H];this.removeListener("error",xo),this.on("error",vo),t&&(t._readyState=T.CLOSING,this.destroy())}});var Ro=v((Vy,Eo)=>{"use strict";var Gy=Bn(),{Duplex:nf}=require("stream");function ko(t){t.emit("close")}function rf(){!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 sf(t,e){let n=!0,r=new nf({...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(ko,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(ko,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",rf),r.on("error",Co),r}Eo.exports=sf});var Mo=v(($y,Po)=>{"use strict";var{tokenChars:of}=rt();function af(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&&of[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:af}});var Fo=v((Yy,Ho)=>{"use strict";var lf=require("events"),Dn=require("http"),{Duplex:zy}=require("stream"),{createHash:cf}=require("crypto"),Lo=Jr(),Ue=Dt(),uf=Mo(),df=Bn(),{CLOSE_TIMEOUT:ff,GUID:pf,kWebSocket:hf}=pe(),gf=/^[+/0-9A-Za-z]{22}==$/,No=0,Oo=1,Do=2,es=class extends lf{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ff,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:df,...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=Dn.createServer((r,s)=>{let i=Dn.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=mf(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=No}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===Do){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(qt,this);return}if(e&&this.once("close",e),this._state!==Oo)if(this._state=Oo,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(qt,this):process.nextTick(qt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{qt(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",Bo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qe(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qe(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!gf.test(i)){qe(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qe(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Wt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=uf.parse(l)}catch{qe(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 Ue(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Lo.parse(u);p[Ue.extensionName]&&(f.accept(p[Ue.extensionName]),d[Ue.extensionName]=f)}catch{qe(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,g,h,y)=>{if(!p)return Wt(n,g||401,h,y);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Wt(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[hf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>No)return Wt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${cf("sha1").update(n+pf).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[Ue.extensionName]){let d=e[Ue.extensionName].params,f=Lo.format({[Ue.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 Hi=Object.defineProperty;var Ju=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Qu=Object.getPrototypeOf,Xu=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Zu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ku(e))!Xu.call(t,s)&&s!==n&&Hi(t,s,{get:()=>e[s],enumerable:!(r=Ju(e,s))||r.enumerable});return t};var tt=(t,e,n)=>(n=t!=null?Yu(Qu(t)):{},Zu(e||!t||!t.__esModule?Hi(n,"default",{value:t,enumerable:!0}):n,t));var ge=v((jy,qi)=>{"use strict";var Fi=["nodebuffer","arraybuffer","fragments"],Ui=typeof Blob<"u";Ui&&Fi.push("blob");qi.exports={BINARY_TYPES:Fi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ui,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ot=v((Gy,Tn)=>{"use strict";var{EMPTY_BUFFER:ed}=ge(),Br=Buffer[Symbol.species];function td(t,e){if(t.length===0)return ed;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 Br(n.buffer,n.byteOffset,r):n}function Wi(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function ji(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Dr(t){if(Dr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Br(t):ArrayBuffer.isView(t)?e=new Br(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Dr.readOnly=!1),e}Tn.exports={concat:td,mask:Wi,toArrayBuffer:nd,toBuffer:Dr,unmask:ji};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Tn.exports.mask=function(e,n,r,s,i){i<48?Wi(e,n,r,s,i):t.mask(e,n,r,s,i)},Tn.exports.unmask=function(e,n){e.length<32?ji(e,n):t.unmask(e,n)}}catch{}});var $i=v((Vy,Vi)=>{"use strict";var Gi=Symbol("kDone"),Hr=Symbol("kRun"),Fr=class{constructor(e){this[Gi]=()=>{this.pending--,this[Hr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hr]()}[Hr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Gi])}}};Vi.exports=Fr});var Dt=v(($y,Ki)=>{"use strict";var Bt=require("zlib"),zi=Ot(),rd=$i(),{kStatusCode:Yi}=ge(),sd=Buffer[Symbol.species],id=Buffer.from([0,0,255,255]),kn=Symbol("permessage-deflate"),me=Symbol("total-length"),nt=Symbol("callback"),we=Symbol("buffers"),rt=Symbol("error"),xn,Ur=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,!xn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;xn=new rd(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[nt];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){xn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){xn.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"?Bt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[kn]=this,this._inflate[me]=0,this._inflate[we]=[],this._inflate.on("error",ad),this._inflate.on("data",Ji)}this._inflate[nt]=r,this._inflate.write(e),n&&this._inflate.write(id),this._inflate.flush(()=>{let i=this._inflate[rt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=zi.concat(this._inflate[we],this._inflate[me]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[me]=0,this._inflate[we]=[],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"?Bt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[me]=0,this._deflate[we]=[],this._deflate.on("data",od)}this._deflate[nt]=r,this._deflate.write(e),this._deflate.flush(Bt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=zi.concat(this._deflate[we],this._deflate[me]);n&&(i=new sd(i.buffer,i.byteOffset,i.length-4)),this._deflate[nt]=null,this._deflate[me]=0,this._deflate[we]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ki.exports=Ur;function od(t){this[we].push(t),this[me]+=t.length}function Ji(t){if(this[me]+=t.length,this[kn]._maxPayload<1||this[me]<=this[kn]._maxPayload){this[we].push(t);return}this[rt]=new RangeError("Max payload size exceeded"),this[rt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rt][Yi]=1009,this.removeListener("data",Ji),this.reset()}function ad(t){if(this[kn]._inflate=null,this[rt]){this[nt](this[rt]);return}t[Yi]=1007,this[nt](t)}});var st=v((zy,Cn)=>{"use strict";var{isUtf8:Qi}=require("buffer"),{hasBlob:ld}=ge(),cd=[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 ud(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function qr(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 dd(t){return ld&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Cn.exports={isBlob:dd,isValidStatusCode:ud,isValidUTF8:qr,tokenChars:cd};if(Qi)Cn.exports.isValidUTF8=function(t){return t.length<24?qr(t):Qi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Cn.exports.isValidUTF8=function(e){return e.length<32?qr(e):t(e)}}catch{}});var $r=v((Yy,so)=>{"use strict";var{Writable:fd}=require("stream"),Xi=Dt(),{BINARY_TYPES:pd,EMPTY_BUFFER:Zi,kStatusCode:hd,kWebSocket:gd}=ge(),{concat:Wr,toArrayBuffer:md,unmask:yd}=Ot(),{isValidStatusCode:vd,isValidUTF8:eo}=st(),En=Buffer[Symbol.species],Q=0,to=1,no=2,ro=3,jr=4,Gr=5,Rn=6,Vr=class extends fd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[gd]=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=Q}_write(e,n,r){if(this._opcode===8&&this._state==Q)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 En(r.buffer,r.byteOffset+e,r.length-e),new En(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 En(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 Q:this.getInfo(e);break;case to:this.getPayloadLength16(e);break;case no:this.getPayloadLength64(e);break;case ro:this.getMask();break;case jr:this.getData(e);break;case Gr:case Rn: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[Xi.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=to:this._payloadLength===127?this._state=no: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=ro:this._state=jr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jr}getData(e){let n=Zi;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&&yd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Gr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Xi.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===Q&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Q;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=Wr(r,n):this._binaryType==="arraybuffer"?s=md(Wr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Q):(this._state=Rn,setImmediate(()=>{this.emit("message",s,!0),this._state=Q,this.startLoop(e)}))}else{let s=Wr(r,n);if(!this._skipUTF8Validation&&!eo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Gr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Q):(this._state=Rn,setImmediate(()=>{this.emit("message",s,!1),this._state=Q,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Zi),this.end();else{let r=e.readUInt16BE(0);if(!vd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new En(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!eo(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=Q;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Q):(this._state=Rn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Q,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[hd]=s,o}};so.exports=Vr});var Jr=v((Ky,ao)=>{"use strict";var{Duplex:Jy}=require("stream"),{randomFillSync:Sd}=require("crypto"),io=Dt(),{EMPTY_BUFFER:_d,kWebSocket:bd,NOOP:wd}=ge(),{isBlob:it,isValidStatusCode:Id}=st(),{mask:oo,toBuffer:De}=Ot(),X=Symbol("kByteLength"),Ad=Buffer.alloc(4),Pn=8*1024,He,ot=Pn,re=0,Td=1,xd=2,zr=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=re,this.onerror=wd,this[bd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Ad,n.generateMask?n.generateMask(r):(ot===Pn&&(He===void 0&&(He=Buffer.alloc(Pn)),Sd(He,0,Pn),ot=0),r[0]=He[ot++],r[1]=He[ot++],r[2]=He[ot++],r[3]=He[ot++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[X]!==void 0?a=n[X]:(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?(oo(e,r,c,i,a),[c]):(oo(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=_d;else{if(typeof e!="number"||!Id(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={[X]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==re?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):it(e)?(s=e.size,i=!1):(e=De(e),s=e.length,i=De.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[X]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};it(e)?this._state!==re?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==re?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):it(e)?(s=e.size,i=!1):(e=De(e),s=e.length,i=De.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[X]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};it(e)?this._state!==re?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==re?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[io.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):it(e)?(a=e.size,l=!1):(e=De(e),a=e.length,l=De.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={[X]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};it(e)?this._state!==re?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==re?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[X],this._state=xd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Yr,this,a,s);return}this._bufferedBytes-=r[X];let o=De(i);n?this.dispatch(o,n,r,s):(this._state=re,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(kd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[io.extensionName];this._bufferedBytes+=r[X],this._state=Td,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Yr(this,l,s);return}this._bufferedBytes-=r[X],this._state=re,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===re&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][X],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][X],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)}};ao.exports=zr;function Yr(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 kd(t,e,n){Yr(t,e,n),t.onerror(e)}});var yo=v((Qy,mo)=>{"use strict";var{kForOnEventAttribute:Ht,kListener:Kr}=ge(),lo=Symbol("kCode"),co=Symbol("kData"),uo=Symbol("kError"),fo=Symbol("kMessage"),po=Symbol("kReason"),at=Symbol("kTarget"),ho=Symbol("kType"),go=Symbol("kWasClean"),ye=class{constructor(e){this[at]=null,this[ho]=e}get target(){return this[at]}get type(){return this[ho]}};Object.defineProperty(ye.prototype,"target",{enumerable:!0});Object.defineProperty(ye.prototype,"type",{enumerable:!0});var Fe=class extends ye{constructor(e,n={}){super(e),this[lo]=n.code===void 0?0:n.code,this[po]=n.reason===void 0?"":n.reason,this[go]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[lo]}get reason(){return this[po]}get wasClean(){return this[go]}};Object.defineProperty(Fe.prototype,"code",{enumerable:!0});Object.defineProperty(Fe.prototype,"reason",{enumerable:!0});Object.defineProperty(Fe.prototype,"wasClean",{enumerable:!0});var lt=class extends ye{constructor(e,n={}){super(e),this[uo]=n.error===void 0?null:n.error,this[fo]=n.message===void 0?"":n.message}get error(){return this[uo]}get message(){return this[fo]}};Object.defineProperty(lt.prototype,"error",{enumerable:!0});Object.defineProperty(lt.prototype,"message",{enumerable:!0});var Ft=class extends ye{constructor(e,n={}){super(e),this[co]=n.data===void 0?null:n.data}get data(){return this[co]}};Object.defineProperty(Ft.prototype,"data",{enumerable:!0});var Cd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ht]&&s[Kr]===e&&!s[Ht])return;let r;if(t==="message")r=function(i,o){let a=new Ft("message",{data:o?i:i.toString()});a[at]=this,Mn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Fe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[at]=this,Mn(e,this,a)};else if(t==="error")r=function(i){let o=new lt("error",{error:i,message:i.message});o[at]=this,Mn(e,this,o)};else if(t==="open")r=function(){let i=new ye("open");i[at]=this,Mn(e,this,i)};else return;r[Ht]=!!n[Ht],r[Kr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Kr]===e&&!n[Ht]){this.removeListener(t,n);break}}};mo.exports={CloseEvent:Fe,ErrorEvent:lt,Event:ye,EventTarget:Cd,MessageEvent:Ft};function Mn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Qr=v((Xy,vo)=>{"use strict";var{tokenChars:Ut}=st();function de(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Ed(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&&Ut[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?(de(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&&Ut[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),de(n,t.slice(l,u),!0),c===44&&(de(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(Ut[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Ut[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&&Ut[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),de(n,a,p),c===44&&(de(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?de(e,f,n):(a===void 0?de(n,f,!0):r?de(n,a,f.replace(/\\/g,"")):de(n,a,f),de(e,o,n)),e}function Rd(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(", ")}vo.exports={format:Rd,parse:Ed}});var Bn=v((tv,Ro)=>{"use strict";var Pd=require("events"),Md=require("https"),Ld=require("http"),bo=require("net"),Nd=require("tls"),{randomBytes:Od,createHash:Bd}=require("crypto"),{Duplex:Zy,Readable:ev}=require("stream"),{URL:Xr}=require("url"),Ie=Dt(),Dd=$r(),Hd=Jr(),{isBlob:Fd}=st(),{BINARY_TYPES:So,CLOSE_TIMEOUT:Ud,EMPTY_BUFFER:Ln,GUID:qd,kForOnEventAttribute:Zr,kListener:Wd,kStatusCode:jd,kWebSocket:F,NOOP:wo}=ge(),{EventTarget:{addEventListener:Gd,removeEventListener:Vd}}=yo(),{format:$d,parse:zd}=Qr(),{toBuffer:Yd}=Ot(),Io=Symbol("kAborted"),es=[8,13],ve=["CONNECTING","OPEN","CLOSING","CLOSED"],Jd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class t extends Pd{constructor(e,n,r){super(),this._binaryType=So[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ln,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]),Ao(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){So.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 Dd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[F]=this,i[F]=this,e[F]=this,s.on("conclude",Xd),s.on("drain",Zd),s.on("error",ef),s.on("message",tf),s.on("ping",nf),s.on("pong",rf),i.onerror=sf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ko),e.on("data",On),e.on("end",Co),e.on("error",Eo),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[Ie.extensionName]&&this._extensions[Ie.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())}),xo(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){ts(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ln,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){ts(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ln,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){ts(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ie.extensionName]||(s.compress=!1),this._sender.send(e||Ln,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(x,"CONNECTING",{enumerable:!0,value:ve.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:ve.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:ve.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:ve.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:ve.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:ve.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:ve.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:ve.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(x.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(x.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Zr])return e[Wd];return null},set(e){for(let n of this.listeners(t))if(n[Zr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Zr]:!0})}})});x.prototype.addEventListener=Gd;x.prototype.removeEventListener=Vd;Ro.exports=x;function Ao(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ud,protocolVersion:es[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,!es.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${es.join(", ")})`);let i;if(e instanceof Xr)i=e;else try{i=new Xr(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 h=new SyntaxError(l);if(t._redirects===0)throw h;Nn(t,h);return}let c=o?443:80,u=Od(16).toString("base64"),d=o?Md.request:Ld.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Qd:Kd),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 Ie(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=$d({[Ie.extensionName]:p.offer()})),n.length){for(let h of n){if(typeof h!="string"||!Jd.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}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 h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[y,m]of Object.entries(h))r.headers[y.toLowerCase()]=m}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[Io]||(g=t._req=null,Nn(t,h))}),g.on("response",h=>{let y=h.headers.location,m=h.statusCode;if(y&&s.followRedirects&&m>=300&&m<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new Xr(y,e)}catch{let R=new SyntaxError(`Invalid URL: ${y}`);Nn(t,R);return}Ao(t,C,n,r)}else t.emit("unexpected-response",g,h)||Y(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,y,m)=>{if(t.emit("upgrade",h),t.readyState!==x.CONNECTING)return;g=t._req=null;let C=h.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Y(t,y,"Invalid Upgrade header");return}let ce=Bd("sha1").update(u+qd).digest("base64");if(h.headers["sec-websocket-accept"]!==ce){Y(t,y,"Invalid Sec-WebSocket-Accept header");return}let R=h.headers["sec-websocket-protocol"],H;if(R!==void 0?f.size?f.has(R)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":f.size&&(H="Server sent no subprotocol"),H){Y(t,y,H);return}R&&(t._protocol=R);let K=h.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){Y(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ue;try{ue=zd(K)}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}let et=Object.keys(ue);if(et.length!==1||et[0]!==Ie.extensionName){Y(t,y,"Server indicated an extension that was not requested");return}try{p.accept(ue[Ie.extensionName])}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ie.extensionName]=p}t.setSocket(y,m,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Nn(t,e){t._readyState=x.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Kd(t){return t.path=t.socketPath,bo.connect(t)}function Qd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=bo.isIP(t.host)?"":t.host),Nd.connect(t)}function Y(t,e,n){t._readyState=x.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[Io]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Nn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ts(t,e,n){if(e){let r=Fd(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} (${ve[t.readyState]})`);process.nextTick(n,r)}}function Xd(t,e){let n=this[F];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[F]!==void 0&&(n._socket.removeListener("data",On),process.nextTick(To,n._socket),t===1005?n.close():n.close(t,e))}function Zd(){let t=this[F];t.isPaused||t._socket.resume()}function ef(t){let e=this[F];e._socket[F]!==void 0&&(e._socket.removeListener("data",On),process.nextTick(To,e._socket),e.close(t[jd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function _o(){this[F].emitClose()}function tf(t,e){this[F].emit("message",t,e)}function nf(t){let e=this[F];e._autoPong&&e.pong(t,!this._isServer,wo),e.emit("ping",t)}function rf(t){this[F].emit("pong",t)}function To(t){t.resume()}function sf(t){let e=this[F];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,xo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ko(){let t=this[F];if(this.removeListener("close",ko),this.removeListener("data",On),this.removeListener("end",Co),t._readyState=x.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[F]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",_o),t._receiver.on("finish",_o))}function On(t){this[F]._receiver.write(t)||this.pause()}function Co(){let t=this[F];t._readyState=x.CLOSING,t._receiver.end(),this.end()}function Eo(){let t=this[F];this.removeListener("error",Eo),this.on("error",wo),t&&(t._readyState=x.CLOSING,this.destroy())}});var No=v((rv,Lo)=>{"use strict";var nv=Bn(),{Duplex:of}=require("stream");function Po(t){t.emit("close")}function af(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Mo(t){this.removeListener("error",Mo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function lf(t,e){let n=!0,r=new of({...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(Po,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Po,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",af),r.on("error",Mo),r}Lo.exports=lf});var Bo=v((sv,Oo)=>{"use strict";var{tokenChars:cf}=st();function uf(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&&cf[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}Oo.exports={parse:uf}});var jo=v((ov,Wo)=>{"use strict";var df=require("events"),Dn=require("http"),{Duplex:iv}=require("stream"),{createHash:ff}=require("crypto"),Do=Qr(),Ue=Dt(),pf=Bo(),hf=Bn(),{CLOSE_TIMEOUT:gf,GUID:mf,kWebSocket:yf}=ge(),vf=/^[+/0-9A-Za-z]{22}==$/,Ho=0,Fo=1,qo=2,ns=class extends df{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:gf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hf,...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=Dn.createServer((r,s)=>{let i=Dn.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=Sf(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=Ho}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===qo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(qt,this);return}if(e&&this.once("close",e),this._state!==Fo)if(this._state=Fo,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(qt,this):process.nextTick(qt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{qt(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",Uo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qe(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qe(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!vf.test(i)){qe(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qe(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Wt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=pf.parse(l)}catch{qe(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 Ue(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Do.parse(u);p[Ue.extensionName]&&(f.accept(p[Ue.extensionName]),d[Ue.extensionName]=f)}catch{qe(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,g,h,y)=>{if(!p)return Wt(n,g||401,h,y);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Wt(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[yf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ho)return Wt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ff("sha1").update(n+mf).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[Ue.extensionName]){let d=e[Ue.extensionName].params,f=Do.format({[Ue.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",Bo),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(qt,this)})),a(u,s)}};Ho.exports=es;function mf(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 qt(t){t._state=Do,t.emit("close")}function Bo(){this.destroy()}function Wt(t,e,n,r){n=n||Dn.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} ${Dn.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",Uo),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(qt,this)})),a(u,s)}};Wo.exports=ns;function Sf(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 qt(t){t._state=qo,t.emit("close")}function Uo(){this.destroy()}function Wt(t,e,n,r){n=n||Dn.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} ${Dn.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 qe(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qe),t.emit("wsClientError",o,n,e)}else Wt(n,r,s,i)}});var ns=v((Ky,Uo)=>{Uo.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Ae=v(We=>{var rs,bf=[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];We.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};We.getSymbolTotalCodewords=function(e){return bf[e]};We.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};We.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');rs=e};We.isKanjiModeEnabled=function(){return typeof rs<"u"};We.toSJIS=function(e){return rs(e)}});var Hn=v(Z=>{Z.L={bit:1};Z.M={bit:0};Z.Q={bit:3};Z.H={bit:2};function wf(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 wf(e)}catch{return n}}});var jo=v((Zy,Wo)=>{function qo(){this.buffer=[],this.length=0}qo.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++}};Wo.exports=qo});var Vo=v((ev,Go)=>{function jt(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)}jt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};jt.prototype.get=function(t,e){return this.data[t*this.size+e]};jt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};jt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Go.exports=jt});var $o=v(Fn=>{var If=Ae().getSymbolSize;Fn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=If(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()};Fn.getPositions=function(e){let n=[],r=Fn.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 Jo=v(Yo=>{var Af=Ae().getSymbolSize,zo=7;Yo.getPositions=function(e){let n=Af(e);return[[0,0],[n-zo,0],[0,n-zo]]}});var Ko=v(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var je={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+=je.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=je.N1+(i-5)),a=u,i=1)}s>=5&&(r+=je.N1+(s-5)),i>=5&&(r+=je.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*je.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*je.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)*je.N4};function xf(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,xf(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 is=v(ss=>{var xe=Hn(),Un=[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],qn=[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];ss.getBlocksCount=function(e,n){switch(n){case xe.L:return Un[(e-1)*4+0];case xe.M:return Un[(e-1)*4+1];case xe.Q:return Un[(e-1)*4+2];case xe.H:return Un[(e-1)*4+3];default:return}};ss.getTotalCodewordsCount=function(e,n){switch(n){case xe.L:return qn[(e-1)*4+0];case xe.M:return qn[(e-1)*4+1];case xe.Q:return qn[(e-1)*4+2];case xe.H:return qn[(e-1)*4+3];default:return}}});var Xo=v(jn=>{var Gt=new Uint8Array(512),Wn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Gt[n]=e,Wn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Gt[n]=Gt[n-255]})();jn.log=function(e){if(e<1)throw new Error("log("+e+")");return Wn[e]};jn.exp=function(e){return Gt[e]};jn.mul=function(e,n){return e===0||n===0?0:Gt[Wn[e]+Wn[n]]}});var Qo=v(Vt=>{var os=Xo();Vt.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]^=os.mul(e[s],n[i]);return r};Vt.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]^=os.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Vt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Vt.mul(n,new Uint8Array([1,os.exp(r)]));return n}});var ta=v((av,ea)=>{var Zo=Qo();function as(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}as.prototype.initialize=function(e){this.degree=e,this.genPoly=Zo.generateECPolynomial(this.degree)};as.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=Zo.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};ea.exports=as});var ls=v(na=>{na.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var cs=v(ye=>{var ra="[0-9]+",Tf="[A-Z $%*+\\-./:]+",$t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";$t=$t.replace(/u/g,"\\u");var kf="(?:(?![A-Z0-9 $%*+\\-./:]|"+$t+`)(?:.|[\r
8
- ]))+`;ye.KANJI=new RegExp($t,"g");ye.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ye.BYTE=new RegExp(kf,"g");ye.NUMERIC=new RegExp(ra,"g");ye.ALPHANUMERIC=new RegExp(Tf,"g");var Cf=new RegExp("^"+$t+"$"),Ef=new RegExp("^"+ra+"$"),Rf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ye.testKanji=function(e){return Cf.test(e)};ye.testNumeric=function(e){return Ef.test(e)};ye.testAlphanumeric=function(e){return Rf.test(e)}});var Te=v(N=>{var Pf=ls(),us=cs();N.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};N.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};N.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};N.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};N.MIXED={bit:-1};N.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Pf.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};N.getBestModeForData=function(e){return us.testNumeric(e)?N.NUMERIC:us.testAlphanumeric(e)?N.ALPHANUMERIC:us.testKanji(e)?N.KANJI:N.BYTE};N.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};N.isValid=function(e){return e&&e.bit&&e.ccBits};function Mf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return N.NUMERIC;case"alphanumeric":return N.ALPHANUMERIC;case"kanji":return N.KANJI;case"byte":return N.BYTE;default:throw new Error("Unknown mode: "+t)}}N.from=function(e,n){if(N.isValid(e))return e;try{return Mf(e)}catch{return n}}});var la=v(Ge=>{var Gn=Ae(),Lf=is(),sa=Hn(),ke=Te(),ds=ls(),oa=7973,ia=Gn.getBCHDigit(oa);function Nf(t,e,n){for(let r=1;r<=40;r++)if(e<=Ge.getCapacity(r,n,t))return r}function aa(t,e){return ke.getCharCountIndicator(t,e)+4}function Of(t,e){let n=0;return t.forEach(function(r){let s=aa(r.mode,e);n+=s+r.getBitsLength()}),n}function Bf(t,e){for(let n=1;n<=40;n++)if(Of(t,n)<=Ge.getCapacity(n,e,ke.MIXED))return n}Ge.from=function(e,n){return ds.isValid(e)?parseInt(e,10):n};Ge.getCapacity=function(e,n,r){if(!ds.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ke.BYTE);let s=Gn.getSymbolTotalCodewords(e),i=Lf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===ke.MIXED)return o;let a=o-aa(r,e);switch(r){case ke.NUMERIC:return Math.floor(a/10*3);case ke.ALPHANUMERIC:return Math.floor(a/11*2);case ke.KANJI:return Math.floor(a/13);case ke.BYTE:default:return Math.floor(a/8)}};Ge.getBestVersionForData=function(e,n){let r,s=sa.from(n,sa.M);if(Array.isArray(e)){if(e.length>1)return Bf(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Nf(r.mode,r.getLength(),s)};Ge.getEncodedBits=function(e){if(!ds.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Gn.getBCHDigit(n)-ia>=0;)n^=oa<<Gn.getBCHDigit(n)-ia;return e<<12|n}});var fa=v(da=>{var fs=Ae(),ua=1335,Df=21522,ca=fs.getBCHDigit(ua);da.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;fs.getBCHDigit(s)-ca>=0;)s^=ua<<fs.getBCHDigit(s)-ca;return(r<<10|s)^Df}});var ha=v((pv,pa)=>{var Hf=Te();function lt(t){this.mode=Hf.NUMERIC,this.data=t.toString()}lt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};lt.prototype.getLength=function(){return this.data.length};lt.prototype.getBitsLength=function(){return lt.getBitsLength(this.data.length)};lt.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))};pa.exports=lt});var ma=v((hv,ga)=>{var Ff=Te(),ps=["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 ct(t){this.mode=Ff.ALPHANUMERIC,this.data=t}ct.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};ct.prototype.getLength=function(){return this.data.length};ct.prototype.getBitsLength=function(){return ct.getBitsLength(this.data.length)};ct.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ps.indexOf(this.data[n])*45;r+=ps.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(ps.indexOf(this.data[n]),6)};ga.exports=ct});var va=v((gv,ya)=>{var Uf=Te();function ut(t){this.mode=Uf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}ut.getBitsLength=function(e){return e*8};ut.prototype.getLength=function(){return this.data.length};ut.prototype.getBitsLength=function(){return ut.getBitsLength(this.data.length)};ut.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};ya.exports=ut});var _a=v((mv,Sa)=>{var qf=Te(),Wf=Ae();function dt(t){this.mode=qf.KANJI,this.data=t}dt.getBitsLength=function(e){return e*13};dt.prototype.getLength=function(){return this.data.length};dt.prototype.getBitsLength=function(){return dt.getBitsLength(this.data.length)};dt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Wf.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)}};Sa.exports=dt});var ba=v((yv,hs)=>{"use strict";var zt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=zt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,g;!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],g=typeof s[l]>"u",(g||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var h=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(h)}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=zt.single_source_shortest_paths(t,e,n);return zt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=zt.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 hs<"u"&&(hs.exports=zt)});var Ea=v(ft=>{var I=Te(),Aa=ha(),xa=ma(),Ta=va(),ka=_a(),Yt=cs(),Vn=Ae(),jf=ba();function wa(t){return unescape(encodeURIComponent(t)).length}function Jt(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=Jt(Yt.NUMERIC,I.NUMERIC,t),n=Jt(Yt.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return Vn.isKanjiModeEnabled()?(r=Jt(Yt.BYTE,I.BYTE,t),s=Jt(Yt.KANJI,I.KANJI,t)):(r=Jt(Yt.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 gs(t,e){switch(e){case I.NUMERIC:return Aa.getBitsLength(t);case I.ALPHANUMERIC:return xa.getBitsLength(t);case I.KANJI:return ka.getBitsLength(t);case I.BYTE:return Ta.getBitsLength(t)}}function Gf(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 Vf(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:wa(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:wa(r.data)}])}}return e}function $f(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]=gs(n[f].lastCount+c.length,c.mode)-gs(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=gs(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&&!Vn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new Aa(t);case I.ALPHANUMERIC:return new xa(t);case I.KANJI:return new ka(t);case I.BYTE:return new Ta(t)}}ft.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},[])};ft.fromString=function(e,n){let r=Ca(e,Vn.isKanjiModeEnabled()),s=Vf(r),i=$f(s,n),o=jf.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return ft.fromArray(Gf(a))};ft.rawSplit=function(e){return ft.fromArray(Ca(e,Vn.isKanjiModeEnabled()))}});var bs=v(Ra=>{var zn=Ae(),ms=Hn(),zf=jo(),Yf=Vo(),Jf=$o(),Kf=Jo(),Ss=Ko(),_s=is(),Xf=ta(),$n=la(),Qf=fa(),Zf=Te(),ys=Ea();function ep(t,e){let n=t.size,r=Kf.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 tp(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 np(t,e){let n=Jf.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 rp(t,e){let n=t.size,r=$n.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 vs(t,e,n){let r=t.size,s=Qf.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 sp(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 ip(t,e,n){let r=new zf;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Zf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=zn.getSymbolTotalCodewords(t),i=_s.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 op(r,t,e)}function op(t,e,n){let r=zn.getSymbolTotalCodewords(e),s=_s.getTotalCodewordsCount(e,n),i=r-s,o=_s.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 Xf(f),g=0,h=new Array(o),y=new Array(o),m=0,C=new Uint8Array(t.buffer);for(let le=0;le<o;le++){let Ze=le<l?u:d;h[le]=C.slice(g,g+Ze),y[le]=p.encode(h[le]),g+=Ze,m=Math.max(m,Ze)}let ae=new Uint8Array(r),R=0,D,K;for(D=0;D<m;D++)for(K=0;K<o;K++)D<h[K].length&&(ae[R++]=h[K][D]);for(D=0;D<f;D++)for(K=0;K<o;K++)ae[R++]=y[K][D];return ae}function ap(t,e,n,r){let s;if(Array.isArray(t))s=ys.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=ys.rawSplit(t);c=$n.getBestVersionForData(u,n)}s=ys.fromString(t,c||40)}else throw new Error("Invalid data");let i=$n.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 qe(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qe),t.emit("wsClientError",o,n,e)}else Wt(n,r,s,i)}});var ss=v((lv,Go)=>{Go.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Ae=v(We=>{var is,Af=[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];We.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};We.getSymbolTotalCodewords=function(e){return Af[e]};We.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};We.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');is=e};We.isKanjiModeEnabled=function(){return typeof is<"u"};We.toSJIS=function(e){return is(e)}});var Hn=v(Z=>{Z.L={bit:1};Z.M={bit:0};Z.Q={bit:3};Z.H={bit:2};function Tf(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 Tf(e)}catch{return n}}});var zo=v((dv,$o)=>{function Vo(){this.buffer=[],this.length=0}Vo.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++}};$o.exports=Vo});var Jo=v((fv,Yo)=>{function jt(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)}jt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};jt.prototype.get=function(t,e){return this.data[t*this.size+e]};jt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};jt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Yo.exports=jt});var Ko=v(Fn=>{var xf=Ae().getSymbolSize;Fn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=xf(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()};Fn.getPositions=function(e){let n=[],r=Fn.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 Zo=v(Xo=>{var kf=Ae().getSymbolSize,Qo=7;Xo.getPositions=function(e){let n=kf(e);return[[0,0],[n-Qo,0],[0,n-Qo]]}});var ea=v(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var je={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+=je.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=je.N1+(i-5)),a=u,i=1)}s>=5&&(r+=je.N1+(s-5)),i>=5&&(r+=je.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*je.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*je.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)*je.N4};function Cf(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,Cf(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 as=v(os=>{var Te=Hn(),Un=[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],qn=[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];os.getBlocksCount=function(e,n){switch(n){case Te.L:return Un[(e-1)*4+0];case Te.M:return Un[(e-1)*4+1];case Te.Q:return Un[(e-1)*4+2];case Te.H:return Un[(e-1)*4+3];default:return}};os.getTotalCodewordsCount=function(e,n){switch(n){case Te.L:return qn[(e-1)*4+0];case Te.M:return qn[(e-1)*4+1];case Te.Q:return qn[(e-1)*4+2];case Te.H:return qn[(e-1)*4+3];default:return}}});var ta=v(jn=>{var Gt=new Uint8Array(512),Wn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Gt[n]=e,Wn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Gt[n]=Gt[n-255]})();jn.log=function(e){if(e<1)throw new Error("log("+e+")");return Wn[e]};jn.exp=function(e){return Gt[e]};jn.mul=function(e,n){return e===0||n===0?0:Gt[Wn[e]+Wn[n]]}});var na=v(Vt=>{var ls=ta();Vt.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]^=ls.mul(e[s],n[i]);return r};Vt.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]^=ls.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Vt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Vt.mul(n,new Uint8Array([1,ls.exp(r)]));return n}});var ia=v((Sv,sa)=>{var ra=na();function cs(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}cs.prototype.initialize=function(e){this.degree=e,this.genPoly=ra.generateECPolynomial(this.degree)};cs.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=ra.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};sa.exports=cs});var us=v(oa=>{oa.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var ds=v(Se=>{var aa="[0-9]+",Ef="[A-Z $%*+\\-./:]+",$t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";$t=$t.replace(/u/g,"\\u");var Rf="(?:(?![A-Z0-9 $%*+\\-./:]|"+$t+`)(?:.|[\r
8
+ ]))+`;Se.KANJI=new RegExp($t,"g");Se.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Se.BYTE=new RegExp(Rf,"g");Se.NUMERIC=new RegExp(aa,"g");Se.ALPHANUMERIC=new RegExp(Ef,"g");var Pf=new RegExp("^"+$t+"$"),Mf=new RegExp("^"+aa+"$"),Lf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Se.testKanji=function(e){return Pf.test(e)};Se.testNumeric=function(e){return Mf.test(e)};Se.testAlphanumeric=function(e){return Lf.test(e)}});var xe=v(O=>{var Nf=us(),fs=ds();O.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};O.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};O.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};O.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};O.MIXED={bit:-1};O.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]};O.getBestModeForData=function(e){return fs.testNumeric(e)?O.NUMERIC:fs.testAlphanumeric(e)?O.ALPHANUMERIC:fs.testKanji(e)?O.KANJI:O.BYTE};O.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};O.isValid=function(e){return e&&e.bit&&e.ccBits};function Of(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return O.NUMERIC;case"alphanumeric":return O.ALPHANUMERIC;case"kanji":return O.KANJI;case"byte":return O.BYTE;default:throw new Error("Unknown mode: "+t)}}O.from=function(e,n){if(O.isValid(e))return e;try{return Of(e)}catch{return n}}});var fa=v(Ge=>{var Gn=Ae(),Bf=as(),la=Hn(),ke=xe(),ps=us(),ua=7973,ca=Gn.getBCHDigit(ua);function Df(t,e,n){for(let r=1;r<=40;r++)if(e<=Ge.getCapacity(r,n,t))return r}function da(t,e){return ke.getCharCountIndicator(t,e)+4}function Hf(t,e){let n=0;return t.forEach(function(r){let s=da(r.mode,e);n+=s+r.getBitsLength()}),n}function Ff(t,e){for(let n=1;n<=40;n++)if(Hf(t,n)<=Ge.getCapacity(n,e,ke.MIXED))return n}Ge.from=function(e,n){return ps.isValid(e)?parseInt(e,10):n};Ge.getCapacity=function(e,n,r){if(!ps.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ke.BYTE);let s=Gn.getSymbolTotalCodewords(e),i=Bf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===ke.MIXED)return o;let a=o-da(r,e);switch(r){case ke.NUMERIC:return Math.floor(a/10*3);case ke.ALPHANUMERIC:return Math.floor(a/11*2);case ke.KANJI:return Math.floor(a/13);case ke.BYTE:default:return Math.floor(a/8)}};Ge.getBestVersionForData=function(e,n){let r,s=la.from(n,la.M);if(Array.isArray(e)){if(e.length>1)return Ff(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Df(r.mode,r.getLength(),s)};Ge.getEncodedBits=function(e){if(!ps.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Gn.getBCHDigit(n)-ca>=0;)n^=ua<<Gn.getBCHDigit(n)-ca;return e<<12|n}});var ma=v(ga=>{var hs=Ae(),ha=1335,Uf=21522,pa=hs.getBCHDigit(ha);ga.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;hs.getBCHDigit(s)-pa>=0;)s^=ha<<hs.getBCHDigit(s)-pa;return(r<<10|s)^Uf}});var va=v((Tv,ya)=>{var qf=xe();function ct(t){this.mode=qf.NUMERIC,this.data=t.toString()}ct.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};ct.prototype.getLength=function(){return this.data.length};ct.prototype.getBitsLength=function(){return ct.getBitsLength(this.data.length)};ct.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))};ya.exports=ct});var _a=v((xv,Sa)=>{var Wf=xe(),gs=["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 ut(t){this.mode=Wf.ALPHANUMERIC,this.data=t}ut.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};ut.prototype.getLength=function(){return this.data.length};ut.prototype.getBitsLength=function(){return ut.getBitsLength(this.data.length)};ut.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=gs.indexOf(this.data[n])*45;r+=gs.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(gs.indexOf(this.data[n]),6)};Sa.exports=ut});var wa=v((kv,ba)=>{var jf=xe();function dt(t){this.mode=jf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}dt.getBitsLength=function(e){return e*8};dt.prototype.getLength=function(){return this.data.length};dt.prototype.getBitsLength=function(){return dt.getBitsLength(this.data.length)};dt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};ba.exports=dt});var Aa=v((Cv,Ia)=>{var Gf=xe(),Vf=Ae();function ft(t){this.mode=Gf.KANJI,this.data=t}ft.getBitsLength=function(e){return e*13};ft.prototype.getLength=function(){return this.data.length};ft.prototype.getBitsLength=function(){return ft.getBitsLength(this.data.length)};ft.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Vf.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)}};Ia.exports=ft});var Ta=v((Ev,ms)=>{"use strict";var zt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=zt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,g;!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],g=typeof s[l]>"u",(g||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var h=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(h)}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=zt.single_source_shortest_paths(t,e,n);return zt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=zt.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 ms<"u"&&(ms.exports=zt)});var La=v(pt=>{var I=xe(),Ca=va(),Ea=_a(),Ra=wa(),Pa=Aa(),Yt=ds(),Vn=Ae(),$f=Ta();function xa(t){return unescape(encodeURIComponent(t)).length}function Jt(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 Ma(t){let e=Jt(Yt.NUMERIC,I.NUMERIC,t),n=Jt(Yt.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return Vn.isKanjiModeEnabled()?(r=Jt(Yt.BYTE,I.BYTE,t),s=Jt(Yt.KANJI,I.KANJI,t)):(r=Jt(Yt.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 ys(t,e){switch(e){case I.NUMERIC:return Ca.getBitsLength(t);case I.ALPHANUMERIC:return Ea.getBitsLength(t);case I.KANJI:return Pa.getBitsLength(t);case I.BYTE:return Ra.getBitsLength(t)}}function zf(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:xa(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:xa(r.data)}])}}return e}function Jf(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]=ys(n[f].lastCount+c.length,c.mode)-ys(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=ys(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 ka(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&&!Vn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new Ca(t);case I.ALPHANUMERIC:return new Ea(t);case I.KANJI:return new Pa(t);case I.BYTE:return new Ra(t)}}pt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(ka(r,null)):r.data&&n.push(ka(r.data,r.mode)),n},[])};pt.fromString=function(e,n){let r=Ma(e,Vn.isKanjiModeEnabled()),s=Yf(r),i=Jf(s,n),o=$f.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return pt.fromArray(zf(a))};pt.rawSplit=function(e){return pt.fromArray(Ma(e,Vn.isKanjiModeEnabled()))}});var Is=v(Na=>{var zn=Ae(),vs=Hn(),Kf=zo(),Qf=Jo(),Xf=Ko(),Zf=Zo(),bs=ea(),ws=as(),ep=ia(),$n=fa(),tp=ma(),np=xe(),Ss=La();function rp(t,e){let n=t.size,r=Zf.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 sp(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 ip(t,e){let n=Xf.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 op(t,e){let n=t.size,r=$n.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 _s(t,e,n){let r=t.size,s=tp.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 ap(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 lp(t,e,n){let r=new Kf;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),np.getCharCountIndicator(l.mode,t)),l.write(r)});let s=zn.getSymbolTotalCodewords(t),i=ws.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 cp(r,t,e)}function cp(t,e,n){let r=zn.getSymbolTotalCodewords(e),s=ws.getTotalCodewordsCount(e,n),i=r-s,o=ws.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 ep(f),g=0,h=new Array(o),y=new Array(o),m=0,C=new Uint8Array(t.buffer);for(let ue=0;ue<o;ue++){let et=ue<l?u:d;h[ue]=C.slice(g,g+et),y[ue]=p.encode(h[ue]),g+=et,m=Math.max(m,et)}let ce=new Uint8Array(r),R=0,H,K;for(H=0;H<m;H++)for(K=0;K<o;K++)H<h[K].length&&(ce[R++]=h[K][H]);for(H=0;H<f;H++)for(K=0;K<o;K++)ce[R++]=y[K][H];return ce}function up(t,e,n,r){let s;if(Array.isArray(t))s=Ss.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Ss.rawSplit(t);c=$n.getBestVersionForData(u,n)}s=Ss.fromString(t,c||40)}else throw new Error("Invalid data");let i=$n.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=ip(e,n,s),a=zn.getSymbolSize(e),l=new Yf(a);return ep(l,e),tp(l),np(l,e),vs(l,n,0),e>=7&&rp(l,e),sp(l,o),isNaN(r)&&(r=Ss.getBestMask(l,vs.bind(null,l,n))),Ss.applyMask(r,l),vs(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Ra.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ms.M,s,i;return typeof n<"u"&&(r=ms.from(n.errorCorrectionLevel,ms.M),s=$n.from(n.version),i=Ss.from(n.maskPattern),n.toSJISFunc&&zn.setToSJISFunction(n.toSJISFunc)),ap(e,s,r,i)}});var ws=v((_v,Ma)=>{"use strict";var lp=require("util"),Pa=require("stream"),se=Ma.exports=function(){Pa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};lp.inherits(se,Pa);se.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))};se.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};se.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()))};se.prototype.destroySoon=se.prototype.end;se.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};se.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};se.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))};se.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)};se.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 As=v(Is=>{"use strict";var Ce=[{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]}];Is.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<Ce.length;a++){let l=Ce[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};Is.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ce[r].x.length,i=(e-s)/Ce[r].x.length*8+Ce[r].x[s],o=n%Ce[r].y.length,a=(n-o)/Ce[r].y.length*8+Ce[r].y[o];return i*4+a*t*4}}});var xs=v((wv,La)=>{"use strict";La.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 Ts=v((Iv,Oa)=>{"use strict";var cp=As(),up=xs();function Na(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var pt=Oa.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=cp.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Na(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Na(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};pt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};pt.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}};pt.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}};pt.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}};pt.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=up(c,l,u);e[o]=a+d}};pt.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 Ha=v((Av,Da)=>{"use strict";var dp=require("util"),Ba=ws(),fp=Ts(),pp=Da.exports=function(t){Ba.call(this);let e=[],n=this;this._filter=new fp(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};dp.inherits(pp,Ba)});var ht=v((xv,Fa)=>{"use strict";Fa.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 Es=v((Tv,Ua)=>{"use strict";var ks=[];(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;ks[t]=e}})();var Cs=Ua.exports=function(){this._crc=-1};Cs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ks[(this._crc^t[e])&255]^this._crc>>>8;return!0};Cs.prototype.crc32=function(){return this._crc^-1};Cs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ks[(e^t[n])&255]^e>>>8;return e^-1}});var Rs=v((kv,qa)=>{"use strict";var B=ht(),hp=Es(),F=qa.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[B.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[B.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[B.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[B.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[B.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[B.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(){}};F.prototype.start=function(){this.read(B.PNG_SIGNATURE.length,this._parseSignature.bind(this))};F.prototype._parseSignature=function(t){let e=B.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))};F.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!==B.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new hp,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))};F.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};F.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};F.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))};F.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};F.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 B.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=B.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&B.COLORTYPE_PALETTE),color:!!(s&B.COLORTYPE_COLOR),alpha:!!(s&B.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};F.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};F.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()};F.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};F.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===B.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===B.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===B.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};F.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};F.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/B.GAMMA_DIVISION),this._handleChunkEnd()};F.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};F.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===B.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()};F.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};F.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ps=v(ja=>{"use strict";var Wa=As(),gp=[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]}],mp=[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 yp(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 vp(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);gp[r](e,s,d,i),i+=r}return i}function Sp(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);mp[r](e,d,f,i)}s.resetAfterLine()}}ja.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=yp(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=Wa.getImagePasses(n,r),f=Wa.getInterlaceIterator(n,r);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=vp(d[p],l,f,i,t,u):Sp(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=v((Ev,Ga)=>{"use strict";function _p(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 bp(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 wp(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}}Ga.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?_p(t,l,r,s,a):(o&&bp(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),wp(t,l,r,s,n))),l}});var za=v((Rv,$a)=>{"use strict";var Ip=require("util"),Ls=require("zlib"),Va=ws(),Ap=Ha(),xp=Rs(),Tp=Ps(),kp=Ms(),ue=$a.exports=function(t){Va.call(this),this._parser=new xp(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()};Ip.inherits(ue,Va);ue.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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ls.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,Ls.Z_MIN_CHUNK);this._inflate=Ls.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)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ap(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Tp.dataToBitMap(t,this._bitmapInfo);e=kp(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ja=v((Pv,Ya)=>{"use strict";var ee=ht();Ya.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 g=(function(){let h=new ArrayBuffer(2);return new DataView(h).setInt16(0,256,!0),new Int16Array(h)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)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 g,h,y,m=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:m=i[u+3],g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_COLOR:g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_ALPHA:m=i[u+1],g=i[u],h=g,y=g;break;case ee.COLORTYPE_GRAYSCALE:g=i[u],h=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(m/=o,g=Math.min(Math.max(Math.round((1-m)*f.red+m*g),0),o),h=Math.min(Math.max(Math.round((1-m)*f.green+m*h),0),o),y=Math.min(Math.max(Math.round((1-m)*f.blue+m*y),0),o))),{red:g,green:h,blue:y,alpha:m}}for(let g=0;g<n;g++)for(let h=0;h<e;h++){let y=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let m=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=m,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(m,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var Qa=v((Mv,Xa)=>{"use strict";var Ka=xs();function Cp(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Ep(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);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=t[e+o]-a;r[s+o]=l}}function Pp(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 Mp(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 Lp(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 Np(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 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=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Bp(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]-Ka(a,l,c);r[s+o]=u}}function Dp(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]-Ka(o,a,l);s+=Math.abs(c)}return s}var Hp={0:Cp,1:Rp,2:Mp,3:Np,4:Bp},Fp={0:Ep,1:Pp,2:Lp,3:Op,4:Dp};Xa.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 g=Fp[i[p]](t,l,o,s);g<f&&(u=i[p],f=g)}}c[a]=u,a++,Hp[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Ns=v((Lv,Za)=>{"use strict";var q=ht(),Up=Es(),qp=Ja(),Wp=Qa(),jp=require("zlib"),Ee=Za.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||jp.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")};Ee.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ee.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ee.prototype.filterData=function(t,e,n){let r=qp(t,e,n,this._options),s=q.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Wp(r,e,n,this._options,s)};Ee.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(Up.crc32(r.slice(4,r.length-4)),r.length-4),r};Ee.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)};Ee.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)};Ee.prototype.packIDAT=function(t){return this._packChunk(q.TYPE_IDAT,t)};Ee.prototype.packIEND=function(){return this._packChunk(q.TYPE_IEND,null)}});var rl=v((Nv,nl)=>{"use strict";var Gp=require("util"),el=require("stream"),Vp=ht(),$p=Ns(),tl=nl.exports=function(t){el.call(this);let e=t||{};this._packer=new $p(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Gp.inherits(tl,el);tl.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Vp.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 cl=v((Kt,ll)=>{"use strict";var sl=require("assert").ok,gt=require("zlib"),zp=require("util"),il=require("buffer").kMaxLength;function Ve(t){if(!(this instanceof Ve))return new Ve(t);t&&t.chunkSize<gt.Z_MIN_CHUNK&&(t.chunkSize=gt.Z_MIN_CHUNK),gt.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 Ve(t)}function ol(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ve.prototype._processChunk=function(t,e,n){if(typeof n=="function")return gt.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(g){u=g});function d(g,h){if(r._hadError)return;let y=i-h;if(sl(y>=0,"have should not go down"),y>0){let m=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,m.length>o&&(m=m.slice(0,o)),l.push(m),c+=m.length,o-=m.length,o===0)return!1}return(h===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),h===0?(a+=s-g,s=g,!0):!1}sl(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>=il)throw ol(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+il.toString(16)+" bytes");let p=Buffer.concat(l,c);return ol(this),p};zp.inherits(Ve,gt.Inflate);function Jp(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=gt.Z_FINISH),t._processChunk(e,n)}function al(t,e){return Jp(new Ve(e),t)}ll.exports=Kt=al;Kt.Inflate=Ve;Kt.createInflate=Yp;Kt.inflateSync=al});var Os=v((Ov,dl)=>{"use strict";var ul=dl.exports=function(t){this._buffer=t,this._reads=[]};ul.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ul.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 pl=v(fl=>{"use strict";var Kp=Os(),Xp=Ts();fl.process=function(t,e){let n=[],r=new Kp(t);return new Xp(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var yl=v((Dv,ml)=>{"use strict";var hl=!0,gl=require("zlib"),Qp=cl();gl.deflateSync||(hl=!1);var Zp=Os(),eh=pl(),th=Rs(),nh=Ps(),rh=Ms();ml.exports=function(t,e){if(!hl)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(R){n=R}let s;function i(R){s=R}function o(R){s.transColor=R}function a(R){s.palette=R}function l(){s.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new Zp(t);if(new th(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 h=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=gl.inflateSync(h);else{let D=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=Qp(h,{chunkSize:D,maxLength:D})}if(h=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let m=eh.process(y,s);h=null;let C=nh.dataToBitMap(m,s);m=null;let ae=rh(C,s);return s.data=ae,s.gamma=c||0,s}});var bl=v((Hv,_l)=>{"use strict";var vl=!0,Sl=require("zlib");Sl.deflateSync||(vl=!1);var sh=ht(),ih=Ns();_l.exports=function(t,e){if(!vl)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 ih(n),s=[];s.push(Buffer.from(sh.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=Sl.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 wl=v(Bs=>{"use strict";var oh=yl(),ah=bl();Bs.read=function(t,e){return oh(t,e||{})};Bs.write=function(t,e){return ah(t,e)}});var xl=v(Al=>{"use strict";var lh=require("util"),Il=require("stream"),ch=za(),uh=rl(),dh=wl(),G=Al.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 ch(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 uh(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"))};lh.inherits(G,Il);G.sync=dh;G.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)};G.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};G.prototype.write=function(t){return this._parser.write(t),!0};G.prototype.end=function(t){this._parser.end(t)};G.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};G.prototype._gamma=function(t){this.gamma=t};G.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};G.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)};G.prototype.bitblt=function(t,e,n,r,s,i,o){return G.bitblt(this,t,e,n,r,s,i,o),this};G.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}};G.prototype.adjustGamma=function(){G.adjustGamma(this)}});var Xt=v($e=>{function Tl(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("")}}$e.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:Tl(e.color.dark||"#000000ff"),light:Tl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};$e.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};$e.getImageWidth=function(e,n){let r=$e.getScale(e,n);return Math.floor((e+n.margin*2)*r)};$e.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=$e.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 g=Math.floor((u-l)/o),h=Math.floor((d-l)/o);p=c[i[g*s+h]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var kl=v(de=>{var fh=require("fs"),ph=xl().PNG,Ds=Xt();de.render=function(e,n){let r=Ds.getOptions(n),s=r.rendererOpts,i=Ds.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new ph(s);return Ds.qrToImageData(o.data,e,r),o};de.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),de.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};de.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=de.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()};de.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=fh.createWriteStream(e);a.on("error",o),a.on("close",o),de.renderToFileStream(a,n,r)};de.renderToFileStream=function(e,n,r){de.render(n,r).pack().pipe(e)}});var Cl=v(Yn=>{var hh=Xt(),gh={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},mh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function yh(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Yn.render=function(t,e,n){let r=hh.getOptions(e),s=gh;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=mh);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+=yh(f,p,s)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Yn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Yn.render(n,r);i.writeFile(e,o,s)}});var Rl=v(El=>{El.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=lp(e,n,s),a=zn.getSymbolSize(e),l=new Qf(a);return rp(l,e),sp(l),ip(l,e),_s(l,n,0),e>=7&&op(l,e),ap(l,o),isNaN(r)&&(r=bs.getBestMask(l,_s.bind(null,l,n))),bs.applyMask(r,l),_s(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Na.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=vs.M,s,i;return typeof n<"u"&&(r=vs.from(n.errorCorrectionLevel,vs.M),s=$n.from(n.version),i=bs.from(n.maskPattern),n.toSJISFunc&&zn.setToSJISFunction(n.toSJISFunc)),up(e,s,r,i)}});var As=v((Mv,Ba)=>{"use strict";var dp=require("util"),Oa=require("stream"),se=Ba.exports=function(){Oa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};dp.inherits(se,Oa);se.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))};se.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};se.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()))};se.prototype.destroySoon=se.prototype.end;se.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};se.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};se.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))};se.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)};se.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 xs=v(Ts=>{"use strict";var Ce=[{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]}];Ts.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<Ce.length;a++){let l=Ce[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};Ts.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ce[r].x.length,i=(e-s)/Ce[r].x.length*8+Ce[r].x[s],o=n%Ce[r].y.length,a=(n-o)/Ce[r].y.length*8+Ce[r].y[o];return i*4+a*t*4}}});var ks=v((Nv,Da)=>{"use strict";Da.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 Cs=v((Ov,Fa)=>{"use strict";var fp=xs(),pp=ks();function Ha(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var ht=Fa.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=fp.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Ha(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Ha(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};ht.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ht.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}};ht.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}};ht.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}};ht.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=pp(c,l,u);e[o]=a+d}};ht.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 Wa=v((Bv,qa)=>{"use strict";var hp=require("util"),Ua=As(),gp=Cs(),mp=qa.exports=function(t){Ua.call(this);let e=[],n=this;this._filter=new gp(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};hp.inherits(mp,Ua)});var gt=v((Dv,ja)=>{"use strict";ja.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=v((Hv,Ga)=>{"use strict";var Es=[];(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;Es[t]=e}})();var Rs=Ga.exports=function(){this._crc=-1};Rs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Es[(this._crc^t[e])&255]^this._crc>>>8;return!0};Rs.prototype.crc32=function(){return this._crc^-1};Rs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Es[(e^t[n])&255]^e>>>8;return e^-1}});var Ms=v((Fv,Va)=>{"use strict";var B=gt(),yp=Ps(),U=Va.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[B.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[B.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[B.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[B.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[B.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[B.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(){}};U.prototype.start=function(){this.read(B.PNG_SIGNATURE.length,this._parseSignature.bind(this))};U.prototype._parseSignature=function(t){let e=B.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))};U.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!==B.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new yp,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))};U.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};U.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))};U.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};U.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 B.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=B.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&B.COLORTYPE_PALETTE),color:!!(s&B.COLORTYPE_COLOR),alpha:!!(s&B.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};U.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};U.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()};U.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};U.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===B.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===B.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===B.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};U.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};U.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/B.GAMMA_DIVISION),this._handleChunkEnd()};U.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};U.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===B.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()};U.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};U.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ls=v(za=>{"use strict";var $a=xs(),vp=[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]}],Sp=[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 _p(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 bp(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);vp[r](e,s,d,i),i+=r}return i}function wp(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);Sp[r](e,d,f,i)}s.resetAfterLine()}}za.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=_p(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=$a.getImagePasses(n,r),f=$a.getInterlaceIterator(n,r);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=bp(d[p],l,f,i,t,u):wp(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 Ns=v((qv,Ya)=>{"use strict";function Ip(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 Ap(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 Tp(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}}Ya.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?Ip(t,l,r,s,a):(o&&Ap(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Tp(t,l,r,s,n))),l}});var Qa=v((Wv,Ka)=>{"use strict";var xp=require("util"),Os=require("zlib"),Ja=As(),kp=Wa(),Cp=Ms(),Ep=Ls(),Rp=Ns(),fe=Ka.exports=function(t){Ja.call(this),this._parser=new Cp(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()};xp.inherits(fe,Ja);fe.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};fe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Os.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,Os.Z_MIN_CHUNK);this._inflate=Os.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)};fe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new kp(this._bitmapInfo)};fe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};fe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};fe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};fe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};fe.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};fe.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Ep.dataToBitMap(t,this._bitmapInfo);e=Rp(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Za=v((jv,Xa)=>{"use strict";var ee=gt();Xa.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 g=(function(){let h=new ArrayBuffer(2);return new DataView(h).setInt16(0,256,!0),new Int16Array(h)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)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 g,h,y,m=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:m=i[u+3],g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_COLOR:g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_ALPHA:m=i[u+1],g=i[u],h=g,y=g;break;case ee.COLORTYPE_GRAYSCALE:g=i[u],h=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(m/=o,g=Math.min(Math.max(Math.round((1-m)*f.red+m*g),0),o),h=Math.min(Math.max(Math.round((1-m)*f.green+m*h),0),o),y=Math.min(Math.max(Math.round((1-m)*f.blue+m*y),0),o))),{red:g,green:h,blue:y,alpha:m}}for(let g=0;g<n;g++)for(let h=0;h<e;h++){let y=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let m=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=m,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(m,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var nl=v((Gv,tl)=>{"use strict";var el=ks();function Pp(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Mp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}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=t[e+o]-a;r[s+o]=l}}function Np(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 Op(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 Bp(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 Dp(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 Hp(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 Fp(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]-el(a,l,c);r[s+o]=u}}function Up(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]-el(o,a,l);s+=Math.abs(c)}return s}var qp={0:Pp,1:Lp,2:Op,3:Dp,4:Fp},Wp={0:Mp,1:Np,2:Bp,3:Hp,4:Up};tl.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 g=Wp[i[p]](t,l,o,s);g<f&&(u=i[p],f=g)}}c[a]=u,a++,qp[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Bs=v((Vv,rl)=>{"use strict";var q=gt(),jp=Ps(),Gp=Za(),Vp=nl(),$p=require("zlib"),Ee=rl.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||$p.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")};Ee.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ee.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ee.prototype.filterData=function(t,e,n){let r=Gp(t,e,n,this._options),s=q.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Vp(r,e,n,this._options,s)};Ee.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(jp.crc32(r.slice(4,r.length-4)),r.length-4),r};Ee.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)};Ee.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)};Ee.prototype.packIDAT=function(t){return this._packChunk(q.TYPE_IDAT,t)};Ee.prototype.packIEND=function(){return this._packChunk(q.TYPE_IEND,null)}});var al=v(($v,ol)=>{"use strict";var zp=require("util"),sl=require("stream"),Yp=gt(),Jp=Bs(),il=ol.exports=function(t){sl.call(this);let e=t||{};this._packer=new Jp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};zp.inherits(il,sl);il.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 pl=v((Kt,fl)=>{"use strict";var ll=require("assert").ok,mt=require("zlib"),Kp=require("util"),cl=require("buffer").kMaxLength;function Ve(t){if(!(this instanceof Ve))return new Ve(t);t&&t.chunkSize<mt.Z_MIN_CHUNK&&(t.chunkSize=mt.Z_MIN_CHUNK),mt.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 Qp(t){return new Ve(t)}function ul(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ve.prototype._processChunk=function(t,e,n){if(typeof n=="function")return mt.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(g){u=g});function d(g,h){if(r._hadError)return;let y=i-h;if(ll(y>=0,"have should not go down"),y>0){let m=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,m.length>o&&(m=m.slice(0,o)),l.push(m),c+=m.length,o-=m.length,o===0)return!1}return(h===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),h===0?(a+=s-g,s=g,!0):!1}ll(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>=cl)throw ul(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+cl.toString(16)+" bytes");let p=Buffer.concat(l,c);return ul(this),p};Kp.inherits(Ve,mt.Inflate);function Xp(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=mt.Z_FINISH),t._processChunk(e,n)}function dl(t,e){return Xp(new Ve(e),t)}fl.exports=Kt=dl;Kt.Inflate=Ve;Kt.createInflate=Qp;Kt.inflateSync=dl});var Ds=v((zv,gl)=>{"use strict";var hl=gl.exports=function(t){this._buffer=t,this._reads=[]};hl.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};hl.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 yl=v(ml=>{"use strict";var Zp=Ds(),eh=Cs();ml.process=function(t,e){let n=[],r=new Zp(t);return new eh(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var bl=v((Jv,_l)=>{"use strict";var vl=!0,Sl=require("zlib"),th=pl();Sl.deflateSync||(vl=!1);var nh=Ds(),rh=yl(),sh=Ms(),ih=Ls(),oh=Ns();_l.exports=function(t,e){if(!vl)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(R){n=R}let s;function i(R){s=R}function o(R){s.transColor=R}function a(R){s.palette=R}function l(){s.alpha=!0}let c;function u(R){c=R}let d=[];function f(R){d.push(R)}let p=new nh(t);if(new sh(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 h=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=Sl.inflateSync(h);else{let H=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=th(h,{chunkSize:H,maxLength:H})}if(h=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let m=rh.process(y,s);h=null;let C=ih.dataToBitMap(m,s);m=null;let ce=oh(C,s);return s.data=ce,s.gamma=c||0,s}});var Tl=v((Kv,Al)=>{"use strict";var wl=!0,Il=require("zlib");Il.deflateSync||(wl=!1);var ah=gt(),lh=Bs();Al.exports=function(t,e){if(!wl)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 lh(n),s=[];s.push(Buffer.from(ah.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=Il.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 xl=v(Hs=>{"use strict";var ch=bl(),uh=Tl();Hs.read=function(t,e){return ch(t,e||{})};Hs.write=function(t,e){return uh(t,e)}});var El=v(Cl=>{"use strict";var dh=require("util"),kl=require("stream"),fh=Qa(),ph=al(),hh=xl(),G=Cl.PNG=function(t){kl.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 fh(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 ph(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"))};dh.inherits(G,kl);G.sync=hh;G.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)};G.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};G.prototype.write=function(t){return this._parser.write(t),!0};G.prototype.end=function(t){this._parser.end(t)};G.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};G.prototype._gamma=function(t){this.gamma=t};G.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};G.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)};G.prototype.bitblt=function(t,e,n,r,s,i,o){return G.bitblt(this,t,e,n,r,s,i,o),this};G.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}};G.prototype.adjustGamma=function(){G.adjustGamma(this)}});var Qt=v($e=>{function Rl(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("")}}$e.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:Rl(e.color.dark||"#000000ff"),light:Rl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};$e.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};$e.getImageWidth=function(e,n){let r=$e.getScale(e,n);return Math.floor((e+n.margin*2)*r)};$e.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=$e.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 g=Math.floor((u-l)/o),h=Math.floor((d-l)/o);p=c[i[g*s+h]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var Pl=v(pe=>{var gh=require("fs"),mh=El().PNG,Fs=Qt();pe.render=function(e,n){let r=Fs.getOptions(n),s=r.rendererOpts,i=Fs.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new mh(s);return Fs.qrToImageData(o.data,e,r),o};pe.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),pe.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};pe.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=pe.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()};pe.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=gh.createWriteStream(e);a.on("error",o),a.on("close",o),pe.renderToFileStream(a,n,r)};pe.renderToFileStream=function(e,n,r){pe.render(n,r).pack().pipe(e)}});var Ml=v(Yn=>{var yh=Qt(),vh={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Sh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function _h(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Yn.render=function(t,e,n){let r=yh.getOptions(e),s=vh;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Sh);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+=_h(f,p,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Yn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Yn.render(n,r);i.writeFile(e,o,s)}});var Nl=v(Ll=>{Ll.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 Nl=v(Ll=>{var vh="\x1B[47m",Sh="\x1B[40m",Hs="\x1B[37m",Fs="\x1B[30m",ze="\x1B[0m",_h=vh+Fs,bh=Sh+Hs,wh=function(t,e,n){return{"00":ze+" "+t,"01":ze+e+"\u2584"+t,"02":ze+n+"\u2584"+t,10:ze+e+"\u2580"+t,11:" ",12:"\u2584",20:ze+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"},Ml=function(t,e,n,r){return Pl(t,e,n,r)+Pl(t,e,n,r+1)};Ll.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?bh:_h,c=wh(o,i?Fs:Hs,i?Hs:Fs),u=ze+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[Ml(s,r,p,f)];d+=c[Ml(s,r,r,f)]+u}return d+=ze,typeof n=="function"&&n(null,d),d}});var Bl=v(Ol=>{var Ih=Rl(),Ah=Nl();Ol.render=function(t,e,n){return e&&e.small?Ah.render(t,e,n):Ih.render(t,e,n)}});var qs=v(Hl=>{var xh=Xt();function Dl(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Us(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Th(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?Us("M",l+n,.5+c+n):Us("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=Us("h",o),o=0)):s++}return r}Hl.render=function(e,n,r){let s=xh.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+Dl(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Dl(s.color.dark,"stroke")+' d="'+Th(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 Fl=v(Jn=>{var kh=qs();Jn.render=kh.render;Jn.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">'+Jn.render(n,r);i.writeFile(e,a,s)}});var Ul=v(Kn=>{var Ws=Xt();function Ch(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 Eh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Kn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Eh()),s=Ws.getOptions(s);let o=Ws.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Ws.qrToImageData(l.data,e,s),Ch(a,i,o),a.putImageData(l,0,0),i};Kn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Kn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Wl=v(Qt=>{var Rh=ns(),js=bs(),ql=Ul(),Ph=qs();function Gs(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Rh())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=js.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=js.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Qt.create=js.create;Qt.toCanvas=Gs.bind(null,ql.render);Qt.toDataURL=Gs.bind(null,ql.renderToDataURL);Qt.toString=Gs.bind(null,function(t,e,n){return Ph.render(t,n)})});var $l=v(Re=>{var jl=ns(),Vs=bs(),Mh=kl(),Gl=Cl(),Lh=Bl(),Vl=Fl();function Zt(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(jl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Nh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Xn(t){switch(t){case"svg":return Vl;case"txt":case"utf8":return Gl;case"png":case"image/png":default:return Mh}}function Oh(t){switch(t){case"svg":return Vl;case"terminal":return Lh;case"utf8":default:return Gl}}function en(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=Vs.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=Vs.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Re.create=Vs.create;Re.toCanvas=Wl().toCanvas;Re.toString=function(e,n,r){let s=Zt(e,n,r),i=s.opts?s.opts.type:void 0,o=Oh(i);return en(o.render,e,s)};Re.toDataURL=function(e,n,r){let s=Zt(e,n,r),i=Xn(s.opts.type);return en(i.renderToDataURL,e,s)};Re.toBuffer=function(e,n,r){let s=Zt(e,n,r),i=Xn(s.opts.type);return en(i.renderToBuffer,e,s)};Re.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&&!jl())throw new Error("Too few arguments provided");let i=Zt(n,r,s),o=i.opts.type||Nh(e),l=Xn(o).renderToFile.bind(null,e);return en(l,n,i)};Re.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Zt(n,r,e.emit.bind(e,"error")),o=Xn("png").renderToFileStream.bind(null,e);en(o,n,s)}});var Yl=v((Qv,zl)=>{zl.exports=$l()});var Hu=require("http");var yf=et(Ro(),1),vf=et(Gr(),1),Sf=et(zr(),1),_f=et(Bn(),1),ts=et(Fo(),1);var ne=require("fs/promises"),Fu=require("crypto"),In=require("path"),Uu=require("os"),Li=et(Yl(),1);var Je=require("child_process"),ac=require("fs"),L=require("path"),tn=require("os");var ir=require("fs");var Jl=require("os"),W=require("path"),ve=(0,W.join)((0,Jl.homedir)(),".vibelet"),Qn=(0,W.join)(ve,"logs"),Zn=(0,W.join)(ve,"data"),Bh=(0,W.join)(ve,"runtime"),Zv=(0,W.join)(Bh,"current"),Kl=(0,W.join)(ve,"identity.json"),Xl=(0,W.join)(ve,"pairings.json"),Ql=(0,W.join)(Zn,"push-subscriptions.json"),er=(0,W.join)(Zn,"sessions.json"),mt=(0,W.join)(Zn,"audit.jsonl"),$s=(0,W.join)(Zn,"uploads"),tr=(0,W.join)(Qn,"daemon.stdout.log"),nr=(0,W.join)(Qn,"daemon.stderr.log"),Zl=(0,W.join)(ve,"update-check.json"),zs=(0,W.join)(ve,"pairing-qr.png");var rr={stdout:!1,stderr:!1};function ec(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Dh(t){return!t.destroyed&&t.writable!==!1}function tc(t,e){if(rr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Dh(n))return rr[t]=!0,!1;try{return n.write(e,r=>{ec(r)&&(rr[t]=!0)}),!0}catch(r){return ec(r)&&(rr[t]=!0),!1}}function yt(t){return tc("stdout",t)}function sr(t){return tc("stderr",t)}var nc={debug:10,info:20,warn:30,error:40},Hh=process.env.VIBE_LOG_LEVEL||"info";function Fh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Uh(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var sc=!Fh()&&!Uh();if(sc)try{(0,ir.mkdirSync)(Qn,{recursive:!0})}catch{}function rc(t,e,n){if(nc[t]<nc[Hh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?sr(s+`
21
- `):yt(s+`
22
- `),sc){let i=t==="error"||t==="warn"?nr:tr;try{(0,ir.appendFileSync)(i,s+`
23
- `)}catch{}}}function ic(t={}){function e(n,r,s){typeof r=="string"?rc(n,t,r):rc(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=>ic({...t,...n})}}var M=ic({module:"daemon"});var qh=["fnm_multishells"],Wh=6e4,Me=process.platform==="win32",jh=M.child({module:"config"});function Pe(t){return qh.some(e=>t.includes(e))}function Ks(){return Me?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var vt=null;function lc(){if(vt&&!Pe(vt.PATH??""))return vt;for(let t of Ks())try{let e=(0,Je.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 Pe(n.PATH??"")?vt=null:vt=n,n}catch{}return vt={},{}}function Gh(t=lc()){let e=(0,tn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Me?(0,L.join)(e,"pnpm"):(0,L.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Me?[(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n,(0,L.join)(e,"AppData","Roaming","npm"),(0,L.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n],i=r.split(L.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(L.delimiter)}function Ys(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 Js(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 or(){let t=lc(),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=Gh(t),e.HOME||(e.HOME=(0,tn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Xs(t){if(Me)try{let n=(0,Je.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function Ye(t,e=3e3){try{return(0,Je.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:or(),...Me?{shell:!0}:{}}).trim()||null}catch{return null}}function Vh(t){for(let e of Ks())try{let n=(0,Je.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function $h(){let t=(0,tn.homedir)();return[(0,L.join)(t,".local","bin","claude"),(0,L.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,L.join)(t,".npm-global","bin","claude")]}function zh(){if(Me){let t=Xs("claude");return t&&Ye(t)?t:void 0}for(let t of $h())if(Ye(t))return t;try{let t=(0,Je.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:or()}).trim();if(t&&!t.includes("cmux")&&Ye(t))return t}catch{}}function Yh(){let t=(0,tn.homedir)(),e=[process.env.PNPM_HOME,(0,L.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,L.join)(t,".npm-global","bin","codex"),(0,L.join)(t,".local","bin","codex"),...e.map(n=>(0,L.join)(n,"codex"))]}function Jh(){if(Me){let n=Xs("codex");return n&&Ye(n)?n:void 0}let t;for(let n of Yh())if(Ye(n)){if(!Pe(n))return n;t=n}try{let n=(0,Je.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:or()}).trim();if(n&&Ye(n)){if(!Pe(n))return n;t=t??n}}catch{}let e=Vh("codex");if(e&&Ye(e)){if(!Pe(e))return e;t=t??e}return t}function cc(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>Wh||!(0,ac.existsSync)(n)||Pe(n))&&(n=t()??e,r=i,jh.info({name:e,path:n,transient:Pe(n)},"binary resolved")),n}}var Kh=cc(zh,"claude"),Xh=cc(Jh,"codex");function Qh(){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 oc=Qh();function Zh(t,e){return Me?{command:Xs(t)??t,args:e}:{command:Ks()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:oc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:oc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Js("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Js("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Ys("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Ys("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Ys("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Js("VIBE_PAIR_WINDOW_MS",300*1e3),get claudePath(){return Kh()},get codexPath(){return Xh()},isTransientPath:Pe,execViaLoginShell:Zh,buildSanitizedEnv:or};var Ai=require("crypto"),mu=require("fs/promises");var vc=require("child_process"),Sc=require("fs");var ar=require("fs"),fc=require("path");var V=require("fs");function eg(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 nn(t,e){if(!(0,V.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,V.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=eg(r,e.maxBytes,s,e.retainBytes),o=(0,V.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,V.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,V.ftruncateSync)(o,0),a.length>0&&(0,V.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,V.closeSync)(o)}}function uc(t){let e=[nn(t.auditPath,{maxBytes:t.auditMaxBytes}),nn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),nn(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 dc=!1,tg=new Set(["ts","event","source","appEvent","level"]);function ng(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function rg(t={}){let e={};for(let[n,r]of Object.entries(t))tg.has(n)||(e[n]=r);return e}function sg(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...rg(n)}}function ig(){dc||((0,ar.mkdirSync)((0,fc.dirname)(mt),{recursive:!0}),dc=!0)}var Qs=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(sg(e,n,r,s))}write(e){if(!ng()){ig();try{let n=JSON.stringify(e)+`
25
- `;nn(mt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,ar.appendFileSync)(mt,n)}catch{}}}},_=new Qs;var Le=require("fs"),pc=require("os"),rn=require("path"),hc=require("crypto"),Zs="claude-hook:",sn="x-vibelet-claude-hook-secret",on={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function og(t,e){return`#!/usr/bin/env node
18
+ `,typeof n=="function"&&n(null,a),a}});var Hl=v(Dl=>{var bh="\x1B[47m",wh="\x1B[40m",Us="\x1B[37m",qs="\x1B[30m",ze="\x1B[0m",Ih=bh+qs,Ah=wh+Us,Th=function(t,e,n){return{"00":ze+" "+t,"01":ze+e+"\u2584"+t,"02":ze+n+"\u2584"+t,10:ze+e+"\u2580"+t,11:" ",12:"\u2584",20:ze+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Ol=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"},Bl=function(t,e,n,r){return Ol(t,e,n,r)+Ol(t,e,n,r+1)};Dl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Ah:Ih,c=Th(o,i?qs:Us,i?Us:qs),u=ze+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[Bl(s,r,p,f)];d+=c[Bl(s,r,r,f)]+u}return d+=ze,typeof n=="function"&&n(null,d),d}});var Ul=v(Fl=>{var xh=Nl(),kh=Hl();Fl.render=function(t,e,n){return e&&e.small?kh.render(t,e,n):xh.render(t,e,n)}});var js=v(Wl=>{var Ch=Qt();function ql(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Ws(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Eh(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?Ws("M",l+n,.5+c+n):Ws("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=Ws("h",o),o=0)):s++}return r}Wl.render=function(e,n,r){let s=Ch.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+ql(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+ql(s.color.dark,"stroke")+' d="'+Eh(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 jl=v(Jn=>{var Rh=js();Jn.render=Rh.render;Jn.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">'+Jn.render(n,r);i.writeFile(e,a,s)}});var Gl=v(Kn=>{var Gs=Qt();function Ph(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 Mh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Kn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Mh()),s=Gs.getOptions(s);let o=Gs.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Gs.qrToImageData(l.data,e,s),Ph(a,i,o),a.putImageData(l,0,0),i};Kn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Kn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var $l=v(Xt=>{var Lh=ss(),Vs=Is(),Vl=Gl(),Nh=js();function $s(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Lh())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=Vs.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Vs.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Xt.create=Vs.create;Xt.toCanvas=$s.bind(null,Vl.render);Xt.toDataURL=$s.bind(null,Vl.renderToDataURL);Xt.toString=$s.bind(null,function(t,e,n){return Nh.render(t,n)})});var Kl=v(Re=>{var zl=ss(),zs=Is(),Oh=Pl(),Yl=Ml(),Bh=Ul(),Jl=jl();function Zt(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(zl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Dh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Qn(t){switch(t){case"svg":return Jl;case"txt":case"utf8":return Yl;case"png":case"image/png":default:return Oh}}function Hh(t){switch(t){case"svg":return Jl;case"terminal":return Bh;case"utf8":default:return Yl}}function en(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=zs.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=zs.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Re.create=zs.create;Re.toCanvas=$l().toCanvas;Re.toString=function(e,n,r){let s=Zt(e,n,r),i=s.opts?s.opts.type:void 0,o=Hh(i);return en(o.render,e,s)};Re.toDataURL=function(e,n,r){let s=Zt(e,n,r),i=Qn(s.opts.type);return en(i.renderToDataURL,e,s)};Re.toBuffer=function(e,n,r){let s=Zt(e,n,r),i=Qn(s.opts.type);return en(i.renderToBuffer,e,s)};Re.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&&!zl())throw new Error("Too few arguments provided");let i=Zt(n,r,s),o=i.opts.type||Dh(e),l=Qn(o).renderToFile.bind(null,e);return en(l,n,i)};Re.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Zt(n,r,e.emit.bind(e,"error")),o=Qn("png").renderToFileStream.bind(null,e);en(o,n,s)}});var Xl=v((uS,Ql)=>{Ql.exports=Kl()});var qu=require("http");var _f=tt(No(),1),bf=tt($r(),1),wf=tt(Jr(),1),If=tt(Bn(),1),rs=tt(jo(),1);var ne=require("fs/promises"),Wu=require("crypto"),In=require("path"),ju=require("os"),Di=tt(Xl(),1);var Je=require("child_process"),dc=require("fs"),L=require("path"),tn=require("os");var ir=require("fs");var Zl=require("os"),W=require("path"),_e=(0,W.join)((0,Zl.homedir)(),".vibelet"),Xn=(0,W.join)(_e,"logs"),Zn=(0,W.join)(_e,"data"),Fh=(0,W.join)(_e,"runtime"),dS=(0,W.join)(Fh,"current"),ec=(0,W.join)(_e,"identity.json"),tc=(0,W.join)(_e,"pairings.json"),nc=(0,W.join)(Zn,"push-subscriptions.json"),er=(0,W.join)(Zn,"sessions.json"),yt=(0,W.join)(Zn,"audit.jsonl"),Ys=(0,W.join)(Zn,"uploads"),tr=(0,W.join)(Xn,"daemon.stdout.log"),nr=(0,W.join)(Xn,"daemon.stderr.log"),rc=(0,W.join)(_e,"update-check.json"),Js=(0,W.join)(_e,"pairing-qr.png");var rr={stdout:!1,stderr:!1};function sc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Uh(t){return!t.destroyed&&t.writable!==!1}function ic(t,e){if(rr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Uh(n))return rr[t]=!0,!1;try{return n.write(e,r=>{sc(r)&&(rr[t]=!0)}),!0}catch(r){return sc(r)&&(rr[t]=!0),!1}}function vt(t){return ic("stdout",t)}function sr(t){return ic("stderr",t)}var oc={debug:10,info:20,warn:30,error:40},qh=process.env.VIBE_LOG_LEVEL||"info";function Wh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function jh(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var lc=!Wh()&&!jh();if(lc)try{(0,ir.mkdirSync)(Xn,{recursive:!0})}catch{}function ac(t,e,n){if(oc[t]<oc[qh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?sr(s+`
21
+ `):vt(s+`
22
+ `),lc){let i=t==="error"||t==="warn"?nr:tr;try{(0,ir.appendFileSync)(i,s+`
23
+ `)}catch{}}}function cc(t={}){function e(n,r,s){typeof r=="string"?ac(n,t,r):ac(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=>cc({...t,...n})}}var M=cc({module:"daemon"});var Gh=["fnm_multishells"],Vh=6e4,Me=process.platform==="win32",$h=M.child({module:"config"});function Pe(t){return Gh.some(e=>t.includes(e))}function Xs(){return Me?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var St=null;function fc(){if(St&&!Pe(St.PATH??""))return St;for(let t of Xs())try{let e=(0,Je.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 Pe(n.PATH??"")?St=null:St=n,n}catch{}return St={},{}}function zh(t=fc()){let e=(0,tn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Me?(0,L.join)(e,"pnpm"):(0,L.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Me?[(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n,(0,L.join)(e,"AppData","Roaming","npm"),(0,L.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n],i=r.split(L.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(L.delimiter)}function Ks(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 Qs(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 or(){let t=fc(),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=zh(t),e.HOME||(e.HOME=(0,tn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Zs(t){if(Me)try{let n=(0,Je.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function Ye(t,e=3e3){try{return(0,Je.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:or(),...Me?{shell:!0}:{}}).trim()||null}catch{return null}}function Yh(t){for(let e of Xs())try{let n=(0,Je.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Jh(){let t=(0,tn.homedir)();return[(0,L.join)(t,".local","bin","claude"),(0,L.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,L.join)(t,".npm-global","bin","claude")]}function Kh(){if(Me){let t=Zs("claude");return t&&Ye(t)?t:void 0}for(let t of Jh())if(Ye(t))return t;try{let t=(0,Je.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:or()}).trim();if(t&&!t.includes("cmux")&&Ye(t))return t}catch{}}function Qh(){let t=(0,tn.homedir)(),e=[process.env.PNPM_HOME,(0,L.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,L.join)(t,".npm-global","bin","codex"),(0,L.join)(t,".local","bin","codex"),...e.map(n=>(0,L.join)(n,"codex"))]}function Xh(){if(Me){let n=Zs("codex");return n&&Ye(n)?n:void 0}let t;for(let n of Qh())if(Ye(n)){if(!Pe(n))return n;t=n}try{let n=(0,Je.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:or()}).trim();if(n&&Ye(n)){if(!Pe(n))return n;t=t??n}}catch{}let e=Yh("codex");if(e&&Ye(e)){if(!Pe(e))return e;t=t??e}return t}function pc(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>Vh||!(0,dc.existsSync)(n)||Pe(n))&&(n=t()??e,r=i,$h.info({name:e,path:n,transient:Pe(n)},"binary resolved")),n}}var Zh=pc(Kh,"claude"),eg=pc(Xh,"codex");function tg(){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 uc=tg();function ng(t,e){return Me?{command:Zs(t)??t,args:e}:{command:Xs()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:uc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:uc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Qs("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Qs("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Ks("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Ks("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Ks("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Qs("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return Zh()},get codexPath(){return eg()},isTransientPath:Pe,execViaLoginShell:ng,buildSanitizedEnv:or};var xi=require("crypto"),bu=require("fs/promises");var wc=require("child_process"),Ic=require("fs");var ar=require("fs"),mc=require("path");var V=require("fs");function rg(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 nn(t,e){if(!(0,V.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,V.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=rg(r,e.maxBytes,s,e.retainBytes),o=(0,V.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,V.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,V.ftruncateSync)(o,0),a.length>0&&(0,V.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,V.closeSync)(o)}}function hc(t){let e=[nn(t.auditPath,{maxBytes:t.auditMaxBytes}),nn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),nn(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 gc=!1,sg=new Set(["ts","event","source","appEvent","level"]);function ig(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function og(t={}){let e={};for(let[n,r]of Object.entries(t))sg.has(n)||(e[n]=r);return e}function ag(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...og(n)}}function lg(){gc||((0,ar.mkdirSync)((0,mc.dirname)(yt),{recursive:!0}),gc=!0)}var ei=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(ag(e,n,r,s))}write(e){if(!ig()){lg();try{let n=JSON.stringify(e)+`
25
+ `;nn(yt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,ar.appendFileSync)(yt,n)}catch{}}}},b=new ei;var Le=require("fs"),yc=require("os"),rn=require("path"),vc=require("crypto"),ti="claude-hook:",sn="x-vibelet-claude-hook-secret",on={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function cg(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));
@@ -43,7 +43,7 @@ process.stdin.on('end', () => {
43
43
  req.end(body);
44
44
  });
45
45
  process.stdin.resume();
46
- `}function ag(t,e){return`#!/usr/bin/env node
46
+ `}function ug(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
48
  const fallback = ${JSON.stringify(JSON.stringify(on))};
49
49
  const chunks = [];
@@ -79,41 +79,41 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function gc(t,e){let n=(0,rn.join)((0,pc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,hc.randomUUID)()}`);(0,Le.mkdirSync)(n,{recursive:!0});let r=(0,rn.join)(n,"settings.json"),s=(0,rn.join)(n,"session_hook_forwarder.cjs"),i=(0,rn.join)(n,"permission_hook_forwarder.cjs");return(0,Le.writeFileSync)(s,og(t,e),"utf8"),(0,Le.writeFileSync)(i,ag(t,e),"utf8"),(0,Le.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 lr(t){if(t)try{(0,Le.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var te=M.child({module:"claude"}),_c="claude-permission-denial:",lg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function cg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function ei(t){cg()&&sr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
- `)}function ug(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 dg(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function fg(t){if(typeof t=="string")return t;let e=ug(t);return e||(dg(t)?"":JSON.stringify(t))}function pg(t){return/requested permissions|haven't granted/i.test(t)}function mc(t){return t.replace(lg,"").replace(/\s+/g," ").trim()}function hg(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function gg(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 mg(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function yc(t){let e=mc(t.resultText??""),n=(t.stderrLines??[]).map(mc).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&gg(i));if(r)return mg(r);let s=[e,...n].find(i=>!!i&&!hg(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 cr(t){return t.startsWith(_c)}var an=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=S.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,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),lr(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=gc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;te.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),ei(`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,vc.spawn)(S.claudePath,r,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",i=>{let o=i.message;i.code==="ENOENT"&&this.cwd&&!(0,Sc.existsSync)(this.cwd)&&(o=`Working directory does not exist: ${this.cwd}`),te.error({sessionId:this.sessionId,error:o,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:o}),this.handler?.({type:"error",sessionId:this.sessionId,message:o})}),this.buffer="",this.proc.stdout.on("data",i=>{this.buffer+=i.toString();let o=this.buffer.split(`
85
- `);this.buffer=o.pop();for(let a of o)if(a.trim())try{this.handleRaw(JSON.parse(a))}catch{te.warn({sessionId:this.sessionId,linePreview:a.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",i=>{let o=i.toString().trim();o&&(te.debug({sessionId:this.sessionId,stderr:o},"stderr"),this.lastStderr.push(o),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(i,o)=>{te.info({sessionId:this.sessionId,exitCode:i,signal:o},"process exited");let a=this.interrupted;this.proc=null,lr(this.hookFiles),this.hookFiles=null,this.interrupted=!1,a&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):i&&i!==0&&!this.sawFinalResult&&(te.error({sessionId:this.sessionId,exitCode:i,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:yc({stderrLines:this.lastStderr,exitCode:i})})),this.exitHandler?.(i)})}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,lr(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=fg(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&pg(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){ei("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:yc({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:`${_c}${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;ei("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 Ac=require("child_process"),xc=require("fs");var ti=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();M.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new ti;var bc=require("node:fs"),ni=require("node:path"),yg="@vibelet/cli";function vg(t){try{let e=JSON.parse((0,bc.readFileSync)(t,"utf8"));if(e.name===yg&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Sg(){return"1.0.0"}var St=Sg();var x=M.child({module:"codex"});function _g(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 bg(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 wg=new Set(["aborted","interrupted","cancelled","canceled"]);function Ig(t){let e=k(t);return e?e.toLowerCase():null}function Ag(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function ri(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function si(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Tc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function kc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function xg(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=>Tc(l))??i[0],a=i.find(l=>kc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Tg(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=>Tc(s)),r=e.some(s=>kc(s));return n&&r}function wc(t){let e=Ag(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:si(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:si(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 kg(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 Ic(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var ln=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)){let c=S.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,Ac.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,xc.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(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;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:St},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}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=Ic(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,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:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{x.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.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=bg(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}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(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;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
- `),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()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
82
+ `}function Sc(t,e){let n=(0,rn.join)((0,yc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,vc.randomUUID)()}`);(0,Le.mkdirSync)(n,{recursive:!0});let r=(0,rn.join)(n,"settings.json"),s=(0,rn.join)(n,"session_hook_forwarder.cjs"),i=(0,rn.join)(n,"permission_hook_forwarder.cjs");return(0,Le.writeFileSync)(s,cg(t,e),"utf8"),(0,Le.writeFileSync)(i,ug(t,e),"utf8"),(0,Le.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 lr(t){if(t)try{(0,Le.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var te=M.child({module:"claude"}),Ac="claude-permission-denial:",dg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function fg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function ni(t){fg()&&sr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
+ `)}function pg(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 hg(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function gg(t){if(typeof t=="string")return t;let e=pg(t);return e||(hg(t)?"":JSON.stringify(t))}function mg(t){return/requested permissions|haven't granted/i.test(t)}function _c(t){return t.replace(dg,"").replace(/\s+/g," ").trim()}function yg(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function vg(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 Sg(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function bc(t){let e=_c(t.resultText??""),n=(t.stderrLines??[]).map(_c).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&vg(i));if(r)return Sg(r);let s=[e,...n].find(i=>!!i&&!yg(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 cr(t){return t.startsWith(Ac)}var an=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=S.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"),b.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),lr(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Sc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;te.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),ni(`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,wc.spawn)(S.claudePath,r,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",i=>{let o=i.message;i.code==="ENOENT"&&this.cwd&&!(0,Ic.existsSync)(this.cwd)&&(o=`Working directory does not exist: ${this.cwd}`),te.error({sessionId:this.sessionId,error:o,cwd:this.cwd},"spawn error"),b.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:o}),this.handler?.({type:"error",sessionId:this.sessionId,message:o})}),this.buffer="",this.proc.stdout.on("data",i=>{this.buffer+=i.toString();let o=this.buffer.split(`
85
+ `);this.buffer=o.pop();for(let a of o)if(a.trim())try{this.handleRaw(JSON.parse(a))}catch{te.warn({sessionId:this.sessionId,linePreview:a.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",i=>{let o=i.toString().trim();o&&(te.debug({sessionId:this.sessionId,stderr:o},"stderr"),this.lastStderr.push(o),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(i,o)=>{te.info({sessionId:this.sessionId,exitCode:i,signal:o},"process exited");let a=this.interrupted;this.proc=null,lr(this.hookFiles),this.hookFiles=null,this.interrupted=!1,a&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):i&&i!==0&&!this.sawFinalResult&&(te.error({sessionId:this.sessionId,exitCode:i,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:bc({stderrLines:this.lastStderr,exitCode:i})})),this.exitHandler?.(i)})}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,lr(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"),b.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=gg(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&mg(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"&&(b.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){ni("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:bc({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}.`;b.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Ac}${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;ni("Claude finished. Run `claude --continue` to continue on desktop."),b.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 Cc=require("child_process"),Ec=require("fs");var ri=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();M.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new ri;var Tc=require("node:fs"),si=require("node:path"),_g="@vibelet/cli";function bg(t){try{let e=JSON.parse((0,Tc.readFileSync)(t,"utf8"));if(e.name===_g&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function wg(){return"1.0.2"}var _t=wg();var T=M.child({module:"codex"});function Ig(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 Ag(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 Tg=new Set(["aborted","interrupted","cancelled","canceled"]);function xg(t){let e=k(t);return e?e.toLowerCase():null}function kg(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function ii(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function oi(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Rc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Pc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Cg(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=>Rc(l))??i[0],a=i.find(l=>Pc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Eg(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=>Rc(s)),r=e.some(s=>Pc(s));return n&&r}function xc(t){let e=kg(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:oi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:oi(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 Rg(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 kc(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var ln=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,T.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,T.info({spawnCmd:i,args:o},"spawning");b.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Cc.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,Ec.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),T.error({error:u,cwd:e},"spawn error"),b.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{T.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(T.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{T.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&T.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;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:_t},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=kc(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,T.info({threadId:this.threadId},"thread resumed"),b.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??"",T.info({threadId:this.threadId},"thread created"),b.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=kc(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,T.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{T.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,T.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.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 T.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=Ag(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,T.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(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;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
+ `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),T.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}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=ri(n);if(!r)return null;let s=n?wc(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?si(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:_g(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(!Tg(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=xg(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"])},kg(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=ri(s),o=s?wc(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=ri(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;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":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=$(r?.turn),i=Ig(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&&wg.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 E=require("fs/promises"),yi=require("fs"),vi=require("readline"),P=require("path"),Se=require("os");var Cg=new Set(["New session","Resumed session","Untitled session"]),Eg=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Rg(t){return t.replace(/\s+/g," ").trim()}function ur(t){return typeof t!="string"?void 0:Rg(t)||void 0}function Cc(t){let e=ur(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 _t(t){let e=ur(t);return!e||Cg.has(e)||Cc(e)}function Pg(t){for(let e of t.replace(/\r/g,"").split(`
92
- `)){let n=ur(e);if(n&&!Mg(n)&&!Lg(n))return n}}function Mg(t){return Eg.some(e=>t.startsWith(e))}function Lg(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Ng(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 ii(t,e=80){if(typeof t!="string")return;let n=Pg(t);if(!n)return;let r=Ng(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 Ke(t,e){for(let n of t){let r=ur(n);if(!(!r||_t(r)))return r}return ii(e)}var Mc=require("child_process"),bt=require("fs/promises"),Ne=require("path"),oi=require("os"),Lc=require("util");var Og=(0,Lc.promisify)(Mc.execFile),Ec=M.child({module:"process-scanner"}),Rc=1500,Bg="(^|[^[:alnum:]_.-])(claude|codex)([^[:alnum:]_.-]|$)",Dg=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,Hg=15e3,un=null,cn=null;function fr(){un=null}function Fg(t){return t.replace(/^['"]|['"]$/g,"")}function Ug(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Fg)}function qg(t){for(let e=0;e<t.length;e+=1){let n=t[e],r=(0,Ne.basename)(n);if(r==="claude"||r==="codex")return{agent:r,args:t.slice(e+1)};if(/\s/.test(n)){let s=wt(n);if(s)return s}}return null}function wt(t){return qg(Ug(t))}function Nc(t){return Dg.test(t)}function Wg(t,e){let n=wt(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 jg(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function Gg(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function Vg(t,e){let n=wt(e);if(!(!n||n.agent!==t))return t==="claude"?jg(n.args):Gg(n.args)}function dr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function $g(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function zg(t,e){let n=wt(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function Yg(t){let e=[...new Set(t.sessionFiles)].filter(i=>$g(t.agent,i)),n=Wg(t.agent,t.command),r=Vg(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=It(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function Jg(t,e){let n=t,r=e;(dr(e.confidence)>dr(t.confidence)||dr(e.confidence)===dr(t.confidence)&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function Kg(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Jg(s,n):n)}return[...e.values()]}function Xg(t){try{return process.kill(t,0),!0}catch{return!1}}async function pr(t,e){try{let{stdout:n}=await Og(t,e,{maxBuffer:8388608,timeout:Rc});return n}catch(n){let r=String(n);return r.includes("ESRCH")||r.includes("No such process")?Ec.debug({file:t,args:e,error:r},"process scan command skipped \u2014 process exited"):Ec.warn({file:t,args:e,timeoutMs:Rc,error:r},"process scan command failed"),""}}async function Pc(t){if(!t.sessionFilePath)return t;let e=await dn(t.sessionFilePath,t.agent);if(!e)return null;let n=await ai(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function Qg(t){return process.platform==="win32"?"":(await pr("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
- `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Zg(t){if(process.platform==="win32")return[];let n=(await pr("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 em(){return(await pr("pgrep",["-fal",Bg])).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];if(!Nc(s))return null;let i=wt(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function tm(){return(await pr("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"])).split(`
96
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!Nc(s))return null;let i=wt(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function nm(){return process.platform==="win32"?tm():em()}async function rm(){let e=(await nm()).filter(n=>Xg(n.pid));return Promise.all(e.map(async n=>({pid:n.pid,agent:n.agent,command:n.command,cwd:await Qg(n.pid),sessionFiles:await Zg(n.pid)})))}function sm(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function im(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ne.join)((0,oi.homedir)(),".claude","projects",sm(e)),l=(await(0,bt.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,bt.stat)((0,Ne.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Ne.join)(o,c.name),d=It(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ne.join)((0,oi.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,bt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ne.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,bt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await dn(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 om(){let t=await rm(),e=await Promise.all(t.map(async r=>{let s=Yg(r);if(s)return Pc(s);if(zg(r.agent,r.command))return null;let i=await im(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=Kg(e.filter(r=>r!==null));return un={value:n,expiresAt:Date.now()+Hg},n}async function Oc(){return un&&Date.now()<un.expiresAt?un.value:cn||(cn=om().finally(()=>{cn=null}),cn)}var Xe=M.child({module:"inventory"}),am=6e3,lm=1e4,cm={listScannedSessions:gn,scanRunningSessions:Oc,searchSessionContent:Wc},ie=um(),pn=null,hr=0,mr=0,gr=0,li=0,ci=new Set;function um(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function dm(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode})}function fm(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding,approvalMode:t.approvalMode})}function Bc(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(dm).sort(),runningSessions:t.runningSessions.map(fm).sort()})}function pm(){for(let t of ci)try{t()}catch(e){Xe.warn({error:String(e)},"session inventory backfill listener failed")}}function fn(){w.gauge("session.inventory.external_cached_sessions",ie.scannedSessions.length),w.gauge("session.inventory.external_running_sessions",ie.runningSessions.length),w.gauge("session.inventory.backfill_inflight",pn?1:0)}function Fc(t){return ci.add(t),()=>{ci.delete(t)}}function Uc(){return{cachedSessions:ie.scannedSessions.length,runningSessions:ie.runningSessions.length,cacheAgeMs:ie.refreshedAt?Math.max(0,Date.now()-ie.refreshedAt):void 0,backfillInFlight:!!pn,lastBackfillDurationMs:gr||void 0,lastBackfillCompletedAt:mr?new Date(mr).toISOString():void 0,lastBackfillAppliedAt:li?new Date(li).toISOString():void 0}}fn();var At={daemonActive:3,externalRunning:2,idle:1},Dc={high:3,medium:2,low:1};function qc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function hm(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||At[e.runtime.state]-At[t.runtime.state]||qc(t,e)}function gm(t,e){return At[e.state]>At[t.state]?e:At[e.state]<At[t.state]?t:Dc[e.confidence]>Dc[t.confidence]?e:t}function mm(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function ym(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function vm(t,e){return e?t?!(_t(e)&&!_t(t)):!0:!1}function ui(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Sm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...ui()},managed:t.managed,approvalMode:t.approvalMode}}function _m(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,isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function bm(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 wm(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=vm(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=gm(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:ym(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:mm(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function Im(...t){let e=new Map;for(let n of t)wm(e,n);return[...e.values()]}function Am(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&&Xe.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function xm(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 Hc(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=Im(t.sessionRecords.map(Sm),t.scannedSessions,t.runningSessions.map(m=>_m(m,t.scannedAt)),t.activeSessions.map(bm)),c=t.deletedSessionIds?.size?l.filter(m=>!t.deletedSessionIds?.has(m.sessionId)):l,u=Am(c,r,s,i,o),d=u.filter(m=>m.runtime.state!=="idle"||m.managed).sort(hm),f=u.filter(m=>m.runtime.state==="idle"&&!m.managed).sort(qc),p=xm(f,n),g=f.slice(p,p+a),y=p+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}function hn(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;Xe.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||Xe.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function Tm(t=Date.now()){return ie.refreshedAt===0||t-ie.refreshedAt>=lm}async function km(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([hn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),hn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Cm(t,e){if(pn)return;let n=hr,r=w.startTimer("session.inventory.backfill_latency_ms");pn=km(t,e).then(s=>{if(n!==hr)return;let i=Bc(ie);ie=s;let o=Bc(s),a=r();gr=a,mr=Date.now(),fn(),i!==o&&(li=Date.now(),w.increment("session.inventory.backfill_applied"),Xe.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),pm())}).catch(s=>{n===hr&&(gr=r(),mr=Date.now(),fn(),Xe.warn({error:String(s),durationMs:gr},"session inventory external backfill failed"))}).finally(()=>{n===hr&&(pn=null,fn())}),fn()}async function yr(t){let e={...cm,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??am);if(!t.search){let c=w.startTimer("session.inventory.fast_path_latency_ms");Tm()&&Cm(e,n);let u=ie,d=Hc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:u.scannedSessions,runningSessions:u.runningSessions,scannedAt:u.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd);return c(),d}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([hn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),hn("process.running_sessions",()=>e.scanRunningSessions(),[],n),hn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);return Xe.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Hc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l)}var Oe=M.child({module:"scanner"});function Yc(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 Jc=3e4,hi=Yc(Jc),gi=Yc(Jc),di=new Map,fi=new Map,xt=24;function Sr(){hi.clear(),gi.clear()}function Kc(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Tt(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*Xc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
97
- `,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 pi=512*1024,jc=256*1024;async function Qc(t,e){if(e<=pi)return(0,E.readFile)(t,"utf-8");let n=await(0,E.open)(t,"r");try{let r=Buffer.alloc(pi),{bytesRead:s}=await n.read(r,0,pi,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function Em(t,e){if(e<=jc)return(0,E.readFile)(t,"utf-8");let n=await(0,E.open)(t,"r");try{let r=Math.max(0,e-jc),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Gc(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Rm(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function Pm(t){return t?.type==="permission-mode"?Gc(t.permissionMode):Gc(t?.permissionMode)}function Mm(t){if(t?.type==="turn_context")return Rm(t.payload)}async function Zc(t,e,n){let r,s=await Em(t,n);for(let i of s.split(`
98
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?Pm(o):Mm(o);a&&(r=a)}return r}function Si(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 eu(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Si(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function _r(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 Lm=["<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 Nm(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Lm.some(r=>n.startsWith(r)):!1}function br(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=_r(t.message.content);return Nm(t,e)?"":e}function Om(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function tu(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function vr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:ui()}}function It(t,e){let n=(0,P.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 Bm(t,e){let n=await Qc(t,e),r=Xc(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=Ke([u.customTitle,u.summary])),!l){let d=br(u),f=Ke([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||It("claude",t)||(0,P.basename)(t,".jsonl"),cwd:s,title:o??l??Ke([],a),approvalMode:await Zc(t,"claude",e)}:null}async function Dm(t,e){let n=await Qc(t,e),r=Xc(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=Ke([u.payload?.title,u.title])),!l){let d=eu(u),f=d&&!tu(d)?Ke([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||It("codex",t)||(0,P.basename)(t,".jsonl"),cwd:s,title:o??l??Ke([],a),approvalMode:await Zc(t,"codex",e)}:null}async function dn(t,e){let n=await(0,E.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Bm(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Dm(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Vc(t,e){let n=(0,P.join)((0,Se.homedir)(),".claude","projects");try{let r;t?r=[Kc(t)]:r=(await(0,E.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,P.join)(n,l),u=await(0,E.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,P.join)(c,d))}let i=await Tt(s,xt,async l=>{let c=await(0,E.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await Tt(i,xt,async l=>{let c=await dn(l.path,"claude");return c&&e&&e.push(vr(c)),c})).filter(l=>l!==null).map(l=>vr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Oe.warn({error:String(r)},"failed to list claude sessions"),[]}}async function $c(t,e){let n=(0,P.join)((0,Se.homedir)(),".codex","sessions");try{let r=await(0,E.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,P.join)(n,l),u=await(0,E.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,P.join)(c,d),p=await(0,E.readdir)(f).catch(()=>[]);for(let g of p){let h=(0,P.join)(f,g),y=await(0,E.readdir)(h).catch(()=>[]);for(let m of y)m.endsWith(".jsonl")&&s.push((0,P.join)(h,m))}}}let i=await Tt(s,xt,async l=>{let c=await(0,E.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await Tt(i,xt,async l=>{let c=await dn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(vr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>vr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Oe.warn({error:String(r)},"failed to list codex sessions"),[]}}async function gn(t,e,n){let s=`list:${(0,Se.homedir)()}:${t??"all"}:${e??""}`,i=hi.get(s);if(i)return i;let o=di.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Vc(e,n);else if(t==="codex")l=await $c(e,n);else{let[c,u]=await Promise.all([Vc(e,n),$c(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return hi.set(s,l),l})();return di.set(s,a),a.finally(()=>di.delete(s)),a}async function Wc(t,e){let r=`search:${(0,Se.homedir)()}:${t}:${e??"all"}`,s=gi.get(r);if(s)return s;let i=fi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,P.join)((0,Se.homedir)(),".claude","projects");try{let f=await(0,E.readdir)(d,{withFileTypes:!0}),p=[];for(let h of f){if(!h.isDirectory())continue;let y=(0,P.join)(d,h.name),m=await(0,E.readdir)(y).catch(()=>[]);for(let C of m)C.endsWith(".jsonl")&&p.push((0,P.join)(y,C))}let g=await Tt(p,xt,h=>zc(h,l,"claude"));for(let h of g)h&&a.add(h)}catch(f){Oe.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,P.join)((0,Se.homedir)(),".codex","sessions");try{let f=[];async function p(h){let y=await(0,E.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let m of y){let C=(0,P.join)(h,m.name);m.isDirectory()?await p(C):m.name.endsWith(".jsonl")&&f.push(C)}}await p(d);let g=await Tt(f,xt,h=>zc(h,l,"codex"));for(let h of g)h&&a.add(h)}catch(f){Oe.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),gi.set(r,a),a})();return fi.set(r,o),o.finally(()=>fi.delete(r)),o}async function zc(t,e,n){let r=(0,yi.createReadStream)(t,{encoding:"utf-8"}),s=(0,vi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Hm:Fm,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||It(n,t):null}function Hm(t){return t?.type==="user"&&t.message?.role==="user"?br(t):t?.type==="assistant"&&t.message?.role==="assistant"?_r(t.message.content):""}function Fm(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Si(t.payload.content)}let e=eu(t);return e||""}async function mi(t,e){let n=(0,yi.createReadStream)(t,{encoding:"utf-8"}),r=(0,vi.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 nu(t,e){let n=(0,P.join)((0,Se.homedir)(),".claude","projects"),r=e?Kc(e):null,s=await(0,E.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,P.join)(n,o,`${t}.jsonl`);if((await(0,E.stat)(a).catch(()=>null))?.isFile())return a}return null}async function ru(t,e,n){if(e==="claude")return nu(t,n);let r=(0,P.join)((0,Se.homedir)(),".codex","sessions");return su(r,t)}function Um(t){if(t?.type==="user"&&t.message?.role==="user")return Om(t.message.content)?{kind:"toolResult"}:br(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=_r(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return t?.type==="system"&&t.subtype==="stop_hook_summary"?{kind:"stopHook"}:null}function qm(t){if(!t)return{};if(t.kind==="stopHook")return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return{isResponding:!0}}async function ai(t,e){if(e!=="claude")return{};let n=null;try{await mi(t,r=>{let s=Um(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Oe.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return qm(n)}async function _i(t,e,n){let r=await ru(t,e,n);return r?ai(r,e):{}}async function mn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await nu(t,n);i&&await mi(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=br(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=_r(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Oe.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await ru(t,e,n);i&&await mi(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=Si(o.payload.content);l&&(a==="user"&&tu(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Oe.warn({error:String(i)},"failed to read codex session history")}return r}async function su(t,e){try{let n=await(0,E.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,P.join)(t,r.name);if(r.isDirectory()){let i=await su(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Oe.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var kt=require("fs"),au=require("path");var Wm=500,iu=200;function jm(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=iu?e:e.slice(-iu)}function Gm(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 Vm(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 ou(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:jm(t.acceptedClientMessageIds),pendingApproval:Vm(t.pendingApproval)}}function $m(t){if(Array.isArray(t))return{records:t.map(ou),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(ou):[],deletedSessionIds:Gm(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var wr=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()},Wm)}loadFromDisk(){try{let e=(0,kt.readFileSync)(er,"utf-8");return $m(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,kt.mkdirSync)((0,au.dirname)(er),{recursive:!0}),(0,kt.writeFileSync)(er,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Ct=require("path"),lu=require("os");function Ir(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Ct.join)((0,lu.homedir)(),t.slice(2)):t}function zm(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 bi(t,e){let n=Ir(zm(t));if(!n||(0,Ct.isAbsolute)(n))return n;let r=Ir(e??"");return r?(0,Ct.resolve)(r,n):n}var cu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Et=require("fs"),uu=require("path");function Ym(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 Jm(t){try{let e=(0,Et.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Ym):[]}catch{return[]}}function yn(t,e){(0,Et.mkdirSync)((0,uu.dirname)(t),{recursive:!0}),(0,Et.writeFileSync)(t,JSON.stringify(e,null,2)+`
99
- `,"utf8")}var Ar=class{constructor(e=Ql){this.pushSubscriptionsPath=e;this.records=Jm(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)],yn(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,yn(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,yn(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&&yn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],yn(this.pushSubscriptionsPath,this.records)}};var z=M.child({module:"push"}),Km="https://exp.host/--/api/v2/push/send",Xm="https://exp.host/--/api/v2/push/getReceipts",Qm=[0,1e3,3e3],vn=new Ar;function Zm(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 ey(t){return new Promise(e=>{setTimeout(e,t)})}function du(t){return t==="DeviceNotRegistered"}function ty(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 ny(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 ry(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 sy(t,e,n,r){let s=new Map(t);for(let i of Qm){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Xm,{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}=ry(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"),du(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 iy(t){let e=t?.pushStore??vn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??ey;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,...Zm(a)&&a.eventType==="approval_request"?{categoryId:cu.approvalRequestV1}:{}}));try{let u=await n(Km,{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}=ty(d,l),g=ny(d,l);for(let{token:h,ticket:y}of p){let m=y.details?.error;if(z.error({token:h,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),du(m)){let C=e.unregisterToken(h);z.info({token:h,errorCode:m,removed:C},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await sy(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function wi(t,e){vn.register(t,e),z.info({deviceId:t,token:e,total:vn.count()},"push token registered")}function Ii(t,e){let n=vn.unregister(t,e);z.info({deviceId:t,token:e,total:vn.count(),removed:n},"push token unregistered")}var xr=iy();var b=M.child({module:"manager"}),oy="Done.",ay="Approval required",fu=180,kr=200;function Sn(...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>kr&&e.splice(0,e.length-kr));return e}function Tr(t){return t?.length?{acceptedClientMessageIds:Sn(t)}:{}}function fe(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:Sn(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 pu(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&cr(e)}function hu(t,e,n){return{sessionId:t,agent:e,...n}}function ly(t){return t.startsWith(Zs)}function gu(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 Cr=class{constructor(e=xr){this.pushSender=e;this.removeInventoryBackfillListener=Fc(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new wr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.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=S.idleTimeoutMs,r=S.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),this.noteInventoryChanged("session_updated");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),this.noteInventoryChanged("session_updated"))}}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"&&"sessionId"in i&&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"||!pu(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),this.noteInventoryChanged("session_updated");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(ay,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"&&cr(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"),(i.type==="approval.request"||i.type==="session.done"||i.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),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&&pu(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),this.noteInventoryChanged("session_updated")})}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(fe(e)),this.noteInventoryChanged("session_remapped"),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),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!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),this.noteInventoryChanged("session_updated"),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,s){if(e==="codex"&&n instanceof ln&&s&&n.setModel(s),e!=="claude"||!(n instanceof an))return;let i=r??(0,Ai.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,i),i}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=on){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&ly(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"),on;if(r.approvalMode==="autoApprove")return gu(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return on;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=`${Zs}${l.trim()||(0,Ai.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),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.noteInventoryChanged("session_updated"),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=Sn(r?.acceptedClientMessageIds),p=r?.isResponding,g=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=Sn(h.acceptedClientMessageIds,f),g="record";else if(!r){let m=(await gn(n??i)).find(C=>C.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p=m.runtime.isResponding??p,g="scanner")}if(!i&&n&&(i=n,g=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:g,managed:r?.managed??h?.managed,isResponding:p||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(hu(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(hu(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(fe(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=fu?n:`${n.slice(0,Math.max(1,fu-3)).trimEnd()}...`:oy}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(fe(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 gn(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,n.model);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,n.model);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.removeInventoryBackfillListener(),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(){yr({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}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Ir(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,mu.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 c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return b.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(l){b.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;b.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let h={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,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:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,h),this.registerClaudeHookSession(h),this.store.upsert(fe(h)),this.updateGauges(),Sr(),fr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(h,e);return}let u=w.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();b.info({sessionId:d,agent:r,spawnMs:f},"session created"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let p={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,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:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,p),this.registerClaudeHookSession(p),this.store.upsert(fe(p)),this.updateGauges(),Sr(),fr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){b.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}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),this.noteInventoryChanged("session_updated");let f=await mn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let g={type:"session.history",sessionId:r,messages:f,...Tr(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g))}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),g=this.configureDriverBeforeStart(s,p),h=await p.start(c,r,u),y=f();b.info({sessionId:h,agent:s,spawnMs:y},"session resumed"),w.increment("session.resume",{agent:s}),_.emit("session.resume",{sessionId:h,agent:s,cwd:c});let m={sessionId:h,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:g,pendingClaudeHookApprovals:new Map};this.sessions.set(h,m),this.registerClaudeHookSession(m),this.store.upsert(fe(m)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(m,s," (resumed)",e),this.restoreDriverPendingApproval(p,m.pendingApproval);let C=await mn(r,s,c);if(C.length>0||m.pendingApproval){b.info({sessionId:r,historyCount:C.length},"sending history messages");let ae={type:"session.history",sessionId:h,messages:C,...Tr(m.acceptedClientMessageIds),approvalMode:u,pendingApproval:m.pendingApproval};e.readyState===1&&e.send(JSON.stringify(ae))}this.reply(e,n,!0,{sessionId:h})}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>kr&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-kr))}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){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:f.agent,source:f.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:f.agent,source:f.source}),_.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let p=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,p,c?.claudeHookSecret);await p.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(p,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=p,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=Sn(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:p,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(fe(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),_t(c.title)){let f=ii(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(fe(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
91
+ `)}resolveToolContext(e){let n=$(e?.item)??e??null,r=ii(n);if(!r)return null;let s=n?xc(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?oi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),b.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){T.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:Ig(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(!Eg(o)){T.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Cg(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"])},Rg(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"){T.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}T.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(T.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&&T.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||T.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=ii(s),o=s?xc(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=ii(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=k(r?.reason)??k($(r?.turn)?.reason);T.info({threadId:this.threadId,reason:s},"turn interrupted"),b.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":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=$(r?.turn),i=xg(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&&Tg.has(i)){T.info({threadId:this.threadId,status:i},"turn interrupted"),b.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}T.info({threadId:this.threadId,status:i??"completed"},"turn completed"),b.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&&T.debug({method:n},"unhandled notification");break}}};var E=require("fs/promises"),Si=require("fs"),_i=require("readline"),P=require("path"),be=require("os");var Pg=new Set(["New session","Resumed session","Untitled session"]),Mg=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Lg(t){return t.replace(/\s+/g," ").trim()}function ur(t){return typeof t!="string"?void 0:Lg(t)||void 0}function Mc(t){let e=ur(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 bt(t){let e=ur(t);return!e||Pg.has(e)||Mc(e)}function Ng(t){for(let e of t.replace(/\r/g,"").split(`
92
+ `)){let n=ur(e);if(n&&!Og(n)&&!Bg(n))return n}}function Og(t){return Mg.some(e=>t.startsWith(e))}function Bg(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Dg(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 ai(t,e=80){if(typeof t!="string")return;let n=Ng(t);if(!n)return;let r=Dg(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Mc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Ke(t,e){for(let n of t){let r=ur(n);if(!(!r||bt(r)))return r}return ai(e)}var Bc=require("child_process"),wt=require("fs/promises"),Ne=require("path"),li=require("os"),Dc=require("util");var Hg=(0,Dc.promisify)(Bc.execFile),Lc=M.child({module:"process-scanner"}),Nc=1500,Fg="(^|[^[:alnum:]_.-])(claude|codex)([^[:alnum:]_.-]|$)",Ug=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,qg=15e3,un=null,cn=null;function fr(){un=null}function Wg(t){return t.replace(/^['"]|['"]$/g,"")}function jg(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Wg)}function Gg(t){for(let e=0;e<t.length;e+=1){let n=t[e],r=(0,Ne.basename)(n);if(r==="claude"||r==="codex")return{agent:r,args:t.slice(e+1)};if(/\s/.test(n)){let s=It(n);if(s)return s}}return null}function It(t){return Gg(jg(t))}function Hc(t){return Ug.test(t)}function Vg(t,e){let n=It(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 $g(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function zg(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function Yg(t,e){let n=It(e);if(!(!n||n.agent!==t))return t==="claude"?$g(n.args):zg(n.args)}function dr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Jg(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Kg(t,e){let n=It(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function Qg(t){let e=[...new Set(t.sessionFiles)].filter(i=>Jg(t.agent,i)),n=Vg(t.agent,t.command),r=Yg(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=At(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function Xg(t,e){let n=t,r=e;(dr(e.confidence)>dr(t.confidence)||dr(e.confidence)===dr(t.confidence)&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function Zg(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Xg(s,n):n)}return[...e.values()]}function em(t){try{return process.kill(t,0),!0}catch{return!1}}async function pr(t,e){try{let{stdout:n}=await Hg(t,e,{maxBuffer:8388608,timeout:Nc});return n}catch(n){let r=String(n);return r.includes("ESRCH")||r.includes("No such process")?Lc.debug({file:t,args:e,error:r},"process scan command skipped \u2014 process exited"):Lc.warn({file:t,args:e,timeoutMs:Nc,error:r},"process scan command failed"),""}}async function Oc(t){if(!t.sessionFilePath)return t;let e=await dn(t.sessionFilePath,t.agent);if(!e)return null;let n=await ci(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function tm(t){return process.platform==="win32"?"":(await pr("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function nm(t){if(process.platform==="win32")return[];let n=(await pr("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 rm(){return(await pr("pgrep",["-fal",Fg])).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];if(!Hc(s))return null;let i=It(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function sm(){return(await pr("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"])).split(`
96
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!Hc(s))return null;let i=It(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function im(){return process.platform==="win32"?sm():rm()}async function om(){let e=(await im()).filter(n=>em(n.pid));return Promise.all(e.map(async n=>({pid:n.pid,agent:n.agent,command:n.command,cwd:await tm(n.pid),sessionFiles:await nm(n.pid)})))}function am(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function lm(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ne.join)((0,li.homedir)(),".claude","projects",am(e)),l=(await(0,wt.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,wt.stat)((0,Ne.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Ne.join)(o,c.name),d=At(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ne.join)((0,li.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,wt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ne.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,wt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await dn(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 cm(){let t=await om(),e=await Promise.all(t.map(async r=>{let s=Qg(r);if(s)return Oc(s);if(Kg(r.agent,r.command))return null;let i=await lm(r.agent,r.cwd);return i?Oc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=Zg(e.filter(r=>r!==null));return un={value:n,expiresAt:Date.now()+qg},n}async function Fc(){return un&&Date.now()<un.expiresAt?un.value:cn||(cn=cm().finally(()=>{cn=null}),cn)}var Qe=M.child({module:"inventory"}),um=6e3,dm=1e4,fm={listScannedSessions:gn,scanRunningSessions:Fc,searchSessionContent:$c},ie=pm(),pn=null,hr=0,mr=0,gr=0,ui=0,di=new Set;function pm(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function hm(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode})}function gm(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding,approvalMode:t.approvalMode})}function Uc(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(hm).sort(),runningSessions:t.runningSessions.map(gm).sort()})}function mm(){for(let t of di)try{t()}catch(e){Qe.warn({error:String(e)},"session inventory backfill listener failed")}}function fn(){w.gauge("session.inventory.external_cached_sessions",ie.scannedSessions.length),w.gauge("session.inventory.external_running_sessions",ie.runningSessions.length),w.gauge("session.inventory.backfill_inflight",pn?1:0)}function jc(t){return di.add(t),()=>{di.delete(t)}}function Gc(){return{cachedSessions:ie.scannedSessions.length,runningSessions:ie.runningSessions.length,cacheAgeMs:ie.refreshedAt?Math.max(0,Date.now()-ie.refreshedAt):void 0,backfillInFlight:!!pn,lastBackfillDurationMs:gr||void 0,lastBackfillCompletedAt:mr?new Date(mr).toISOString():void 0,lastBackfillAppliedAt:ui?new Date(ui).toISOString():void 0}}fn();var Tt={daemonActive:3,externalRunning:2,idle:1},qc={high:3,medium:2,low:1};function Vc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function ym(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||Tt[e.runtime.state]-Tt[t.runtime.state]||Vc(t,e)}function vm(t,e){return Tt[e.state]>Tt[t.state]?e:Tt[e.state]<Tt[t.state]?t:qc[e.confidence]>qc[t.confidence]?e:t}function Sm(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function _m(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function bm(t,e){return e?t?!(bt(e)&&!bt(t)):!0:!1}function fi(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function wm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...fi()},managed:t.managed,approvalMode:t.approvalMode}}function Im(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,isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function Am(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 Tm(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=bm(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=vm(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:_m(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:Sm(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function xm(...t){let e=new Map;for(let n of t)Tm(e,n);return[...e.values()]}function km(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&&Qe.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function Cm(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 Wc(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=xm(t.sessionRecords.map(wm),t.scannedSessions,t.runningSessions.map(m=>Im(m,t.scannedAt)),t.activeSessions.map(Am)),c=t.deletedSessionIds?.size?l.filter(m=>!t.deletedSessionIds?.has(m.sessionId)):l,u=km(c,r,s,i,o),d=u.filter(m=>m.runtime.state!=="idle"||m.managed).sort(ym),f=u.filter(m=>m.runtime.state==="idle"&&!m.managed).sort(Vc),p=Cm(f,n),g=f.slice(p,p+a),y=p+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}function hn(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;Qe.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||Qe.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function Em(t=Date.now()){return ie.refreshedAt===0||t-ie.refreshedAt>=dm}async function Rm(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([hn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),hn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Pm(t,e){if(pn)return;let n=hr,r=w.startTimer("session.inventory.backfill_latency_ms");pn=Rm(t,e).then(s=>{if(n!==hr)return;let i=Uc(ie);ie=s;let o=Uc(s),a=r();gr=a,mr=Date.now(),fn(),i!==o&&(ui=Date.now(),w.increment("session.inventory.backfill_applied"),Qe.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),mm())}).catch(s=>{n===hr&&(gr=r(),mr=Date.now(),fn(),Qe.warn({error:String(s),durationMs:gr},"session inventory external backfill failed"))}).finally(()=>{n===hr&&(pn=null,fn())}),fn()}async function yr(t){let e={...fm,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??um);if(!t.search){let c=w.startTimer("session.inventory.fast_path_latency_ms");Em()&&Pm(e,n);let u=ie,d=Wc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:u.scannedSessions,runningSessions:u.runningSessions,scannedAt:u.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd);return c(),d}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([hn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),hn("process.running_sessions",()=>e.scanRunningSessions(),[],n),hn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);return Qe.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Wc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l)}var Oe=M.child({module:"scanner"});function Xc(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 Zc=3e4,mi=Xc(Zc),yi=Xc(Zc),pi=new Map,hi=new Map,xt=24;function Sr(){mi.clear(),yi.clear()}function eu(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function kt(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*tu(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
97
+ `,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 gi=512*1024,zc=256*1024;async function nu(t,e){if(e<=gi)return(0,E.readFile)(t,"utf-8");let n=await(0,E.open)(t,"r");try{let r=Buffer.alloc(gi),{bytesRead:s}=await n.read(r,0,gi,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function Mm(t,e){if(e<=zc)return(0,E.readFile)(t,"utf-8");let n=await(0,E.open)(t,"r");try{let r=Math.max(0,e-zc),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Yc(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Lm(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function Nm(t){return t?.type==="permission-mode"?Yc(t.permissionMode):Yc(t?.permissionMode)}function Om(t){if(t?.type==="turn_context")return Lm(t.payload)}async function ru(t,e,n){let r,s=await Mm(t,n);for(let i of s.split(`
98
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?Nm(o):Om(o);a&&(r=a)}return r}function bi(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 su(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?bi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function _r(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 Bm=["<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 Dm(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Bm.some(r=>n.startsWith(r)):!1}function br(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=_r(t.message.content);return Dm(t,e)?"":e}function Hm(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function iu(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function vr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:fi()}}function At(t,e){let n=(0,P.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 Fm(t,e){let n=await nu(t,e),r=tu(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=Ke([u.customTitle,u.summary])),!l){let d=br(u),f=Ke([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||At("claude",t)||(0,P.basename)(t,".jsonl"),cwd:s,title:o??l??Ke([],a),approvalMode:await ru(t,"claude",e)}:null}async function Um(t,e){let n=await nu(t,e),r=tu(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=Ke([u.payload?.title,u.title])),!l){let d=su(u),f=d&&!iu(d)?Ke([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||At("codex",t)||(0,P.basename)(t,".jsonl"),cwd:s,title:o??l??Ke([],a),approvalMode:await ru(t,"codex",e)}:null}async function dn(t,e){let n=await(0,E.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Fm(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Um(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Jc(t,e){let n=(0,P.join)((0,be.homedir)(),".claude","projects");try{let r;t?r=[eu(t)]:r=(await(0,E.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,P.join)(n,l),u=await(0,E.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,P.join)(c,d))}let i=await kt(s,xt,async l=>{let c=await(0,E.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await kt(i,xt,async l=>{let c=await dn(l.path,"claude");return c&&e&&e.push(vr(c)),c})).filter(l=>l!==null).map(l=>vr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Oe.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Kc(t,e){let n=(0,P.join)((0,be.homedir)(),".codex","sessions");try{let r=await(0,E.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,P.join)(n,l),u=await(0,E.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,P.join)(c,d),p=await(0,E.readdir)(f).catch(()=>[]);for(let g of p){let h=(0,P.join)(f,g),y=await(0,E.readdir)(h).catch(()=>[]);for(let m of y)m.endsWith(".jsonl")&&s.push((0,P.join)(h,m))}}}let i=await kt(s,xt,async l=>{let c=await(0,E.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await kt(i,xt,async l=>{let c=await dn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(vr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>vr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Oe.warn({error:String(r)},"failed to list codex sessions"),[]}}async function gn(t,e,n){let s=`list:${(0,be.homedir)()}:${t??"all"}:${e??""}`,i=mi.get(s);if(i)return i;let o=pi.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Jc(e,n);else if(t==="codex")l=await Kc(e,n);else{let[c,u]=await Promise.all([Jc(e,n),Kc(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return mi.set(s,l),l})();return pi.set(s,a),a.finally(()=>pi.delete(s)),a}async function $c(t,e){let r=`search:${(0,be.homedir)()}:${t}:${e??"all"}`,s=yi.get(r);if(s)return s;let i=hi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,P.join)((0,be.homedir)(),".claude","projects");try{let f=await(0,E.readdir)(d,{withFileTypes:!0}),p=[];for(let h of f){if(!h.isDirectory())continue;let y=(0,P.join)(d,h.name),m=await(0,E.readdir)(y).catch(()=>[]);for(let C of m)C.endsWith(".jsonl")&&p.push((0,P.join)(y,C))}let g=await kt(p,xt,h=>Qc(h,l,"claude"));for(let h of g)h&&a.add(h)}catch(f){Oe.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,P.join)((0,be.homedir)(),".codex","sessions");try{let f=[];async function p(h){let y=await(0,E.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let m of y){let C=(0,P.join)(h,m.name);m.isDirectory()?await p(C):m.name.endsWith(".jsonl")&&f.push(C)}}await p(d);let g=await kt(f,xt,h=>Qc(h,l,"codex"));for(let h of g)h&&a.add(h)}catch(f){Oe.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),yi.set(r,a),a})();return hi.set(r,o),o.finally(()=>hi.delete(r)),o}async function Qc(t,e,n){let r=(0,Si.createReadStream)(t,{encoding:"utf-8"}),s=(0,_i.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?qm:Wm,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||At(n,t):null}function qm(t){return t?.type==="user"&&t.message?.role==="user"?br(t):t?.type==="assistant"&&t.message?.role==="assistant"?_r(t.message.content):""}function Wm(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return bi(t.payload.content)}let e=su(t);return e||""}async function vi(t,e){let n=(0,Si.createReadStream)(t,{encoding:"utf-8"}),r=(0,_i.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 ou(t,e){let n=(0,P.join)((0,be.homedir)(),".claude","projects"),r=e?eu(e):null,s=await(0,E.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,P.join)(n,o,`${t}.jsonl`);if((await(0,E.stat)(a).catch(()=>null))?.isFile())return a}return null}async function au(t,e,n){if(e==="claude")return ou(t,n);let r=(0,P.join)((0,be.homedir)(),".codex","sessions");return lu(r,t)}function jm(t){if(t?.type==="user"&&t.message?.role==="user")return Hm(t.message.content)?{kind:"toolResult"}:br(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=_r(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return t?.type==="system"&&t.subtype==="stop_hook_summary"?{kind:"stopHook"}:null}function Gm(t){if(!t)return{};if(t.kind==="stopHook")return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return{isResponding:!0}}async function ci(t,e){if(e!=="claude")return{};let n=null;try{await vi(t,r=>{let s=jm(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Oe.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Gm(n)}async function wi(t,e,n){let r=await au(t,e,n);return r?ci(r,e):{}}async function mn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await ou(t,n);i&&await vi(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=br(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=_r(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Oe.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await au(t,e,n);i&&await vi(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=bi(o.payload.content);l&&(a==="user"&&iu(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Oe.warn({error:String(i)},"failed to read codex session history")}return r}async function lu(t,e){try{let n=await(0,E.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,P.join)(t,r.name);if(r.isDirectory()){let i=await lu(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Oe.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Ct=require("fs"),du=require("path");var Vm=500,cu=200;function $m(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=cu?e:e.slice(-cu)}function zm(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 Ym(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 uu(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:$m(t.acceptedClientMessageIds),pendingApproval:Ym(t.pendingApproval)}}function Jm(t){if(Array.isArray(t))return{records:t.map(uu),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(uu):[],deletedSessionIds:zm(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var wr=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()},Vm)}loadFromDisk(){try{let e=(0,Ct.readFileSync)(er,"utf-8");return Jm(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,Ct.mkdirSync)((0,du.dirname)(er),{recursive:!0}),(0,Ct.writeFileSync)(er,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Et=require("path"),fu=require("os");function Ir(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Et.join)((0,fu.homedir)(),t.slice(2)):t}function Km(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 Ii(t,e){let n=Ir(Km(t));if(!n||(0,Et.isAbsolute)(n))return n;let r=Ir(e??"");return r?(0,Et.resolve)(r,n):n}var pu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Rt=require("fs"),hu=require("path");function Qm(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 Xm(t){try{let e=(0,Rt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Qm):[]}catch{return[]}}function yn(t,e){(0,Rt.mkdirSync)((0,hu.dirname)(t),{recursive:!0}),(0,Rt.writeFileSync)(t,JSON.stringify(e,null,2)+`
99
+ `,"utf8")}var Ar=class{constructor(e=nc){this.pushSubscriptionsPath=e;this.records=Xm(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)],yn(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,yn(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,yn(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&&yn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],yn(this.pushSubscriptionsPath,this.records)}};var z=M.child({module:"push"}),Zm="https://exp.host/--/api/v2/push/send",ey="https://exp.host/--/api/v2/push/getReceipts",ty=[0,1e3,3e3],vn=new Ar;function ny(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 ry(t){return new Promise(e=>{setTimeout(e,t)})}function gu(t){return t==="DeviceNotRegistered"}function sy(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 iy(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 oy(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 ay(t,e,n,r){let s=new Map(t);for(let i of ty){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(ey,{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}=oy(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"),gu(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 ly(t){let e=t?.pushStore??vn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??ry;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,...ny(a)&&a.eventType==="approval_request"?{categoryId:pu.approvalRequestV1}:{}}));try{let u=await n(Zm,{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}=sy(d,l),g=iy(d,l);for(let{token:h,ticket:y}of p){let m=y.details?.error;if(z.error({token:h,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),gu(m)){let C=e.unregisterToken(h);z.info({token:h,errorCode:m,removed:C},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await ay(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function Ai(t,e){vn.register(t,e),z.info({deviceId:t,token:e,total:vn.count()},"push token registered")}function Ti(t,e){let n=vn.unregister(t,e);z.info({deviceId:t,token:e,total:vn.count(),removed:n},"push token unregistered")}var Tr=ly();var _=M.child({module:"manager"}),cy="Done.",uy="Approval required",mu=180,kr=200;function Sn(...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>kr&&e.splice(0,e.length-kr));return e}function xr(t){return t?.length?{acceptedClientMessageIds:Sn(t)}:{}}function he(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:Sn(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 yu(t){t.managed||(t.managed=!0)}function vu(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&cr(e)}function Su(t,e,n){return{sessionId:t,agent:e,...n}}function dy(t){return t.startsWith(ti)}function _u(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 Cr=class{constructor(e=Tr){this.pushSender=e;this.removeInventoryBackfillListener=jc(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new wr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.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=S.idleTimeoutMs,r=S.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&&(_.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;_.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),w.increment("driver.stall_timeout",{agent:o.agent}),b.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),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(_.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),w.increment("driver.idle_timeout",{agent:o.agent}),b.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),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){_.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(_.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,(o.type==="session.interrupted"||!vu(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){b.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}_.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender(uy,this.buildPushBody(`${e.title||e.sessionId}: ${o.description||o.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:o.requestId,eventType:"approval_request"})}n==="claude"&&o.type==="approval.request"&&cr(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:_.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){_.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}_.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),b.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o}),w.increment("driver.exit",{agent:n,abnormal:o&&o!==0?"true":"false"});let a=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&vu(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",a||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){_.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;_.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(he(e)),this.noteInventoryChanged("session_remapped"),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),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!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){_.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,_.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){_.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),this.noteInventoryChanged("session_updated"),_.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,s){if(e==="codex"&&n instanceof ln&&s&&n.setModel(s),e!=="claude"||!(n instanceof an))return;let i=r??(0,xi.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,i),i}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=on){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&dy(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):(_.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 _.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),on;if(r.approvalMode==="autoApprove")return _u(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return on;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=`${ti}${l.trim()||(0,xi.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},b.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),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=Sn(r?.acceptedClientMessageIds),p=r?.isResponding,g=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=Sn(h.acceptedClientMessageIds,f),g="record";else if(!r){let m=(await gn(n??i)).find(C=>C.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p=m.runtime.isResponding??p,g="scanner")}if(!i&&n&&(i=n,g=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:g,managed:r?.managed??h?.managed,isResponding:p||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(Su(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(Su(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(he(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=mu?n:`${n.slice(0,Math.max(1,mu-3)).trimEnd()}...`:cy}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(he(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 gn(e,n)}async handle(e,n){switch(_.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,n.model);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,n.model);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.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){_.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(){yr({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}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Ir(s),_.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,bu.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 c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return _.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,i);_.info("continue mode: no previous sessions found, creating new")}catch(l){_.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;_.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),b.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let h={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,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:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,h),this.registerClaudeHookSession(h),this.store.upsert(he(h)),this.updateGauges(),Sr(),fr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(h,e);return}let u=w.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();_.info({sessionId:d,agent:r,spawnMs:f},"session created"),w.increment("session.create",{agent:r}),b.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let p={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,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:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,p),this.registerClaudeHookSession(p),this.store.upsert(he(p)),this.updateGauges(),Sr(),fr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){_.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}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),this.noteInventoryChanged("session_updated");let f=await mn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let g={type:"session.history",sessionId:r,messages:f,...xr(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g))}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),g=this.configureDriverBeforeStart(s,p),h=await p.start(c,r,u),y=f();_.info({sessionId:h,agent:s,spawnMs:y},"session resumed"),w.increment("session.resume",{agent:s}),b.emit("session.resume",{sessionId:h,agent:s,cwd:c});let m={sessionId:h,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:g,pendingClaudeHookApprovals:new Map};this.sessions.set(h,m),this.registerClaudeHookSession(m),this.store.upsert(he(m)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(m,s," (resumed)",e),this.restoreDriverPendingApproval(p,m.pendingApproval);let C=await mn(r,s,c);if(C.length>0||m.pendingApproval){_.info({sessionId:r,historyCount:C.length},"sending history messages");let ce={type:"session.history",sessionId:h,messages:C,...xr(m.acceptedClientMessageIds),approvalMode:u,pendingApproval:m.pendingApproval};e.readyState===1&&e.send(JSON.stringify(ce))}this.reply(e,n,!0,{sessionId:h})}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>kr&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-kr))}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){_.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}_.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:f.agent,source:f.source}),b.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let p=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,p,c?.claudeHookSecret);await p.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(p,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=p,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=Sn(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:p,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(he(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(_.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),b.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),yu(c),bt(c.title)){let f=ai(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(he(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
100
100
  `):"",d=u?s?`${s}
101
101
 
102
- ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),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 yr({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}}c={...c,inventoryVersion:this.inventoryVersion};let u;if(o&&!l.has(o)){let f=a??c.sessions.find(h=>h.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let g=await this.resolveReconnectSession(o,f,p);if(g){let h=await mn(o,g.agent,p?.cwd??g.cwd),y=p?{}:await _i(o,g.agent,g.cwd);u={sessionId:o,agent:g.agent,messages:h,...Tr(p?.acceptedClientMessageIds??g.acceptedClientMessageIds),isResponding:p?.isResponding??y.isResponding??g.isResponding,partialReplyText:p?this.currentPartialReplyText(p):y.partialReplyText,approvalMode:p?.approvalMode??g.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,inventoryVersion:c.inventoryVersion,...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),this.noteInventoryChanged("session_updated"),l.resolve(gu(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&cr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),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.noteInventoryChanged("session_updated"),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(fe(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}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),this.noteInventoryChanged("session_updated"),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?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),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}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(fe(i)),this.noteInventoryChanged("session_updated"),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}if(_.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;b.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}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.noteInventoryChanged("session_updated"),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(),Sr(),fr(),this.noteInventoryChanged("session_deleted"),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 mn(r,s,o),c=i?{}:await _i(r,s,o),u=i?.isResponding??c.isResponding,d=i?this.currentPartialReplyText(i):c.partialReplyText;b.info({sessionId:r,historyCount:l.length,isResponding:u,approvalMode:i?.approvalMode??a?.approvalMode},"sending history");let f={type:"session.history",sessionId:r,messages:l,...Tr(i?.acceptedClientMessageIds??a?.acceptedClientMessageIds),isResponding:u,partialReplyText:d,approvalMode:i?.approvalMode??a?.approvalMode,pendingApproval:i?.pendingApproval??a?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(f)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await yr({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,inventoryVersion:this.inventoryVersion})}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new an;case"codex":return new ln;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 xi(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 yu=require("child_process");function cy(t,e){return(0,yu.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function uy(t){let e=t.split(`
103
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function vu(t,e=cy){let n;try{n=uy(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 Rt=require("fs"),Ti=require("os"),_u=require("crypto"),bu=require("path");function wu(t){return(0,_u.randomBytes)(t).toString("base64url")}function dy(){return`d_${wu(12)}`}function fy(){return(0,Ti.hostname)()}function py(){let t=(0,Ti.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function hy(t){return{daemonId:dy(),daemonSecret:wu(32),displayName:fy(),canonicalHost:py(),port:t,createdAt:new Date().toISOString()}}function Su(t,e){(0,Rt.mkdirSync)((0,bu.dirname)(e),{recursive:!0}),(0,Rt.writeFileSync)(e,JSON.stringify(t,null,2)+`
104
- `,"utf8")}function Iu(t,e=Kl){try{let r=(0,Rt.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,Su(i,e)),i}}catch{}let n=hy(t);return Su(n,e),n}var Pt=require("crypto"),Mt=require("fs"),xu=require("path");function ki(t){return(0,Pt.randomBytes)(t).toString("base64url")}function Ci(t){return(0,Pt.createHash)("sha256").update(t).digest("hex")}function Au(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Pt.timingSafeEqual)(n,r)}function gy(t){try{let e=(0,Mt.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 _n(t,e){(0,Mt.mkdirSync)((0,xu.dirname)(t),{recursive:!0}),(0,Mt.writeFileSync)(t,JSON.stringify(e,null,2)+`
105
- `,"utf8")}var Er=class{constructor(e=Xl){this.pairingsPath=e;this.records=gy(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_${ki(8)}`,r=ki(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=ki(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),_n(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 Au(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),_n(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ci(e),s=this.records.find(i=>!i.revokedAt&&Au(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),_n(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(),_n(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),_n(this.pairingsPath,this.records)}};function Lt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function my(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Tu(t,e){return my(t)??e}function Ei(t,e){return!!(t&&e&&t===e)}function ku(t,e,n,r=!0){return t?Ei(t,e)?!0:!!n(t,r):!1}var Ru=require("child_process");function Ri(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Pu(t){if(!Ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function yy(t){if(!Ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function vy(t){if(!Ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Rr(t){return!!t&&!yy(t)&&!vy(t)}function _e(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Cu(t,e){return(t??[]).map(n=>_e(n)).filter(n=>!!n).filter(n=>Rr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Mu(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Sy(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||Rr(s.address)&&(Pu(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function Eu(t){let e=JSON.parse(t),n=_e(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>_e(o)).filter(o=>!!o).filter(o=>Pu(o)&&Rr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Lu(t=Ru.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 Eu(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Eu(n)}catch{return{fallbackHosts:[]}}}function Nu(t){let e=_e(t.canonicalHost)||"localhost",n=Cu(t.fallbackHosts,e);if(!t.relayUrl)return{canonicalHost:e,fallbackHosts:n,port:t.port};try{let r=new URL(t.relayUrl),s=_e(r.hostname);if(!s)throw new Error("invalid relay hostname");let i=r.port?Number(r.port):r.protocol==="https:"?443:80;return{canonicalHost:s,fallbackHosts:Cu([e,...n],s),port:Number.isFinite(i)&&i>0?Math.floor(i):t.port}}catch{return{canonicalHost:e,fallbackHosts:n,port:t.port}}}function Ou(t){let e=_e(t.canonicalHost),n=_e(t.configuredCanonicalHost)||_e(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Sy(t.interfaces)].map(s=>_e(s)).filter(s=>!!s).filter(s=>Rr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Bu(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 j=M.child({module:"daemon"}),bn=M.child({module:"ws"});function _y(){try{let t=JSON.parse(require("fs").readFileSync(Zl,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var U=Iu(S.port),J=new Cr((t,e,n)=>xr(t,e,{daemonId:U.daemonId,canonicalHost:wn().canonicalHost,...n??{}})),be=new Er,Mr=new Set,Be=new WeakMap,Du=!1,qu=Date.now(),Nt=null,Pr=null,by=1e3;function wy(){let t=Lu();return Ou({canonicalHost:U.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Mu(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Uu.networkInterfaces)()})}function wn(){let t=Date.now();if(Pr&&Pr.expiresAt>t)return Pr.value;let e=wy(),n=Nu({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:U.port,relayUrl:S.relayUrl});return Pr={value:n,expiresAt:t+by},n}function Iy(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),e}async function Ay(t){let e=JSON.stringify(Iy(t));await(0,ne.mkdir)(ve,{recursive:!0}),await Li.default.toFile(zs,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Li.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});yt(`
102
+ ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),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 yr({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(f){_.warn({error:String(f)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}c={...c,inventoryVersion:this.inventoryVersion};let u;if(o&&!l.has(o)){let f=a??c.sessions.find(h=>h.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let g=await this.resolveReconnectSession(o,f,p);if(g){let h=await mn(o,g.agent,p?.cwd??g.cwd),y=p?{}:await wi(o,g.agent,g.cwd);u={sessionId:o,agent:g.agent,messages:h,...xr(p?.acceptedClientMessageIds??g.acceptedClientMessageIds),isResponding:p?.isResponding??y.isResponding??g.isResponding,partialReplyText:p?this.currentPartialReplyText(p):y.partialReplyText,approvalMode:p?.approvalMode??g.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,inventoryVersion:c.inventoryVersion,...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,b.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(_u(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&cr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,b.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),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(b.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.noteInventoryChanged("session_updated"),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(he(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),_.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}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),this.noteInventoryChanged("session_updated"),_.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?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),_.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):_.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(he(i)),this.noteInventoryChanged("session_updated"),_.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}if(b.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;_.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}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}_.info({sessionId:r,agent:s.agent},"stopping session"),b.emit("session.stop",{sessionId:r,agent:s.agent}),yu(s),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.isResponding=!1,s.currentReplyText="",s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(_.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)),b.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Sr(),fr(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r),o=i?.active?i:void 0;if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let a=o?.cwd??i?.cwd??this.store.find(r)?.cwd??"",l=this.store.find(r),c=await mn(r,s,a),u=o?{}:await wi(r,s,a),d=o?.isResponding??u.isResponding,f=o?this.currentPartialReplyText(o):u.partialReplyText;_.info({sessionId:r,historyCount:c.length,isResponding:d,approvalMode:i?.approvalMode??l?.approvalMode},"sending history");let p={type:"session.history",sessionId:r,messages:c,...xr(i?.acceptedClientMessageIds??l?.acceptedClientMessageIds),isResponding:d,partialReplyText:f,approvalMode:i?.approvalMode??l?.approvalMode,pendingApproval:i?.pendingApproval??l?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(p)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await yr({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,inventoryVersion:this.inventoryVersion})}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new an;case"codex":return new ln;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){_.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"&&_.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 ki(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 wu=require("child_process");function fy(t,e){return(0,wu.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function py(t){let e=t.split(`
103
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Iu(t,e=fy){let n;try{n=py(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 Pt=require("fs"),Ci=require("os"),Tu=require("crypto"),xu=require("path");function ku(t){return(0,Tu.randomBytes)(t).toString("base64url")}function hy(){return`d_${ku(12)}`}function gy(){return(0,Ci.hostname)()}function my(){let t=(0,Ci.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function yy(t){return{daemonId:hy(),daemonSecret:ku(32),displayName:gy(),canonicalHost:my(),port:t,createdAt:new Date().toISOString()}}function Au(t,e){(0,Pt.mkdirSync)((0,xu.dirname)(e),{recursive:!0}),(0,Pt.writeFileSync)(e,JSON.stringify(t,null,2)+`
104
+ `,"utf8")}function Cu(t,e=ec){try{let r=(0,Pt.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,Au(i,e)),i}}catch{}let n=yy(t);return Au(n,e),n}var Mt=require("crypto"),Lt=require("fs"),Ru=require("path");function Ei(t){return(0,Mt.randomBytes)(t).toString("base64url")}function Ri(t){return(0,Mt.createHash)("sha256").update(t).digest("hex")}function Eu(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Mt.timingSafeEqual)(n,r)}function vy(t){try{let e=(0,Lt.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 _n(t,e){(0,Lt.mkdirSync)((0,Ru.dirname)(t),{recursive:!0}),(0,Lt.writeFileSync)(t,JSON.stringify(e,null,2)+`
105
+ `,"utf8")}var Er=class{constructor(e=tc){this.pairingsPath=e;this.records=vy(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${Ei(8)}`,s=Ei(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=Ei(32),i={deviceId:e,deviceName:n,tokenHash:Ri(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),_n(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=Ri(n);return Eu(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),_n(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ri(e),s=this.records.find(i=>!i.revokedAt&&Eu(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),_n(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(),_n(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),_n(this.pairingsPath,this.records)}};function Xe(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Sy(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Pi(t,e){return Sy(t)??e}function Rr(t,e){return!!(t&&e&&t===e)}function Mi(t,e,n,r=!0){return t?Rr(t,e)?!0:!!n(t,r):!1}var Lu=require("child_process");function Pr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Li(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function _y(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function by(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function wy(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function Mr(t){return!!t&&!_y(t)&&!by(t)}function oe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Ni(t){return oe(t.replace(/^https?:\/\//,""))??t}function Iy(t,e){return(t??[]).map(n=>oe(n)).filter(n=>!!n).filter(n=>Mr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Ay(t){let e=Ni(t);return Li(e)||e.endsWith(".ts.net")}function Ty(t){let e=Ni(t);return wy(e)||e.endsWith(".local")}function xy(t){return Ni(t).endsWith(".trycloudflare.com")}function Pu(t,e){return Ay(t)?"tailscale":Ty(t)?"local_network":e?"configured_host":"fallback"}function Nu(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}`;e.has(s)||(e.add(s),n.push(r))}return n}function ky(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function Cy(t){try{let e=new URL(t),n=oe(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=xy(n);return{kind:"relay",host:n,port:s,source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function Ey(t,e,n){let r=oe(t)||"localhost",s=Iy(e,r);return Nu([{kind:"direct",host:r,port:n,source:Pu(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:Pu(i,!1),stability:"stable"}))])}function Ou(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Ry(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||Mr(s.address)&&(Li(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function Mu(t){let e=JSON.parse(t),n=oe(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>oe(o)).filter(o=>!!o).filter(o=>Li(o)&&Mr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Bu(t=Lu.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 Mu(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Mu(n)}catch{return{fallbackHosts:[]}}}function Du(t){let e=Ey(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?Cy(t.relayUrl):null,r=Nu([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:oe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:ky(r),port:s.port,connections:r}}function Hu(t){let e=oe(t.canonicalHost),n=oe(t.configuredCanonicalHost)||oe(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Ry(t.interfaces)].map(s=>oe(s)).filter(s=>!!s).filter(s=>Mr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Fu(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 j=M.child({module:"daemon"}),bn=M.child({module:"ws"});function Py(){try{let t=JSON.parse(require("fs").readFileSync(rc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var D=Cu(S.port),J=new Cr((t,e,n)=>Tr(t,e,{daemonId:D.daemonId,canonicalHost:wn().canonicalHost,...n??{}})),le=new Er,Nr=new Set,Be=new WeakMap,Uu=!1,Gu=Date.now(),Nt=null,Lr=null,My=1e3;function Ly(){let t=Bu();return Hu({canonicalHost:D.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Ou(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,ju.networkInterfaces)()})}function wn(){let t=Date.now();if(Lr&&Lr.expiresAt>t)return Lr.value;let e=Ly(),n=Du({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:D.port,relayUrl:S.relayUrl});return Lr={value:n,expiresAt:t+My},n}function Ny(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability])),e}async function Oy(t){let e=JSON.stringify(Ny(t));await(0,ne.mkdir)(_e,{recursive:!0}),await Di.default.toFile(Js,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Di.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});vt(`
106
106
  Scan this QR code with Vibelet app:
107
107
 
108
108
  ${n}
109
- `),yt(`If Vibelet app can't scan the terminal QR, open this PNG instead:
110
- ${zs}
111
- `)}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 O(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function xy(t){let e=(0,In.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 Wu(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function Ty(){let t=be.openWindow(Wu()),e=wn();return{type:"vibelet-pair",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function ky(t,e){let n=bi(t,e),r=await(0,ne.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,ne.stat)((0,In.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var An=(0,Hu.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=wn(),i={status:"ok",version:St,daemonId:U.daemonId,displayName:U.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-qu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:be.pairedCount(),wsClients:oe.clients.size,drivers:J.getDriverCounts(),sessionInventory:Uc(),metrics:w.snapshot()};S.relayUrl&&(i.relayUrl=S.relayUrl);let o=_y();o&&(i.latestVersion=o),O(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Lt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}O(e,200,Ty());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Lt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}be.reset(),O(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Lt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}O(e,200,{status:"stopping"}),setTimeout(()=>Qe("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!Lt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}try{let s=await Pi(t),i=t.headers[sn],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),O(e,200,{ok:!0})}catch(s){O(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!Lt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}try{let s=await Pi(t),i=t.headers[sn],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);O(e,200,a)}catch(s){O(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await Pi(t);if(s.daemonId!==U.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){O(e,400,{error:"invalid_pair_request"});return}if(!be.consumeWindow(s.pairNonce)){O(e,401,{error:"pair_window_expired"});return}let o=be.issuePairToken(s.deviceId,s.deviceName),a=wn();O(e,200,{daemonId:U.daemonId,displayName:U.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,deviceId:s.deviceId,pairToken:o})}catch(s){O(e,400,{error:String(s)})}return}let r=Tu(t.headers.authorization,n.searchParams.get("token"));if(!ku(r,S.legacyToken,(s,i)=>be.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){O(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,ne.mkdir)($s,{recursive:!0});let u=`${Date.now()}_${(0,Fu.randomBytes)(8).toString("hex")}${o}`,d=(0,In.join)($s,u);await(0,ne.writeFile)(d,Buffer.concat(l)),j.info({filePath:d,size:c},"file uploaded"),O(e,200,{path:d})}catch(u){j.error({error:String(u)},"upload failed"),O(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=bi(s,i);if(!(await(0,ne.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=xy(o),c=await(0,ne.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${St}`)}),oe=new ts.default({server:An});An.on("connection",t=>{Mr.add(t),t.on("close",()=>{Mr.delete(t)})});oe.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Ei(r,S.legacyToken))Be.set(t,{authMode:"query_token"}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=be.validateAnyPairToken(r);if(s)Be.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}}bn.info({clients:oe.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",oe.clients.size),_.emit("ws.connect",{clients:oe.clients.size,authMode:Be.get(t)?.authMode??"pending",deviceId:Be.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Bu(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(!Be.has(t)){if(o.action==="auth.hello"&&o.daemonId===U.daemonId&&be.validatePairToken(o.deviceId,o.pairToken)){Be.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:U.daemonId,displayName:U.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"?j.error:a.level==="warn"?j.warn:j.info).call(j,{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 ky(o.path,o.cwd);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=Be.get(t);xi(i,{deviceId:a?.deviceId,registerToken:wi,unregisterToken:Ii,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Be.get(t);xi(i,{deviceId:a?.deviceId,registerToken:wi,unregisterToken:Ii,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){bn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{bn.info({clients:oe.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",oe.clients.size),_.emit("ws.disconnect",{clients:oe.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{bn.error({error:s.message},"websocket error")})});function Mi(){for(let t of Mr)try{t.destroy()}catch{}Mr.clear()}function ju(){let t=uc({auditPath:mt,stdoutLogPath:tr,stderrLogPath:nr,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&j.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 Cy(){Nt||(Nt=setInterval(ju,S.storageHousekeepingIntervalMs),Nt.unref())}function Ey(){Nt&&(clearInterval(Nt),Nt=null)}function Qe(t,e=0){if(!Du){Du=!0,j.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-qu)/1e3)}),w.stopPeriodicLog(),Ey(),J.shutdown();for(let n of oe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}oe.close(n=>{n&&j.error({error:String(n)},"websocket close error")}),An.close(n=>{if(n){j.error({error:String(n)},"http close error"),Mi(),process.exit(1);return}Mi(),process.exit(e)}),setTimeout(()=>{j.error("force exiting after shutdown timeout"),Mi(),process.exit(e||1)},3e3).unref()}}oe.on("error",t=>{bn.error({error:t.message},"wss error")});An.on("error",t=>{if(t.code==="EADDRINUSE"){let e=vu(S.port).filter(n=>n.pid!==process.pid);j.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else j.error({error:String(t)},"server error");Qe(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>Qe("SIGINT"));process.once("SIGTERM",()=>Qe("SIGTERM"));process.once("SIGHUP",()=>Qe("SIGHUP"));process.once("SIGTTIN",()=>Qe("SIGTTIN"));process.once("SIGTSTP",()=>Qe("SIGTSTP"));process.on("uncaughtException",t=>{j.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{j.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});An.listen(S.port,async()=>{ju(),_.emit("daemon.start",{port:S.port}),w.startPeriodicLog(),Cy();let t=wn();j.info({port:S.port,pairingPort:t.port,daemonId:U.daemonId,displayName:U.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=be.openWindow(Wu()),n={type:"vibelet-pair",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,pairNonce:e.pairNonce,expiresAt:e.expiresAt};yt(`
109
+ `),vt(`If Vibelet app can't scan the terminal QR, open this PNG instead:
110
+ ${Js}
111
+ `)}async function Oi(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 By(t){let e=(0,In.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 Vu(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function Dy(t,e){if(Xe(t.socket.remoteAddress))return!0;let n=Pi(t.headers.authorization,e.searchParams.get("token"));return Mi(n,S.legacyToken,(r,s)=>le.validateAnyPairToken(r,s),!1)}function Hy(){let t=le.openWindow(Vu(),S.pairReusable),e=wn();return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Fy(t,e){let n=Ii(t,e),r=await(0,ne.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,ne.stat)((0,In.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var An=(0,qu.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=wn(),i=Py(),o={status:"ok",version:_t,...i?{latestVersion:i}:{}};if(!Dy(t,n)){N(e,200,o);return}let a={...o,status:"ok",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Gu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:le.pairedCount(),wsClients:ae.clients.size,drivers:J.getDriverCounts(),sessionInventory:Gc(),metrics:w.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),N(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Xe(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,Hy());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Xe(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(!Xe(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(!Xe(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Oi(t),i=t.headers[sn],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(!Xe(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Oi(t),i=t.headers[sn],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 Oi(t);if(s.daemonId!==D.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=wn();N(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=Pi(t.headers.authorization,n.searchParams.get("token"));if(!Mi(r,S.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,ne.mkdir)(Ys,{recursive:!0});let u=`${Date.now()}_${(0,Wu.randomBytes)(8).toString("hex")}${o}`,d=(0,In.join)(Ys,u);await(0,ne.writeFile)(d,Buffer.concat(l)),j.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){j.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=Ii(s,i);if(!(await(0,ne.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=By(o),c=await(0,ne.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${_t}`)}),ae=new rs.default({server:An});An.on("connection",t=>{Nr.add(t),t.on("close",()=>{Nr.delete(t)})});ae.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Rr(r,S.legacyToken))Be.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)Be.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}}bn.info({clients:ae.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",ae.clients.size),b.emit("ws.connect",{clients:ae.clients.size,authMode:Be.get(t)?.authMode??"pending",deviceId:Be.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Fu(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(!Be.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Rr(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===D.daemonId&&le.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===D.daemonId){let l=le.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){Be.set(t,{authMode:"auth_hello",deviceId:a.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:D.daemonId,displayName:D.displayName}}));return}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)b.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?j.error:a.level==="warn"?j.warn:j.info).call(j,{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 Fy(o.path,o.cwd);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=Be.get(t);ki(i,{deviceId:a?.deviceId,registerToken:Ai,unregisterToken:Ti,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Be.get(t);ki(i,{deviceId:a?.deviceId,registerToken:Ai,unregisterToken:Ti,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){bn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{bn.info({clients:ae.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",ae.clients.size),b.emit("ws.disconnect",{clients:ae.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{bn.error({error:s.message},"websocket error")})});function Bi(){for(let t of Nr)try{t.destroy()}catch{}Nr.clear()}function $u(){let t=hc({auditPath:yt,stdoutLogPath:tr,stderrLogPath:nr,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&j.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 Uy(){Nt||(Nt=setInterval($u,S.storageHousekeepingIntervalMs),Nt.unref())}function qy(){Nt&&(clearInterval(Nt),Nt=null)}function Ze(t,e=0){if(!Uu){Uu=!0,j.info({reason:t,exitCode:e},"shutting down"),b.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Gu)/1e3)}),w.stopPeriodicLog(),qy(),J.shutdown();for(let n of ae.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ae.close(n=>{n&&j.error({error:String(n)},"websocket close error")}),An.close(n=>{if(n){j.error({error:String(n)},"http close error"),Bi(),process.exit(1);return}Bi(),process.exit(e)}),setTimeout(()=>{j.error("force exiting after shutdown timeout"),Bi(),process.exit(e||1)},3e3).unref()}}ae.on("error",t=>{bn.error({error:t.message},"wss error")});An.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Iu(S.port).filter(n=>n.pid!==process.pid);j.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else j.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=>{j.error({error:String(t),stack:t.stack},"uncaughtException"),b.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{j.error({reason:String(t)},"unhandledRejection"),b.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});An.listen(S.port,async()=>{$u(),b.emit("daemon.start",{port:S.port}),w.startPeriodicLog(),Uy();let t=wn();j.info({port:S.port,pairingPort:t.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=le.openWindow(Vu(),S.pairReusable),n={type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};vt(`
112
112
  \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
113
- \u2551 Vibelet Daemon v${St} \u2551
113
+ \u2551 Vibelet Daemon v${_t} \u2551
114
114
  \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
115
115
  \u2551 Port: ${String(n.port).padEnd(28)}\u2551
116
- \u2551 ID: ${U.daemonId.slice(0,28).padEnd(28)}\u2551
116
+ \u2551 ID: ${D.daemonId.slice(0,28).padEnd(28)}\u2551
117
117
  \u2551 Host: ${n.canonicalHost.slice(0,28).padEnd(28)}\u2551
118
118
  \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
119
119
 
@@ -123,4 +123,4 @@ Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
123
123
 
124
124
  Claude: ${S.claudePath}
125
125
  Codex: ${S.codexPath}
126
- `);try{await Ay(n)}catch{}});
126
+ `);try{await Oy(n)}catch{}});