vibelet 1.2.0 → 1.2.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 Uf=Object.create;var No=Object.defineProperty;var Wf=Object.getOwnPropertyDescriptor;var qf=Object.getOwnPropertyNames;var Gf=Object.getPrototypeOf,jf=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $f=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qf(e))!jf.call(t,r)&&r!==n&&No(t,r,{get:()=>e[r],enumerable:!(s=Wf(e,r))||s.enumerable});return t};var dt=(t,e,n)=>(n=t!=null?Uf(Gf(t)):{},$f(e||!t||!t.__esModule?No(n,"default",{value:t,enumerable:!0}):n,t));var ve=v((hb,Bo)=>{"use strict";var Oo=["nodebuffer","arraybuffer","fragments"],Do=typeof Blob<"u";Do&&Oo.push("blob");Bo.exports={BINARY_TYPES:Oo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Do,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qt=v((gb,jn)=>{"use strict";var{EMPTY_BUFFER:zf}=ve(),mr=Buffer[Symbol.species];function Vf(t,e){if(t.length===0)return zf;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),s=0;for(let r=0;r<t.length;r++){let i=t[r];n.set(i,s),s+=i.length}return s<e?new mr(n.buffer,n.byteOffset,s):n}function Fo(t,e,n,s,r){for(let i=0;i<r;i++)n[s+i]=t[i]^e[i&3]}function Ho(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Qf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yr(t){if(yr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new mr(t):ArrayBuffer.isView(t)?e=new mr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yr.readOnly=!1),e}jn.exports={concat:Vf,mask:Fo,toArrayBuffer:Qf,toBuffer:yr,unmask:Ho};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");jn.exports.mask=function(e,n,s,r,i){i<48?Fo(e,n,s,r,i):t.mask(e,n,s,r,i)},jn.exports.unmask=function(e,n){e.length<32?Ho(e,n):t.unmask(e,n)}}catch{}});var qo=v((mb,Wo)=>{"use strict";var Uo=Symbol("kDone"),vr=Symbol("kRun"),Sr=class{constructor(e){this[Uo]=()=>{this.pending--,this[vr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[vr]()}[vr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Uo])}}};Wo.exports=Sr});var Jt=v((yb,zo)=>{"use strict";var Yt=require("zlib"),Go=Qt(),Yf=qo(),{kStatusCode:jo}=ve(),Jf=Buffer[Symbol.species],Kf=Buffer.from([0,0,255,255]),zn=Symbol("permessage-deflate"),Se=Symbol("total-length"),ft=Symbol("callback"),ke=Symbol("buffers"),pt=Symbol("error"),$n,_r=class{constructor(e,n,s){if(this._maxPayload=s|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,!$n){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$n=new Yf(r)}}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[ft];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,s=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(s.server_no_context_takeover=!0),n.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(s.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?s.client_max_window_bits=n.clientMaxWindowBits:(s.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}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(s=>{let r=n[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);n[s]=r})}),e}decompress(e,n,s){$n.add(r=>{this._decompress(e,n,(i,o)=>{r(),s(i,o)})})}compress(e,n,s){$n.add(r=>{this._compress(e,n,(i,o)=>{r(),s(i,o)})})}_decompress(e,n,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Yt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Yt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[zn]=this,this._inflate[Se]=0,this._inflate[ke]=[],this._inflate.on("error",Zf),this._inflate.on("data",$o)}this._inflate[ft]=s,this._inflate.write(e),n&&this._inflate.write(Kf),this._inflate.flush(()=>{let i=this._inflate[pt];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=Go.concat(this._inflate[ke],this._inflate[Se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Se]=0,this._inflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,n,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Yt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Yt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[ke]=[],this._deflate.on("data",Xf)}this._deflate[ft]=s,this._deflate.write(e),this._deflate.flush(Yt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Go.concat(this._deflate[ke],this._deflate[Se]);n&&(i=new Jf(i.buffer,i.byteOffset,i.length-4)),this._deflate[ft]=null,this._deflate[Se]=0,this._deflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};zo.exports=_r;function Xf(t){this[ke].push(t),this[Se]+=t.length}function $o(t){if(this[Se]+=t.length,this[zn]._maxPayload<1||this[Se]<=this[zn]._maxPayload){this[ke].push(t);return}this[pt]=new RangeError("Max payload size exceeded"),this[pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pt][jo]=1009,this.removeListener("data",$o),this.reset()}function Zf(t){if(this[zn]._inflate=null,this[pt]){this[ft](this[pt]);return}t[jo]=1007,this[ft](t)}});var ht=v((vb,Vn)=>{"use strict";var{isUtf8:Vo}=require("buffer"),{hasBlob:ep}=ve(),tp=[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 np(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function br(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 sp(t){return ep&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Vn.exports={isBlob:sp,isValidStatusCode:np,isValidUTF8:br,tokenChars:tp};if(Vo)Vn.exports.isValidUTF8=function(t){return t.length<24?br(t):Vo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Vn.exports.isValidUTF8=function(e){return e.length<32?br(e):t(e)}}catch{}});var Cr=v((Sb,ea)=>{"use strict";var{Writable:rp}=require("stream"),Qo=Jt(),{BINARY_TYPES:ip,EMPTY_BUFFER:Yo,kStatusCode:op,kWebSocket:ap}=ve(),{concat:wr,toArrayBuffer:lp,unmask:cp}=Qt(),{isValidStatusCode:up,isValidUTF8:Jo}=ht(),Qn=Buffer[Symbol.species],ne=0,Ko=1,Xo=2,Zo=3,Ir=4,Ar=5,Yn=6,Tr=class extends rp{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ip[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ap]=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=ne}_write(e,n,s){if(this._opcode===8&&this._state==ne)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Qn(s.buffer,s.byteOffset+e,s.length-e),new Qn(s.buffer,s.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=n.length-e;e>=s.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new Qn(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ne:this.getInfo(e);break;case Ko:this.getPayloadLength16(e);break;case Xo:this.getPayloadLength64(e);break;case Zo:this.getMask();break;case Ir:this.getData(e);break;case Ar:case Yn: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 r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(n[0]&64)===64;if(s&&!this._extensions[Qo.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=Ko:this._payloadLength===127?this._state=Xo: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),s=n.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*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=Zo:this._state=Ir}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ir}getData(e){let n=Yo;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&&cp(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Ar,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Qo.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return n(r);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===ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ne;return}let n=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=wr(s,n):this._binaryType==="arraybuffer"?r=lp(wr(s,n)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit("message",r,!0),this._state=ne,this.startLoop(e)}))}else{let r=wr(s,n);if(!this._skipUTF8Validation&&!Jo(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ar||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit("message",r,!1),this._state=ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Yo),this.end();else{let s=e.readUInt16BE(0);if(!up(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let r=new Qn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Jo(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ne,this.startLoop(n)}))}createError(e,n,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[op]=r,o}};ea.exports=Tr});var Rr=v((bb,sa)=>{"use strict";var{Duplex:_b}=require("stream"),{randomFillSync:dp}=require("crypto"),ta=Jt(),{EMPTY_BUFFER:fp,kWebSocket:pp,NOOP:hp}=ve(),{isBlob:gt,isValidStatusCode:gp}=ht(),{mask:na,toBuffer:qe}=Qt(),se=Symbol("kByteLength"),mp=Buffer.alloc(4),Jn=8*1024,Ge,mt=Jn,ce=0,yp=1,vp=2,kr=class t{constructor(e,n,s){this._extensions=n||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ce,this.onerror=hp,this[pp]=void 0}static frame(e,n){let s,r=!1,i=2,o=!1;n.mask&&(s=n.maskBuffer||mp,n.generateMask?n.generateMask(s):(mt===Jn&&(Ge===void 0&&(Ge=Buffer.alloc(Jn)),dp(Ge,0,Jn),mt=0),s[0]=Ge[mt++],s[1]=Ge[mt++],s[2]=Ge[mt++],s[3]=Ge[mt++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[se]!==void 0?a=n[se]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(r?a+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(a,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[i-4]=s[0],u[i-3]=s[1],u[i-2]=s[2],u[i-1]=s[3],o?[u,e]:r?(na(e,s,u,i,a),[u]):(na(e,s,e,0,a),[u,e])):[u,e]}close(e,n,s,r){let i;if(e===void 0)i=fp;else{if(typeof e!="number"||!gp(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={[se]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ce?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(t.frame(i,o),r)}ping(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):gt(e)?(r=e.size,i=!1):(e=qe(e),r=e.length,i=qe.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):gt(e)?(r=e.size,i=!1):(e=qe(e),r=e.length,i=qe.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,n,s){let r=this._extensions[ta.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):gt(e)?(a=e.size,l=!1):(e=qe(e),a=e.length,l=qe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[se]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==ce?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,n,s,r){this._bufferedBytes+=s[se],this._state=vp,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(xr,this,a,r);return}this._bufferedBytes-=s[se];let o=qe(i);n?this.dispatch(o,n,s,r):(this._state=ce,this.sendFrame(t.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(Sp,this,i,r)})}dispatch(e,n,s,r){if(!n){this.sendFrame(t.frame(e,s),r);return}let i=this._extensions[ta.extensionName];this._bufferedBytes+=s[se],this._state=yp,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");xr(this,l,r);return}this._bufferedBytes-=s[se],this._state=ce,s.readOnly=!1,this.sendFrame(t.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===ce&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][se],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][se],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)}};sa.exports=kr;function xr(t,e,n){typeof n=="function"&&n(e);for(let s=0;s<t._queue.length;s++){let r=t._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function Sp(t,e,n){xr(t,e,n),t.onerror(e)}});var fa=v((wb,da)=>{"use strict";var{kForOnEventAttribute:Kt,kListener:Er}=ve(),ra=Symbol("kCode"),ia=Symbol("kData"),oa=Symbol("kError"),aa=Symbol("kMessage"),la=Symbol("kReason"),yt=Symbol("kTarget"),ca=Symbol("kType"),ua=Symbol("kWasClean"),_e=class{constructor(e){this[yt]=null,this[ca]=e}get target(){return this[yt]}get type(){return this[ca]}};Object.defineProperty(_e.prototype,"target",{enumerable:!0});Object.defineProperty(_e.prototype,"type",{enumerable:!0});var je=class extends _e{constructor(e,n={}){super(e),this[ra]=n.code===void 0?0:n.code,this[la]=n.reason===void 0?"":n.reason,this[ua]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ra]}get reason(){return this[la]}get wasClean(){return this[ua]}};Object.defineProperty(je.prototype,"code",{enumerable:!0});Object.defineProperty(je.prototype,"reason",{enumerable:!0});Object.defineProperty(je.prototype,"wasClean",{enumerable:!0});var vt=class extends _e{constructor(e,n={}){super(e),this[oa]=n.error===void 0?null:n.error,this[aa]=n.message===void 0?"":n.message}get error(){return this[oa]}get message(){return this[aa]}};Object.defineProperty(vt.prototype,"error",{enumerable:!0});Object.defineProperty(vt.prototype,"message",{enumerable:!0});var Xt=class extends _e{constructor(e,n={}){super(e),this[ia]=n.data===void 0?null:n.data}get data(){return this[ia]}};Object.defineProperty(Xt.prototype,"data",{enumerable:!0});var _p={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Kt]&&r[Er]===e&&!r[Kt])return;let s;if(t==="message")s=function(i,o){let a=new Xt("message",{data:o?i:i.toString()});a[yt]=this,Kn(e,this,a)};else if(t==="close")s=function(i,o){let a=new je("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[yt]=this,Kn(e,this,a)};else if(t==="error")s=function(i){let o=new vt("error",{error:i,message:i.message});o[yt]=this,Kn(e,this,o)};else if(t==="open")s=function(){let i=new _e("open");i[yt]=this,Kn(e,this,i)};else return;s[Kt]=!!n[Kt],s[Er]=e,n.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Er]===e&&!n[Kt]){this.removeListener(t,n);break}}};da.exports={CloseEvent:je,ErrorEvent:vt,Event:_e,EventTarget:_p,MessageEvent:Xt};function Kn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Pr=v((Ib,pa)=>{"use strict";var{tokenChars:Zt}=ht();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function bp(t){let e=Object.create(null),n=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,u=-1,c=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),o===void 0)if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(d!==0&&(u===32||u===9))c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);u===44?(he(e,h,n),n=Object.create(null)):o=h,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(u===32||u===9)c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d),he(n,t.slice(l,c),!0),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),l=c=-1}else if(u===61&&l!==-1&&c===-1)a=t.slice(l,d),l=c=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Zt[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:s||(s=!0),r=!1}else if(i)if(Zt[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)i=!0;else if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(l!==-1&&(u===32||u===9))c===-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);s&&(h=h.replace(/\\/g,""),s=!1),he(n,a,h),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=d);let f=t.slice(l,c);return o===void 0?he(e,f,n):(a===void 0?he(n,f,!0):s?he(n,a,f.replace(/\\/g,"")):he(n,a,f),he(e,o,n)),e}function wp(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}pa.exports={format:wp,parse:bp}});var ts=v((Cb,Ta)=>{"use strict";var Ip=require("events"),Ap=require("https"),Tp=require("http"),ma=require("net"),Cp=require("tls"),{randomBytes:kp,createHash:xp}=require("crypto"),{Duplex:Ab,Readable:Tb}=require("stream"),{URL:Mr}=require("url"),xe=Jt(),Rp=Cr(),Ep=Rr(),{isBlob:Pp}=ht(),{BINARY_TYPES:ha,CLOSE_TIMEOUT:Mp,EMPTY_BUFFER:Xn,GUID:Lp,kForOnEventAttribute:Lr,kListener:Np,kStatusCode:Op,kWebSocket:q,NOOP:ya}=ve(),{EventTarget:{addEventListener:Dp,removeEventListener:Bp}}=fa(),{format:Fp,parse:Hp}=Pr(),{toBuffer:Up}=Qt(),va=Symbol("kAborted"),Nr=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],Wp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,N=class t extends Ip{constructor(e,n,s){super(),this._binaryType=ha[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(s=n,n=[]):n=[n]),Sa(this,e,n,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ha.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,s){let r=new Rp({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Ep(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[q]=this,i[q]=this,e[q]=this,r.on("conclude",jp),r.on("drain",$p),r.on("error",zp),r.on("message",Vp),r.on("ping",Qp),r.on("pong",Yp),i.onerror=Jp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",wa),e.on("data",es),e.on("end",Ia),e.on("error",Aa),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[xe.extensionName]&&this._extensions[xe.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){Z(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,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ba(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Xn,n,s)}pong(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Xn,n,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(s=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(r.compress=!1),this._sender.send(e||Xn,r,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(N.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(N.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(N.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Lr])return e[Np];return null},set(e){for(let n of this.listeners(t))if(n[Lr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Lr]:!0})}})});N.prototype.addEventListener=Dp;N.prototype.removeEventListener=Bp;Ta.exports=N;function Sa(t,e,n,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Mp,protocolVersion:Nr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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=r.autoPong,t._closeTimeout=r.closeTimeout,!Nr.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Nr.join(", ")})`);let i;if(e instanceof Mr)i=e;else try{i=new Mr(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 m=new SyntaxError(l);if(t._redirects===0)throw m;Zn(t,m);return}let u=o?443:80,c=kp(16).toString("base64"),d=o?Ap.request:Tp.request,f=new Set,h;if(r.createConnection=r.createConnection||(o?Gp:qp),r.defaultPort=r.defaultPort||u,r.port=i.port||u,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new xe(r.perMessageDeflate!==!0?r.perMessageDeflate:{},!1,r.maxPayload),r.headers["Sec-WebSocket-Extensions"]=Fp({[xe.extensionName]:h.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Wp.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let m=r.path.split(":");r.socketPath=m[0],r.path=m[1]}let g;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?r.socketPath:i.host;let m=s&&s.headers;if(s={...s,headers:{}},m)for(let[p,y]of Object.entries(m))s.headers[p.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,m||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),g=t._req=d(r),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(r);r.timeout&&g.on("timeout",()=>{Z(t,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[va]||(g=t._req=null,Zn(t,m))}),g.on("response",m=>{let p=m.headers.location,y=m.statusCode;if(p&&r.followRedirects&&y>=300&&y<400){if(++t._redirects>r.maxRedirects){Z(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new Mr(p,e)}catch{let T=new SyntaxError(`Invalid URL: ${p}`);Zn(t,T);return}Sa(t,C,n,s)}else t.emit("unexpected-response",g,m)||Z(t,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,p,y)=>{if(t.emit("upgrade",m),t.readyState!==N.CONNECTING)return;g=t._req=null;let C=m.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Z(t,p,"Invalid Upgrade header");return}let A=xp("sha1").update(c+Lp).digest("base64");if(m.headers["sec-websocket-accept"]!==A){Z(t,p,"Invalid Sec-WebSocket-Accept header");return}let T=m.headers["sec-websocket-protocol"],I;if(T!==void 0?f.size?f.has(T)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":f.size&&(I="Server sent no subprotocol"),I){Z(t,p,I);return}T&&(t._protocol=T);let D=m.headers["sec-websocket-extensions"];if(D!==void 0){if(!h){Z(t,p,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=Hp(D)}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(x);if(X.length!==1||X[0]!==xe.extensionName){Z(t,p,"Server indicated an extension that was not requested");return}try{h.accept(x[xe.extensionName])}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=h}t.setSocket(p,y,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(g,t):g.end()}function Zn(t,e){t._readyState=N.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qp(t){return t.path=t.socketPath,ma.connect(t)}function Gp(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ma.isIP(t.host)?"":t.host),Cp.connect(t)}function Z(t,e,n){t._readyState=N.CLOSING;let s=new Error(n);Error.captureStackTrace(s,Z),e.setHeader?(e[va]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zn,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Or(t,e,n){if(e){let s=Pp(e)?e.size:Up(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(n){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,s)}}function jp(t,e){let n=this[q];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[q]!==void 0&&(n._socket.removeListener("data",es),process.nextTick(_a,n._socket),t===1005?n.close():n.close(t,e))}function $p(){let t=this[q];t.isPaused||t._socket.resume()}function zp(t){let e=this[q];e._socket[q]!==void 0&&(e._socket.removeListener("data",es),process.nextTick(_a,e._socket),e.close(t[Op])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ga(){this[q].emitClose()}function Vp(t,e){this[q].emit("message",t,e)}function Qp(t){let e=this[q];e._autoPong&&e.pong(t,!this._isServer,ya),e.emit("ping",t)}function Yp(t){this[q].emit("pong",t)}function _a(t){t.resume()}function Jp(t){let e=this[q];e.readyState!==N.CLOSED&&(e.readyState===N.OPEN&&(e._readyState=N.CLOSING,ba(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ba(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function wa(){let t=this[q];if(this.removeListener("close",wa),this.removeListener("data",es),this.removeListener("end",Ia),t._readyState=N.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[q]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ga),t._receiver.on("finish",ga))}function es(t){this[q]._receiver.write(t)||this.pause()}function Ia(){let t=this[q];t._readyState=N.CLOSING,t._receiver.end(),this.end()}function Aa(){let t=this[q];this.removeListener("error",Aa),this.on("error",ya),t&&(t._readyState=N.CLOSING,this.destroy())}});var Ra=v((xb,xa)=>{"use strict";var kb=ts(),{Duplex:Kp}=require("stream");function Ca(t){t.emit("close")}function Xp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ka(t){this.removeListener("error",ka),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Zp(t,e){let n=!0,s=new Kp({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(n=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(t.readyState===t.CLOSED){i(r),process.nextTick(Ca,s);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(r),process.nextTick(Ca,s)}),n&&t.terminate()},s._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(r,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(r,i,o)});return}t.send(r,o)},s.on("end",Xp),s.on("error",ka),s}xa.exports=Zp});var Pa=v((Rb,Ea)=>{"use strict";var{tokenChars:eh}=ht();function th(t){let e=new Set,n=-1,s=-1,r=0;for(r;r<t.length;r++){let o=t.charCodeAt(r);if(s===-1&&eh[o]===1)n===-1&&(n=r);else if(r!==0&&(o===32||o===9))s===-1&&n!==-1&&(s=r);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Ea.exports={parse:th}});var Fa=v((Pb,Ba)=>{"use strict";var nh=require("events"),ns=require("http"),{Duplex:Eb}=require("stream"),{createHash:sh}=require("crypto"),Ma=Pr(),$e=Jt(),rh=Pa(),ih=ts(),{CLOSE_TIMEOUT:oh,GUID:ah,kWebSocket:lh}=ve(),ch=/^[+/0-9A-Za-z]{22}==$/,La=0,Na=1,Da=2,Dr=class extends nh{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:oh,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ih,...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=ns.createServer((s,r)=>{let i=ns.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=uh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=La}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===Da){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(en,this);return}if(e&&this.once("close",e),this._state!==Na)if(this._state=Na,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(en,this):process.nextTick(en,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{en(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,s,r){n.on("error",Oa);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ze(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ze(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!ch.test(i)){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){tn(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=rh.parse(l)}catch{ze(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let c=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&c!==void 0){let f=new $e(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=Ma.parse(c);h[$e.extensionName]&&(f.accept(h[$e.extensionName]),d[$e.extensionName]=f)}catch{ze(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,(h,g,m,p)=>{if(!h)return tn(n,g||401,m,p);this.completeUpgrade(d,i,u,e,n,s,r)});return}if(!this.options.verifyClient(f))return tn(n,401)}this.completeUpgrade(d,i,u,e,n,s,r)}completeUpgrade(e,n,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[lh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>La)return tn(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${sh("sha1").update(n+ah).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[$e.extensionName]){let d=e[$e.extensionName].params,f=Ma.format({[$e.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${f}`),c._extensions=e}this.emit("headers",u,r),i.write(u.concat(`\r
1
+ "use strict";var Wf=Object.create;var Oo=Object.defineProperty;var qf=Object.getOwnPropertyDescriptor;var Gf=Object.getOwnPropertyNames;var jf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var zf=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gf(e))!$f.call(t,r)&&r!==n&&Oo(t,r,{get:()=>e[r],enumerable:!(s=qf(e,r))||s.enumerable});return t};var dt=(t,e,n)=>(n=t!=null?Wf(jf(t)):{},zf(e||!t||!t.__esModule?Oo(n,"default",{value:t,enumerable:!0}):n,t));var ve=v((mb,Fo)=>{"use strict";var Do=["nodebuffer","arraybuffer","fragments"],Bo=typeof Blob<"u";Bo&&Do.push("blob");Fo.exports={BINARY_TYPES:Do,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Bo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qt=v((yb,jn)=>{"use strict";var{EMPTY_BUFFER:Vf}=ve(),mr=Buffer[Symbol.species];function Qf(t,e){if(t.length===0)return Vf;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),s=0;for(let r=0;r<t.length;r++){let i=t[r];n.set(i,s),s+=i.length}return s<e?new mr(n.buffer,n.byteOffset,s):n}function Ho(t,e,n,s,r){for(let i=0;i<r;i++)n[s+i]=t[i]^e[i&3]}function Uo(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Yf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function yr(t){if(yr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new mr(t):ArrayBuffer.isView(t)?e=new mr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),yr.readOnly=!1),e}jn.exports={concat:Qf,mask:Ho,toArrayBuffer:Yf,toBuffer:yr,unmask:Uo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");jn.exports.mask=function(e,n,s,r,i){i<48?Ho(e,n,s,r,i):t.mask(e,n,s,r,i)},jn.exports.unmask=function(e,n){e.length<32?Uo(e,n):t.unmask(e,n)}}catch{}});var Go=v((vb,qo)=>{"use strict";var Wo=Symbol("kDone"),vr=Symbol("kRun"),Sr=class{constructor(e){this[Wo]=()=>{this.pending--,this[vr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[vr]()}[vr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Wo])}}};qo.exports=Sr});var Jt=v((Sb,Vo)=>{"use strict";var Yt=require("zlib"),jo=Qt(),Jf=Go(),{kStatusCode:$o}=ve(),Kf=Buffer[Symbol.species],Xf=Buffer.from([0,0,255,255]),zn=Symbol("permessage-deflate"),Se=Symbol("total-length"),ft=Symbol("callback"),ke=Symbol("buffers"),pt=Symbol("error"),$n,_r=class{constructor(e,n,s){if(this._maxPayload=s|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,!$n){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$n=new Jf(r)}}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[ft];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,s=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(s.server_no_context_takeover=!0),n.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(s.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?s.client_max_window_bits=n.clientMaxWindowBits:(s.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}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(s=>{let r=n[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);n[s]=r})}),e}decompress(e,n,s){$n.add(r=>{this._decompress(e,n,(i,o)=>{r(),s(i,o)})})}compress(e,n,s){$n.add(r=>{this._compress(e,n,(i,o)=>{r(),s(i,o)})})}_decompress(e,n,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Yt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Yt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[zn]=this,this._inflate[Se]=0,this._inflate[ke]=[],this._inflate.on("error",ep),this._inflate.on("data",zo)}this._inflate[ft]=s,this._inflate.write(e),n&&this._inflate.write(Xf),this._inflate.flush(()=>{let i=this._inflate[pt];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=jo.concat(this._inflate[ke],this._inflate[Se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Se]=0,this._inflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,n,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Yt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Yt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[ke]=[],this._deflate.on("data",Zf)}this._deflate[ft]=s,this._deflate.write(e),this._deflate.flush(Yt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=jo.concat(this._deflate[ke],this._deflate[Se]);n&&(i=new Kf(i.buffer,i.byteOffset,i.length-4)),this._deflate[ft]=null,this._deflate[Se]=0,this._deflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Vo.exports=_r;function Zf(t){this[ke].push(t),this[Se]+=t.length}function zo(t){if(this[Se]+=t.length,this[zn]._maxPayload<1||this[Se]<=this[zn]._maxPayload){this[ke].push(t);return}this[pt]=new RangeError("Max payload size exceeded"),this[pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pt][$o]=1009,this.removeListener("data",zo),this.reset()}function ep(t){if(this[zn]._inflate=null,this[pt]){this[ft](this[pt]);return}t[$o]=1007,this[ft](t)}});var ht=v((_b,Vn)=>{"use strict";var{isUtf8:Qo}=require("buffer"),{hasBlob:tp}=ve(),np=[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 sp(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function br(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 rp(t){return tp&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Vn.exports={isBlob:rp,isValidStatusCode:sp,isValidUTF8:br,tokenChars:np};if(Qo)Vn.exports.isValidUTF8=function(t){return t.length<24?br(t):Qo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Vn.exports.isValidUTF8=function(e){return e.length<32?br(e):t(e)}}catch{}});var Cr=v((bb,ta)=>{"use strict";var{Writable:ip}=require("stream"),Yo=Jt(),{BINARY_TYPES:op,EMPTY_BUFFER:Jo,kStatusCode:ap,kWebSocket:lp}=ve(),{concat:wr,toArrayBuffer:cp,unmask:up}=Qt(),{isValidStatusCode:dp,isValidUTF8:Ko}=ht(),Qn=Buffer[Symbol.species],ne=0,Xo=1,Zo=2,ea=3,Ir=4,Ar=5,Yn=6,Tr=class extends ip{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||op[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[lp]=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=ne}_write(e,n,s){if(this._opcode===8&&this._state==ne)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Qn(s.buffer,s.byteOffset+e,s.length-e),new Qn(s.buffer,s.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=n.length-e;e>=s.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new Qn(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ne:this.getInfo(e);break;case Xo:this.getPayloadLength16(e);break;case Zo:this.getPayloadLength64(e);break;case ea:this.getMask();break;case Ir:this.getData(e);break;case Ar:case Yn: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 r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(n[0]&64)===64;if(s&&!this._extensions[Yo.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=Xo:this._payloadLength===127?this._state=Zo: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),s=n.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*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=ea:this._state=Ir}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ir}getData(e){let n=Jo;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&&up(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Ar,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Yo.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return n(r);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===ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ne;return}let n=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=wr(s,n):this._binaryType==="arraybuffer"?r=cp(wr(s,n)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit("message",r,!0),this._state=ne,this.startLoop(e)}))}else{let r=wr(s,n);if(!this._skipUTF8Validation&&!Ko(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ar||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit("message",r,!1),this._state=ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Jo),this.end();else{let s=e.readUInt16BE(0);if(!dp(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let r=new Qn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ko(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ne):(this._state=Yn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ne,this.startLoop(n)}))}createError(e,n,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[ap]=r,o}};ta.exports=Tr});var Rr=v((Ib,ra)=>{"use strict";var{Duplex:wb}=require("stream"),{randomFillSync:fp}=require("crypto"),na=Jt(),{EMPTY_BUFFER:pp,kWebSocket:hp,NOOP:gp}=ve(),{isBlob:gt,isValidStatusCode:mp}=ht(),{mask:sa,toBuffer:qe}=Qt(),se=Symbol("kByteLength"),yp=Buffer.alloc(4),Jn=8*1024,Ge,mt=Jn,ce=0,vp=1,Sp=2,kr=class t{constructor(e,n,s){this._extensions=n||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ce,this.onerror=gp,this[hp]=void 0}static frame(e,n){let s,r=!1,i=2,o=!1;n.mask&&(s=n.maskBuffer||yp,n.generateMask?n.generateMask(s):(mt===Jn&&(Ge===void 0&&(Ge=Buffer.alloc(Jn)),fp(Ge,0,Jn),mt=0),s[0]=Ge[mt++],s[1]=Ge[mt++],s[2]=Ge[mt++],s[3]=Ge[mt++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[se]!==void 0?a=n[se]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(r?a+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(a,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[i-4]=s[0],u[i-3]=s[1],u[i-2]=s[2],u[i-1]=s[3],o?[u,e]:r?(sa(e,s,u,i,a),[u]):(sa(e,s,e,0,a),[u,e])):[u,e]}close(e,n,s,r){let i;if(e===void 0)i=pp;else{if(typeof e!="number"||!mp(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={[se]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ce?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(t.frame(i,o),r)}ping(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):gt(e)?(r=e.size,i=!1):(e=qe(e),r=e.length,i=qe.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):gt(e)?(r=e.size,i=!1):(e=qe(e),r=e.length,i=qe.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,n,s){let r=this._extensions[na.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):gt(e)?(a=e.size,l=!1):(e=qe(e),a=e.length,l=qe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[se]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};gt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==ce?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,n,s,r){this._bufferedBytes+=s[se],this._state=Sp,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(xr,this,a,r);return}this._bufferedBytes-=s[se];let o=qe(i);n?this.dispatch(o,n,s,r):(this._state=ce,this.sendFrame(t.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(_p,this,i,r)})}dispatch(e,n,s,r){if(!n){this.sendFrame(t.frame(e,s),r);return}let i=this._extensions[na.extensionName];this._bufferedBytes+=s[se],this._state=vp,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");xr(this,l,r);return}this._bufferedBytes-=s[se],this._state=ce,s.readOnly=!1,this.sendFrame(t.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===ce&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][se],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][se],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)}};ra.exports=kr;function xr(t,e,n){typeof n=="function"&&n(e);for(let s=0;s<t._queue.length;s++){let r=t._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function _p(t,e,n){xr(t,e,n),t.onerror(e)}});var pa=v((Ab,fa)=>{"use strict";var{kForOnEventAttribute:Kt,kListener:Er}=ve(),ia=Symbol("kCode"),oa=Symbol("kData"),aa=Symbol("kError"),la=Symbol("kMessage"),ca=Symbol("kReason"),yt=Symbol("kTarget"),ua=Symbol("kType"),da=Symbol("kWasClean"),_e=class{constructor(e){this[yt]=null,this[ua]=e}get target(){return this[yt]}get type(){return this[ua]}};Object.defineProperty(_e.prototype,"target",{enumerable:!0});Object.defineProperty(_e.prototype,"type",{enumerable:!0});var je=class extends _e{constructor(e,n={}){super(e),this[ia]=n.code===void 0?0:n.code,this[ca]=n.reason===void 0?"":n.reason,this[da]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ia]}get reason(){return this[ca]}get wasClean(){return this[da]}};Object.defineProperty(je.prototype,"code",{enumerable:!0});Object.defineProperty(je.prototype,"reason",{enumerable:!0});Object.defineProperty(je.prototype,"wasClean",{enumerable:!0});var vt=class extends _e{constructor(e,n={}){super(e),this[aa]=n.error===void 0?null:n.error,this[la]=n.message===void 0?"":n.message}get error(){return this[aa]}get message(){return this[la]}};Object.defineProperty(vt.prototype,"error",{enumerable:!0});Object.defineProperty(vt.prototype,"message",{enumerable:!0});var Xt=class extends _e{constructor(e,n={}){super(e),this[oa]=n.data===void 0?null:n.data}get data(){return this[oa]}};Object.defineProperty(Xt.prototype,"data",{enumerable:!0});var bp={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Kt]&&r[Er]===e&&!r[Kt])return;let s;if(t==="message")s=function(i,o){let a=new Xt("message",{data:o?i:i.toString()});a[yt]=this,Kn(e,this,a)};else if(t==="close")s=function(i,o){let a=new je("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[yt]=this,Kn(e,this,a)};else if(t==="error")s=function(i){let o=new vt("error",{error:i,message:i.message});o[yt]=this,Kn(e,this,o)};else if(t==="open")s=function(){let i=new _e("open");i[yt]=this,Kn(e,this,i)};else return;s[Kt]=!!n[Kt],s[Er]=e,n.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Er]===e&&!n[Kt]){this.removeListener(t,n);break}}};fa.exports={CloseEvent:je,ErrorEvent:vt,Event:_e,EventTarget:bp,MessageEvent:Xt};function Kn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Pr=v((Tb,ha)=>{"use strict";var{tokenChars:Zt}=ht();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function wp(t){let e=Object.create(null),n=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,u=-1,c=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),o===void 0)if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(d!==0&&(u===32||u===9))c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);u===44?(he(e,h,n),n=Object.create(null)):o=h,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(u===32||u===9)c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d),he(n,t.slice(l,c),!0),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),l=c=-1}else if(u===61&&l!==-1&&c===-1)a=t.slice(l,d),l=c=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(Zt[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:s||(s=!0),r=!1}else if(i)if(Zt[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)i=!0;else if(c===-1&&Zt[u]===1)l===-1&&(l=d);else if(l!==-1&&(u===32||u===9))c===-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);s&&(h=h.replace(/\\/g,""),s=!1),he(n,a,h),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=d);let f=t.slice(l,c);return o===void 0?he(e,f,n):(a===void 0?he(n,f,!0):s?he(n,a,f.replace(/\\/g,"")):he(n,a,f),he(e,o,n)),e}function Ip(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ha.exports={format:Ip,parse:wp}});var ts=v((xb,Ca)=>{"use strict";var Ap=require("events"),Tp=require("https"),Cp=require("http"),ya=require("net"),kp=require("tls"),{randomBytes:xp,createHash:Rp}=require("crypto"),{Duplex:Cb,Readable:kb}=require("stream"),{URL:Mr}=require("url"),xe=Jt(),Ep=Cr(),Pp=Rr(),{isBlob:Mp}=ht(),{BINARY_TYPES:ga,CLOSE_TIMEOUT:Lp,EMPTY_BUFFER:Xn,GUID:Np,kForOnEventAttribute:Lr,kListener:Op,kStatusCode:Dp,kWebSocket:G,NOOP:va}=ve(),{EventTarget:{addEventListener:Bp,removeEventListener:Fp}}=pa(),{format:Hp,parse:Up}=Pr(),{toBuffer:Wp}=Qt(),Sa=Symbol("kAborted"),Nr=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],qp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,N=class t extends Ap{constructor(e,n,s){super(),this._binaryType=ga[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(s=n,n=[]):n=[n]),_a(this,e,n,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ga.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,s){let r=new Ep({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Pp(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[G]=this,i[G]=this,e[G]=this,r.on("conclude",$p),r.on("drain",zp),r.on("error",Vp),r.on("message",Qp),r.on("ping",Yp),r.on("pong",Jp),i.onerror=Kp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ia),e.on("data",es),e.on("end",Aa),e.on("error",Ta),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[xe.extensionName]&&this._extensions[xe.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){Z(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,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),wa(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Xn,n,s)}pong(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Xn,n,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(s=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Or(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(r.compress=!1),this._sender.send(e||Xn,r,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(N.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(N.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(N.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Lr])return e[Op];return null},set(e){for(let n of this.listeners(t))if(n[Lr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Lr]:!0})}})});N.prototype.addEventListener=Bp;N.prototype.removeEventListener=Fp;Ca.exports=N;function _a(t,e,n,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Lp,protocolVersion:Nr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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=r.autoPong,t._closeTimeout=r.closeTimeout,!Nr.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Nr.join(", ")})`);let i;if(e instanceof Mr)i=e;else try{i=new Mr(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 m=new SyntaxError(l);if(t._redirects===0)throw m;Zn(t,m);return}let u=o?443:80,c=xp(16).toString("base64"),d=o?Tp.request:Cp.request,f=new Set,h;if(r.createConnection=r.createConnection||(o?jp:Gp),r.defaultPort=r.defaultPort||u,r.port=i.port||u,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new xe(r.perMessageDeflate!==!0?r.perMessageDeflate:{},!1,r.maxPayload),r.headers["Sec-WebSocket-Extensions"]=Hp({[xe.extensionName]:h.offer()})),n.length){for(let m of n){if(typeof m!="string"||!qp.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let m=r.path.split(":");r.socketPath=m[0],r.path=m[1]}let g;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?r.socketPath:i.host;let m=s&&s.headers;if(s={...s,headers:{}},m)for(let[p,y]of Object.entries(m))s.headers[p.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,m||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),g=t._req=d(r),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(r);r.timeout&&g.on("timeout",()=>{Z(t,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[Sa]||(g=t._req=null,Zn(t,m))}),g.on("response",m=>{let p=m.headers.location,y=m.statusCode;if(p&&r.followRedirects&&y>=300&&y<400){if(++t._redirects>r.maxRedirects){Z(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new Mr(p,e)}catch{let T=new SyntaxError(`Invalid URL: ${p}`);Zn(t,T);return}_a(t,C,n,s)}else t.emit("unexpected-response",g,m)||Z(t,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,p,y)=>{if(t.emit("upgrade",m),t.readyState!==N.CONNECTING)return;g=t._req=null;let C=m.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Z(t,p,"Invalid Upgrade header");return}let A=Rp("sha1").update(c+Np).digest("base64");if(m.headers["sec-websocket-accept"]!==A){Z(t,p,"Invalid Sec-WebSocket-Accept header");return}let T=m.headers["sec-websocket-protocol"],I;if(T!==void 0?f.size?f.has(T)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":f.size&&(I="Server sent no subprotocol"),I){Z(t,p,I);return}T&&(t._protocol=T);let D=m.headers["sec-websocket-extensions"];if(D!==void 0){if(!h){Z(t,p,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=Up(D)}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(R);if(X.length!==1||X[0]!==xe.extensionName){Z(t,p,"Server indicated an extension that was not requested");return}try{h.accept(R[xe.extensionName])}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=h}t.setSocket(p,y,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(g,t):g.end()}function Zn(t,e){t._readyState=N.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Gp(t){return t.path=t.socketPath,ya.connect(t)}function jp(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ya.isIP(t.host)?"":t.host),kp.connect(t)}function Z(t,e,n){t._readyState=N.CLOSING;let s=new Error(n);Error.captureStackTrace(s,Z),e.setHeader?(e[Sa]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zn,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Or(t,e,n){if(e){let s=Mp(e)?e.size:Wp(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(n){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,s)}}function $p(t,e){let n=this[G];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[G]!==void 0&&(n._socket.removeListener("data",es),process.nextTick(ba,n._socket),t===1005?n.close():n.close(t,e))}function zp(){let t=this[G];t.isPaused||t._socket.resume()}function Vp(t){let e=this[G];e._socket[G]!==void 0&&(e._socket.removeListener("data",es),process.nextTick(ba,e._socket),e.close(t[Dp])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ma(){this[G].emitClose()}function Qp(t,e){this[G].emit("message",t,e)}function Yp(t){let e=this[G];e._autoPong&&e.pong(t,!this._isServer,va),e.emit("ping",t)}function Jp(t){this[G].emit("pong",t)}function ba(t){t.resume()}function Kp(t){let e=this[G];e.readyState!==N.CLOSED&&(e.readyState===N.OPEN&&(e._readyState=N.CLOSING,wa(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function wa(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ia(){let t=this[G];if(this.removeListener("close",Ia),this.removeListener("data",es),this.removeListener("end",Aa),t._readyState=N.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[G]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ma),t._receiver.on("finish",ma))}function es(t){this[G]._receiver.write(t)||this.pause()}function Aa(){let t=this[G];t._readyState=N.CLOSING,t._receiver.end(),this.end()}function Ta(){let t=this[G];this.removeListener("error",Ta),this.on("error",va),t&&(t._readyState=N.CLOSING,this.destroy())}});var Ea=v((Eb,Ra)=>{"use strict";var Rb=ts(),{Duplex:Xp}=require("stream");function ka(t){t.emit("close")}function Zp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xa(t){this.removeListener("error",xa),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function eh(t,e){let n=!0,s=new Xp({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(n=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(t.readyState===t.CLOSED){i(r),process.nextTick(ka,s);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(r),process.nextTick(ka,s)}),n&&t.terminate()},s._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(r,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(r,i,o)});return}t.send(r,o)},s.on("end",Zp),s.on("error",xa),s}Ra.exports=eh});var Ma=v((Pb,Pa)=>{"use strict";var{tokenChars:th}=ht();function nh(t){let e=new Set,n=-1,s=-1,r=0;for(r;r<t.length;r++){let o=t.charCodeAt(r);if(s===-1&&th[o]===1)n===-1&&(n=r);else if(r!==0&&(o===32||o===9))s===-1&&n!==-1&&(s=r);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Pa.exports={parse:nh}});var Ha=v((Lb,Fa)=>{"use strict";var sh=require("events"),ns=require("http"),{Duplex:Mb}=require("stream"),{createHash:rh}=require("crypto"),La=Pr(),$e=Jt(),ih=Ma(),oh=ts(),{CLOSE_TIMEOUT:ah,GUID:lh,kWebSocket:ch}=ve(),uh=/^[+/0-9A-Za-z]{22}==$/,Na=0,Oa=1,Ba=2,Dr=class extends sh{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ah,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:oh,...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=ns.createServer((s,r)=>{let i=ns.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=dh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Na}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===Ba){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(en,this);return}if(e&&this.once("close",e),this._state!==Oa)if(this._state=Oa,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(en,this):process.nextTick(en,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{en(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,s,r){n.on("error",Da);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ze(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ze(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!uh.test(i)){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){tn(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=ih.parse(l)}catch{ze(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let c=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&c!==void 0){let f=new $e(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=La.parse(c);h[$e.extensionName]&&(f.accept(h[$e.extensionName]),d[$e.extensionName]=f)}catch{ze(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,(h,g,m,p)=>{if(!h)return tn(n,g||401,m,p);this.completeUpgrade(d,i,u,e,n,s,r)});return}if(!this.options.verifyClient(f))return tn(n,401)}this.completeUpgrade(d,i,u,e,n,s,r)}completeUpgrade(e,n,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[ch])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Na)return tn(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rh("sha1").update(n+lh).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[$e.extensionName]){let d=e[$e.extensionName].params,f=La.format({[$e.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${f}`),c._extensions=e}this.emit("headers",u,r),i.write(u.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",Oa),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(en,this)})),a(c,r)}};Ba.exports=Dr;function uh(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function en(t){t._state=Da,t.emit("close")}function Oa(){this.destroy()}function tn(t,e,n,s){n=n||ns.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ns.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",Da),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(en,this)})),a(c,r)}};Fa.exports=Dr;function dh(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function en(t){t._state=Ba,t.emit("close")}function Da(){this.destroy()}function tn(t,e,n,s){n=n||ns.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ns.STATUS_CODES[e]}\r
4
4
  `+Object.keys(s).map(r=>`${r}: ${s[r]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function ze(t,e,n,s,r,i){if(t.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,ze),t.emit("wsClientError",o,n,e)}else tn(n,s,r,i)}});var Fr=v((Lb,Ha)=>{Ha.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Re=v(Ve=>{var Hr,gh=[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];Ve.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};Ve.getSymbolTotalCodewords=function(e){return gh[e]};Ve.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ve.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Hr=e};Ve.isKanjiModeEnabled=function(){return typeof Hr<"u"};Ve.toSJIS=function(e){return Hr(e)}});var ss=v(re=>{re.L={bit:1};re.M={bit:0};re.Q={bit:3};re.H={bit:2};function mh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return re.L;case"m":case"medium":return re.M;case"q":case"quartile":return re.Q;case"h":case"high":return re.H;default:throw new Error("Unknown EC Level: "+t)}}re.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};re.from=function(e,n){if(re.isValid(e))return e;try{return mh(e)}catch{return n}}});var qa=v((Db,Wa)=>{function Ua(){this.buffer=[],this.length=0}Ua.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++}};Wa.exports=Ua});var ja=v((Bb,Ga)=>{function nn(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)}nn.prototype.set=function(t,e,n,s){let r=t*this.size+e;this.data[r]=n,s&&(this.reservedBit[r]=!0)};nn.prototype.get=function(t,e){return this.data[t*this.size+e]};nn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};nn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ga.exports=nn});var $a=v(rs=>{var yh=Re().getSymbolSize;rs.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,s=yh(e),r=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-r;return i.push(6),i.reverse()};rs.getPositions=function(e){let n=[],s=rs.getRowColCoords(e),r=s.length;for(let i=0;i<r;i++)for(let o=0;o<r;o++)i===0&&o===0||i===0&&o===r-1||i===r-1&&o===0||n.push([s[i],s[o]]);return n}});var Qa=v(Va=>{var vh=Re().getSymbolSize,za=7;Va.getPositions=function(e){let n=vh(e);return[[0,0],[n-za,0],[0,n-za]]}});var Ya=v(R=>{R.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Qe={N1:3,N2:3,N3:40,N4:10};R.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};R.from=function(e){return R.isValid(e)?parseInt(e,10):void 0};R.getPenaltyN1=function(e){let n=e.size,s=0,r=0,i=0,o=null,a=null;for(let l=0;l<n;l++){r=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?r++:(r>=5&&(s+=Qe.N1+(r-5)),o=c,r=1),c=e.get(u,l),c===a?i++:(i>=5&&(s+=Qe.N1+(i-5)),a=c,i=1)}r>=5&&(s+=Qe.N1+(r-5)),i>=5&&(s+=Qe.N1+(i-5))}return s};R.getPenaltyN2=function(e){let n=e.size,s=0;for(let r=0;r<n-1;r++)for(let i=0;i<n-1;i++){let o=e.get(r,i)+e.get(r,i+1)+e.get(r+1,i)+e.get(r+1,i+1);(o===4||o===0)&&s++}return s*Qe.N2};R.getPenaltyN3=function(e){let n=e.size,s=0,r=0,i=0;for(let o=0;o<n;o++){r=i=0;for(let a=0;a<n;a++)r=r<<1&2047|e.get(o,a),a>=10&&(r===1488||r===93)&&s++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&s++}return s*Qe.N3};R.getPenaltyN4=function(e){let n=0,s=e.data.length;for(let i=0;i<s;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/s/5)-10)*Qe.N4};function Sh(t,e,n){switch(t){case R.Patterns.PATTERN000:return(e+n)%2===0;case R.Patterns.PATTERN001:return e%2===0;case R.Patterns.PATTERN010:return n%3===0;case R.Patterns.PATTERN011:return(e+n)%3===0;case R.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case R.Patterns.PATTERN101:return e*n%2+e*n%3===0;case R.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case R.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}R.applyMask=function(e,n){let s=n.size;for(let r=0;r<s;r++)for(let i=0;i<s;i++)n.isReserved(i,r)||n.xor(i,r,Sh(e,i,r))};R.getBestMask=function(e,n){let s=Object.keys(R.Patterns).length,r=0,i=1/0;for(let o=0;o<s;o++){n(o),R.applyMask(o,e);let a=R.getPenaltyN1(e)+R.getPenaltyN2(e)+R.getPenaltyN3(e)+R.getPenaltyN4(e);R.applyMask(o,e),a<i&&(i=a,r=o)}return r}});var Wr=v(Ur=>{var Ee=ss(),is=[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],os=[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];Ur.getBlocksCount=function(e,n){switch(n){case Ee.L:return is[(e-1)*4+0];case Ee.M:return is[(e-1)*4+1];case Ee.Q:return is[(e-1)*4+2];case Ee.H:return is[(e-1)*4+3];default:return}};Ur.getTotalCodewordsCount=function(e,n){switch(n){case Ee.L:return os[(e-1)*4+0];case Ee.M:return os[(e-1)*4+1];case Ee.Q:return os[(e-1)*4+2];case Ee.H:return os[(e-1)*4+3];default:return}}});var Ja=v(ls=>{var sn=new Uint8Array(512),as=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)sn[n]=e,as[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)sn[n]=sn[n-255]})();ls.log=function(e){if(e<1)throw new Error("log("+e+")");return as[e]};ls.exp=function(e){return sn[e]};ls.mul=function(e,n){return e===0||n===0?0:sn[as[e]+as[n]]}});var Ka=v(rn=>{var qr=Ja();rn.mul=function(e,n){let s=new Uint8Array(e.length+n.length-1);for(let r=0;r<e.length;r++)for(let i=0;i<n.length;i++)s[r+i]^=qr.mul(e[r],n[i]);return s};rn.mod=function(e,n){let s=new Uint8Array(e);for(;s.length-n.length>=0;){let r=s[0];for(let o=0;o<n.length;o++)s[o]^=qr.mul(n[o],r);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s};rn.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let s=0;s<e;s++)n=rn.mul(n,new Uint8Array([1,qr.exp(s)]));return n}});var el=v((jb,Za)=>{var Xa=Ka();function Gr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Gr.prototype.initialize=function(e){this.degree=e,this.genPoly=Xa.generateECPolynomial(this.degree)};Gr.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 s=Xa.mod(n,this.genPoly),r=this.degree-s.length;if(r>0){let i=new Uint8Array(this.degree);return i.set(s,r),i}return s};Za.exports=Gr});var jr=v(tl=>{tl.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var $r=v(we=>{var nl="[0-9]+",_h="[A-Z $%*+\\-./:]+",on="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";on=on.replace(/u/g,"\\u");var bh="(?:(?![A-Z0-9 $%*+\\-./:]|"+on+`)(?:.|[\r
8
- ]))+`;we.KANJI=new RegExp(on,"g");we.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");we.BYTE=new RegExp(bh,"g");we.NUMERIC=new RegExp(nl,"g");we.ALPHANUMERIC=new RegExp(_h,"g");var wh=new RegExp("^"+on+"$"),Ih=new RegExp("^"+nl+"$"),Ah=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");we.testKanji=function(e){return wh.test(e)};we.testNumeric=function(e){return Ih.test(e)};we.testAlphanumeric=function(e){return Ah.test(e)}});var Pe=v(B=>{var Th=jr(),zr=$r();B.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};B.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};B.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};B.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};B.MIXED={bit:-1};B.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Th.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};B.getBestModeForData=function(e){return zr.testNumeric(e)?B.NUMERIC:zr.testAlphanumeric(e)?B.ALPHANUMERIC:zr.testKanji(e)?B.KANJI:B.BYTE};B.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};B.isValid=function(e){return e&&e.bit&&e.ccBits};function Ch(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return B.NUMERIC;case"alphanumeric":return B.ALPHANUMERIC;case"kanji":return B.KANJI;case"byte":return B.BYTE;default:throw new Error("Unknown mode: "+t)}}B.from=function(e,n){if(B.isValid(e))return e;try{return Ch(e)}catch{return n}}});var al=v(Ye=>{var cs=Re(),kh=Wr(),sl=ss(),Me=Pe(),Vr=jr(),il=7973,rl=cs.getBCHDigit(il);function xh(t,e,n){for(let s=1;s<=40;s++)if(e<=Ye.getCapacity(s,n,t))return s}function ol(t,e){return Me.getCharCountIndicator(t,e)+4}function Rh(t,e){let n=0;return t.forEach(function(s){let r=ol(s.mode,e);n+=r+s.getBitsLength()}),n}function Eh(t,e){for(let n=1;n<=40;n++)if(Rh(t,n)<=Ye.getCapacity(n,e,Me.MIXED))return n}Ye.from=function(e,n){return Vr.isValid(e)?parseInt(e,10):n};Ye.getCapacity=function(e,n,s){if(!Vr.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=Me.BYTE);let r=cs.getSymbolTotalCodewords(e),i=kh.getTotalCodewordsCount(e,n),o=(r-i)*8;if(s===Me.MIXED)return o;let a=o-ol(s,e);switch(s){case Me.NUMERIC:return Math.floor(a/10*3);case Me.ALPHANUMERIC:return Math.floor(a/11*2);case Me.KANJI:return Math.floor(a/13);case Me.BYTE:default:return Math.floor(a/8)}};Ye.getBestVersionForData=function(e,n){let s,r=sl.from(n,sl.M);if(Array.isArray(e)){if(e.length>1)return Eh(e,r);if(e.length===0)return 1;s=e[0]}else s=e;return xh(s.mode,s.getLength(),r)};Ye.getEncodedBits=function(e){if(!Vr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;cs.getBCHDigit(n)-rl>=0;)n^=il<<cs.getBCHDigit(n)-rl;return e<<12|n}});var dl=v(ul=>{var Qr=Re(),cl=1335,Ph=21522,ll=Qr.getBCHDigit(cl);ul.getEncodedBits=function(e,n){let s=e.bit<<3|n,r=s<<10;for(;Qr.getBCHDigit(r)-ll>=0;)r^=cl<<Qr.getBCHDigit(r)-ll;return(s<<10|r)^Ph}});var pl=v((Jb,fl)=>{var Mh=Pe();function St(t){this.mode=Mh.NUMERIC,this.data=t.toString()}St.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.prototype.write=function(e){let n,s,r;for(n=0;n+3<=this.data.length;n+=3)s=this.data.substr(n,3),r=parseInt(s,10),e.put(r,10);let i=this.data.length-n;i>0&&(s=this.data.substr(n),r=parseInt(s,10),e.put(r,i*3+1))};fl.exports=St});var gl=v((Kb,hl)=>{var Lh=Pe(),Yr=["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 _t(t){this.mode=Lh.ALPHANUMERIC,this.data=t}_t.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let s=Yr.indexOf(this.data[n])*45;s+=Yr.indexOf(this.data[n+1]),e.put(s,11)}this.data.length%2&&e.put(Yr.indexOf(this.data[n]),6)};hl.exports=_t});var yl=v((Xb,ml)=>{var Nh=Pe();function bt(t){this.mode=Nh.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}bt.getBitsLength=function(e){return e*8};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};ml.exports=bt});var Sl=v((Zb,vl)=>{var Oh=Pe(),Dh=Re();function wt(t){this.mode=Oh.KANJI,this.data=t}wt.getBitsLength=function(e){return e*13};wt.prototype.getLength=function(){return this.data.length};wt.prototype.getBitsLength=function(){return wt.getBitsLength(this.data.length)};wt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Dh.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)}};vl.exports=wt});var _l=v((e0,Jr)=>{"use strict";var an={single_source_shortest_paths:function(t,e,n){var s={},r={};r[e]=0;var i=an.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,u=o.cost,c=t[a]||{};for(l in c)c.hasOwnProperty(l)&&(d=c[l],f=u+d,h=r[l],g=typeof r[l]>"u",(g||h>f)&&(r[l]=f,i.push(l,f),s[l]=a))}if(typeof n<"u"&&typeof r[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],s=e,r;s;)n.push(s),r=t[s],s=t[s];return n.reverse(),n},find_path:function(t,e,n){var s=an.single_source_shortest_paths(t,e,n);return an.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var e=an.PriorityQueue,n={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(n[s]=e[s]);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 Jr<"u"&&(Jr.exports=an)});var xl=v(It=>{var k=Pe(),Il=pl(),Al=gl(),Tl=yl(),Cl=Sl(),ln=$r(),us=Re(),Bh=_l();function bl(t){return unescape(encodeURIComponent(t)).length}function cn(t,e,n){let s=[],r;for(;(r=t.exec(n))!==null;)s.push({data:r[0],index:r.index,mode:e,length:r[0].length});return s}function kl(t){let e=cn(ln.NUMERIC,k.NUMERIC,t),n=cn(ln.ALPHANUMERIC,k.ALPHANUMERIC,t),s,r;return us.isKanjiModeEnabled()?(s=cn(ln.BYTE,k.BYTE,t),r=cn(ln.KANJI,k.KANJI,t)):(s=cn(ln.BYTE_KANJI,k.BYTE,t),r=[]),e.concat(n,s,r).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Kr(t,e){switch(e){case k.NUMERIC:return Il.getBitsLength(t);case k.ALPHANUMERIC:return Al.getBitsLength(t);case k.KANJI:return Cl.getBitsLength(t);case k.BYTE:return Tl.getBitsLength(t)}}function Fh(t){return t.reduce(function(e,n){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Hh(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];switch(s.mode){case k.NUMERIC:e.push([s,{data:s.data,mode:k.ALPHANUMERIC,length:s.length},{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.ALPHANUMERIC:e.push([s,{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.KANJI:e.push([s,{data:s.data,mode:k.BYTE,length:bl(s.data)}]);break;case k.BYTE:e.push([{data:s.data,mode:k.BYTE,length:bl(s.data)}])}}return e}function Uh(t,e){let n={},s={start:{}},r=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},s[c]={};for(let d=0;d<r.length;d++){let f=r[d];n[f]&&n[f].node.mode===u.mode?(s[f][c]=Kr(n[f].lastCount+u.length,u.mode)-Kr(n[f].lastCount,u.mode),n[f].lastCount+=u.length):(n[f]&&(n[f].lastCount=u.length),s[f][c]=Kr(u.length,u.mode)+4+k.getCharCountIndicator(u.mode,e))}}r=a}for(let i=0;i<r.length;i++)s[r[i]].end=0;return{map:s,table:n}}function wl(t,e){let n,s=k.getBestModeForData(t);if(n=k.from(e,s),n!==k.BYTE&&n.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+k.toString(n)+`.
10
- Suggested mode is: `+k.toString(s));switch(n===k.KANJI&&!us.isKanjiModeEnabled()&&(n=k.BYTE),n){case k.NUMERIC:return new Il(t);case k.ALPHANUMERIC:return new Al(t);case k.KANJI:return new Cl(t);case k.BYTE:return new Tl(t)}}It.fromArray=function(e){return e.reduce(function(n,s){return typeof s=="string"?n.push(wl(s,null)):s.data&&n.push(wl(s.data,s.mode)),n},[])};It.fromString=function(e,n){let s=kl(e,us.isKanjiModeEnabled()),r=Hh(s),i=Uh(r,n),o=Bh.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return It.fromArray(Fh(a))};It.rawSplit=function(e){return It.fromArray(kl(e,us.isKanjiModeEnabled()))}});var si=v(Rl=>{var fs=Re(),Xr=ss(),Wh=qa(),qh=ja(),Gh=$a(),jh=Qa(),ti=Ya(),ni=Wr(),$h=el(),ds=al(),zh=dl(),Vh=Pe(),Zr=xl();function Qh(t,e){let n=t.size,s=jh.getPositions(e);for(let r=0;r<s.length;r++){let i=s[r][0],o=s[r][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 Yh(t){let e=t.size;for(let n=8;n<e-8;n++){let s=n%2===0;t.set(n,6,s,!0),t.set(6,n,s,!0)}}function Jh(t,e){let n=Gh.getPositions(e);for(let s=0;s<n.length;s++){let r=n[s][0],i=n[s][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(r+o,i+a,!0,!0):t.set(r+o,i+a,!1,!0)}}function Kh(t,e){let n=t.size,s=ds.getEncodedBits(e),r,i,o;for(let a=0;a<18;a++)r=Math.floor(a/3),i=a%3+n-8-3,o=(s>>a&1)===1,t.set(r,i,o,!0),t.set(i,r,o,!0)}function ei(t,e,n){let s=t.size,r=zh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(r>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(s-15+i,8,o,!0),i<8?t.set(8,s-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(s-8,8,1,!0)}function Xh(t,e){let n=t.size,s=-1,r=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(r,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(r,a-l,u),i--,i===-1&&(o++,i=7)}if(r+=s,r<0||n<=r){r-=s,s=-s;break}}}function Zh(t,e,n){let s=new Wh;n.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),Vh.getCharCountIndicator(l.mode,t)),l.write(s)});let r=fs.getSymbolTotalCodewords(t),i=ni.getTotalCodewordsCount(t,e),o=(r-i)*8;for(s.getLengthInBits()+4<=o&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let a=(o-s.getLengthInBits())/8;for(let l=0;l<a;l++)s.put(l%2?17:236,8);return eg(s,t,e)}function eg(t,e,n){let s=fs.getSymbolTotalCodewords(e),r=ni.getTotalCodewordsCount(e,n),i=s-r,o=ni.getBlocksCount(e,n),a=s%o,l=o-a,u=Math.floor(s/o),c=Math.floor(i/o),d=c+1,f=u-c,h=new $h(f),g=0,m=new Array(o),p=new Array(o),y=0,C=new Uint8Array(t.buffer);for(let x=0;x<o;x++){let X=x<l?c:d;m[x]=C.slice(g,g+X),p[x]=h.encode(m[x]),g+=X,y=Math.max(y,X)}let A=new Uint8Array(s),T=0,I,D;for(I=0;I<y;I++)for(D=0;D<o;D++)I<m[D].length&&(A[T++]=m[D][I]);for(I=0;I<f;I++)for(D=0;D<o;D++)A[T++]=p[D][I];return A}function tg(t,e,n,s){let r;if(Array.isArray(t))r=Zr.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=Zr.rawSplit(t);u=ds.getBestVersionForData(c,n)}r=Zr.fromString(t,u||40)}else throw new Error("Invalid data");let i=ds.getBestVersionForData(r,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 ze(t,e,n,s,r,i){if(t.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,ze),t.emit("wsClientError",o,n,e)}else tn(n,s,r,i)}});var Fr=v((Ob,Ua)=>{Ua.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Re=v(Ve=>{var Hr,mh=[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];Ve.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};Ve.getSymbolTotalCodewords=function(e){return mh[e]};Ve.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ve.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Hr=e};Ve.isKanjiModeEnabled=function(){return typeof Hr<"u"};Ve.toSJIS=function(e){return Hr(e)}});var ss=v(re=>{re.L={bit:1};re.M={bit:0};re.Q={bit:3};re.H={bit:2};function yh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return re.L;case"m":case"medium":return re.M;case"q":case"quartile":return re.Q;case"h":case"high":return re.H;default:throw new Error("Unknown EC Level: "+t)}}re.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};re.from=function(e,n){if(re.isValid(e))return e;try{return yh(e)}catch{return n}}});var Ga=v((Fb,qa)=>{function Wa(){this.buffer=[],this.length=0}Wa.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++}};qa.exports=Wa});var $a=v((Hb,ja)=>{function nn(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)}nn.prototype.set=function(t,e,n,s){let r=t*this.size+e;this.data[r]=n,s&&(this.reservedBit[r]=!0)};nn.prototype.get=function(t,e){return this.data[t*this.size+e]};nn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};nn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ja.exports=nn});var za=v(rs=>{var vh=Re().getSymbolSize;rs.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,s=vh(e),r=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-r;return i.push(6),i.reverse()};rs.getPositions=function(e){let n=[],s=rs.getRowColCoords(e),r=s.length;for(let i=0;i<r;i++)for(let o=0;o<r;o++)i===0&&o===0||i===0&&o===r-1||i===r-1&&o===0||n.push([s[i],s[o]]);return n}});var Ya=v(Qa=>{var Sh=Re().getSymbolSize,Va=7;Qa.getPositions=function(e){let n=Sh(e);return[[0,0],[n-Va,0],[0,n-Va]]}});var Ja=v(E=>{E.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Qe={N1:3,N2:3,N3:40,N4:10};E.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};E.from=function(e){return E.isValid(e)?parseInt(e,10):void 0};E.getPenaltyN1=function(e){let n=e.size,s=0,r=0,i=0,o=null,a=null;for(let l=0;l<n;l++){r=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?r++:(r>=5&&(s+=Qe.N1+(r-5)),o=c,r=1),c=e.get(u,l),c===a?i++:(i>=5&&(s+=Qe.N1+(i-5)),a=c,i=1)}r>=5&&(s+=Qe.N1+(r-5)),i>=5&&(s+=Qe.N1+(i-5))}return s};E.getPenaltyN2=function(e){let n=e.size,s=0;for(let r=0;r<n-1;r++)for(let i=0;i<n-1;i++){let o=e.get(r,i)+e.get(r,i+1)+e.get(r+1,i)+e.get(r+1,i+1);(o===4||o===0)&&s++}return s*Qe.N2};E.getPenaltyN3=function(e){let n=e.size,s=0,r=0,i=0;for(let o=0;o<n;o++){r=i=0;for(let a=0;a<n;a++)r=r<<1&2047|e.get(o,a),a>=10&&(r===1488||r===93)&&s++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&s++}return s*Qe.N3};E.getPenaltyN4=function(e){let n=0,s=e.data.length;for(let i=0;i<s;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/s/5)-10)*Qe.N4};function _h(t,e,n){switch(t){case E.Patterns.PATTERN000:return(e+n)%2===0;case E.Patterns.PATTERN001:return e%2===0;case E.Patterns.PATTERN010:return n%3===0;case E.Patterns.PATTERN011:return(e+n)%3===0;case E.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case E.Patterns.PATTERN101:return e*n%2+e*n%3===0;case E.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case E.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}E.applyMask=function(e,n){let s=n.size;for(let r=0;r<s;r++)for(let i=0;i<s;i++)n.isReserved(i,r)||n.xor(i,r,_h(e,i,r))};E.getBestMask=function(e,n){let s=Object.keys(E.Patterns).length,r=0,i=1/0;for(let o=0;o<s;o++){n(o),E.applyMask(o,e);let a=E.getPenaltyN1(e)+E.getPenaltyN2(e)+E.getPenaltyN3(e)+E.getPenaltyN4(e);E.applyMask(o,e),a<i&&(i=a,r=o)}return r}});var Wr=v(Ur=>{var Ee=ss(),is=[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],os=[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];Ur.getBlocksCount=function(e,n){switch(n){case Ee.L:return is[(e-1)*4+0];case Ee.M:return is[(e-1)*4+1];case Ee.Q:return is[(e-1)*4+2];case Ee.H:return is[(e-1)*4+3];default:return}};Ur.getTotalCodewordsCount=function(e,n){switch(n){case Ee.L:return os[(e-1)*4+0];case Ee.M:return os[(e-1)*4+1];case Ee.Q:return os[(e-1)*4+2];case Ee.H:return os[(e-1)*4+3];default:return}}});var Ka=v(ls=>{var sn=new Uint8Array(512),as=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)sn[n]=e,as[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)sn[n]=sn[n-255]})();ls.log=function(e){if(e<1)throw new Error("log("+e+")");return as[e]};ls.exp=function(e){return sn[e]};ls.mul=function(e,n){return e===0||n===0?0:sn[as[e]+as[n]]}});var Xa=v(rn=>{var qr=Ka();rn.mul=function(e,n){let s=new Uint8Array(e.length+n.length-1);for(let r=0;r<e.length;r++)for(let i=0;i<n.length;i++)s[r+i]^=qr.mul(e[r],n[i]);return s};rn.mod=function(e,n){let s=new Uint8Array(e);for(;s.length-n.length>=0;){let r=s[0];for(let o=0;o<n.length;o++)s[o]^=qr.mul(n[o],r);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s};rn.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let s=0;s<e;s++)n=rn.mul(n,new Uint8Array([1,qr.exp(s)]));return n}});var tl=v((zb,el)=>{var Za=Xa();function Gr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Gr.prototype.initialize=function(e){this.degree=e,this.genPoly=Za.generateECPolynomial(this.degree)};Gr.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 s=Za.mod(n,this.genPoly),r=this.degree-s.length;if(r>0){let i=new Uint8Array(this.degree);return i.set(s,r),i}return s};el.exports=Gr});var jr=v(nl=>{nl.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var $r=v(we=>{var sl="[0-9]+",bh="[A-Z $%*+\\-./:]+",on="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";on=on.replace(/u/g,"\\u");var wh="(?:(?![A-Z0-9 $%*+\\-./:]|"+on+`)(?:.|[\r
8
+ ]))+`;we.KANJI=new RegExp(on,"g");we.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");we.BYTE=new RegExp(wh,"g");we.NUMERIC=new RegExp(sl,"g");we.ALPHANUMERIC=new RegExp(bh,"g");var Ih=new RegExp("^"+on+"$"),Ah=new RegExp("^"+sl+"$"),Th=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");we.testKanji=function(e){return Ih.test(e)};we.testNumeric=function(e){return Ah.test(e)};we.testAlphanumeric=function(e){return Th.test(e)}});var Pe=v(B=>{var Ch=jr(),zr=$r();B.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};B.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};B.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};B.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};B.MIXED={bit:-1};B.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Ch.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};B.getBestModeForData=function(e){return zr.testNumeric(e)?B.NUMERIC:zr.testAlphanumeric(e)?B.ALPHANUMERIC:zr.testKanji(e)?B.KANJI:B.BYTE};B.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};B.isValid=function(e){return e&&e.bit&&e.ccBits};function kh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return B.NUMERIC;case"alphanumeric":return B.ALPHANUMERIC;case"kanji":return B.KANJI;case"byte":return B.BYTE;default:throw new Error("Unknown mode: "+t)}}B.from=function(e,n){if(B.isValid(e))return e;try{return kh(e)}catch{return n}}});var ll=v(Ye=>{var cs=Re(),xh=Wr(),rl=ss(),Me=Pe(),Vr=jr(),ol=7973,il=cs.getBCHDigit(ol);function Rh(t,e,n){for(let s=1;s<=40;s++)if(e<=Ye.getCapacity(s,n,t))return s}function al(t,e){return Me.getCharCountIndicator(t,e)+4}function Eh(t,e){let n=0;return t.forEach(function(s){let r=al(s.mode,e);n+=r+s.getBitsLength()}),n}function Ph(t,e){for(let n=1;n<=40;n++)if(Eh(t,n)<=Ye.getCapacity(n,e,Me.MIXED))return n}Ye.from=function(e,n){return Vr.isValid(e)?parseInt(e,10):n};Ye.getCapacity=function(e,n,s){if(!Vr.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=Me.BYTE);let r=cs.getSymbolTotalCodewords(e),i=xh.getTotalCodewordsCount(e,n),o=(r-i)*8;if(s===Me.MIXED)return o;let a=o-al(s,e);switch(s){case Me.NUMERIC:return Math.floor(a/10*3);case Me.ALPHANUMERIC:return Math.floor(a/11*2);case Me.KANJI:return Math.floor(a/13);case Me.BYTE:default:return Math.floor(a/8)}};Ye.getBestVersionForData=function(e,n){let s,r=rl.from(n,rl.M);if(Array.isArray(e)){if(e.length>1)return Ph(e,r);if(e.length===0)return 1;s=e[0]}else s=e;return Rh(s.mode,s.getLength(),r)};Ye.getEncodedBits=function(e){if(!Vr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;cs.getBCHDigit(n)-il>=0;)n^=ol<<cs.getBCHDigit(n)-il;return e<<12|n}});var fl=v(dl=>{var Qr=Re(),ul=1335,Mh=21522,cl=Qr.getBCHDigit(ul);dl.getEncodedBits=function(e,n){let s=e.bit<<3|n,r=s<<10;for(;Qr.getBCHDigit(r)-cl>=0;)r^=ul<<Qr.getBCHDigit(r)-cl;return(s<<10|r)^Mh}});var hl=v((Xb,pl)=>{var Lh=Pe();function St(t){this.mode=Lh.NUMERIC,this.data=t.toString()}St.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.prototype.write=function(e){let n,s,r;for(n=0;n+3<=this.data.length;n+=3)s=this.data.substr(n,3),r=parseInt(s,10),e.put(r,10);let i=this.data.length-n;i>0&&(s=this.data.substr(n),r=parseInt(s,10),e.put(r,i*3+1))};pl.exports=St});var ml=v((Zb,gl)=>{var Nh=Pe(),Yr=["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 _t(t){this.mode=Nh.ALPHANUMERIC,this.data=t}_t.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let s=Yr.indexOf(this.data[n])*45;s+=Yr.indexOf(this.data[n+1]),e.put(s,11)}this.data.length%2&&e.put(Yr.indexOf(this.data[n]),6)};gl.exports=_t});var vl=v((e0,yl)=>{var Oh=Pe();function bt(t){this.mode=Oh.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}bt.getBitsLength=function(e){return e*8};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};yl.exports=bt});var _l=v((t0,Sl)=>{var Dh=Pe(),Bh=Re();function wt(t){this.mode=Dh.KANJI,this.data=t}wt.getBitsLength=function(e){return e*13};wt.prototype.getLength=function(){return this.data.length};wt.prototype.getBitsLength=function(){return wt.getBitsLength(this.data.length)};wt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Bh.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)}};Sl.exports=wt});var bl=v((n0,Jr)=>{"use strict";var an={single_source_shortest_paths:function(t,e,n){var s={},r={};r[e]=0;var i=an.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,u=o.cost,c=t[a]||{};for(l in c)c.hasOwnProperty(l)&&(d=c[l],f=u+d,h=r[l],g=typeof r[l]>"u",(g||h>f)&&(r[l]=f,i.push(l,f),s[l]=a))}if(typeof n<"u"&&typeof r[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],s=e,r;s;)n.push(s),r=t[s],s=t[s];return n.reverse(),n},find_path:function(t,e,n){var s=an.single_source_shortest_paths(t,e,n);return an.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var e=an.PriorityQueue,n={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(n[s]=e[s]);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 Jr<"u"&&(Jr.exports=an)});var Rl=v(It=>{var k=Pe(),Al=hl(),Tl=ml(),Cl=vl(),kl=_l(),ln=$r(),us=Re(),Fh=bl();function wl(t){return unescape(encodeURIComponent(t)).length}function cn(t,e,n){let s=[],r;for(;(r=t.exec(n))!==null;)s.push({data:r[0],index:r.index,mode:e,length:r[0].length});return s}function xl(t){let e=cn(ln.NUMERIC,k.NUMERIC,t),n=cn(ln.ALPHANUMERIC,k.ALPHANUMERIC,t),s,r;return us.isKanjiModeEnabled()?(s=cn(ln.BYTE,k.BYTE,t),r=cn(ln.KANJI,k.KANJI,t)):(s=cn(ln.BYTE_KANJI,k.BYTE,t),r=[]),e.concat(n,s,r).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Kr(t,e){switch(e){case k.NUMERIC:return Al.getBitsLength(t);case k.ALPHANUMERIC:return Tl.getBitsLength(t);case k.KANJI:return kl.getBitsLength(t);case k.BYTE:return Cl.getBitsLength(t)}}function Hh(t){return t.reduce(function(e,n){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Uh(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];switch(s.mode){case k.NUMERIC:e.push([s,{data:s.data,mode:k.ALPHANUMERIC,length:s.length},{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.ALPHANUMERIC:e.push([s,{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.KANJI:e.push([s,{data:s.data,mode:k.BYTE,length:wl(s.data)}]);break;case k.BYTE:e.push([{data:s.data,mode:k.BYTE,length:wl(s.data)}])}}return e}function Wh(t,e){let n={},s={start:{}},r=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},s[c]={};for(let d=0;d<r.length;d++){let f=r[d];n[f]&&n[f].node.mode===u.mode?(s[f][c]=Kr(n[f].lastCount+u.length,u.mode)-Kr(n[f].lastCount,u.mode),n[f].lastCount+=u.length):(n[f]&&(n[f].lastCount=u.length),s[f][c]=Kr(u.length,u.mode)+4+k.getCharCountIndicator(u.mode,e))}}r=a}for(let i=0;i<r.length;i++)s[r[i]].end=0;return{map:s,table:n}}function Il(t,e){let n,s=k.getBestModeForData(t);if(n=k.from(e,s),n!==k.BYTE&&n.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+k.toString(n)+`.
10
+ Suggested mode is: `+k.toString(s));switch(n===k.KANJI&&!us.isKanjiModeEnabled()&&(n=k.BYTE),n){case k.NUMERIC:return new Al(t);case k.ALPHANUMERIC:return new Tl(t);case k.KANJI:return new kl(t);case k.BYTE:return new Cl(t)}}It.fromArray=function(e){return e.reduce(function(n,s){return typeof s=="string"?n.push(Il(s,null)):s.data&&n.push(Il(s.data,s.mode)),n},[])};It.fromString=function(e,n){let s=xl(e,us.isKanjiModeEnabled()),r=Uh(s),i=Wh(r,n),o=Fh.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return It.fromArray(Hh(a))};It.rawSplit=function(e){return It.fromArray(xl(e,us.isKanjiModeEnabled()))}});var si=v(El=>{var fs=Re(),Xr=ss(),qh=Ga(),Gh=$a(),jh=za(),$h=Ya(),ti=Ja(),ni=Wr(),zh=tl(),ds=ll(),Vh=fl(),Qh=Pe(),Zr=Rl();function Yh(t,e){let n=t.size,s=$h.getPositions(e);for(let r=0;r<s.length;r++){let i=s[r][0],o=s[r][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 Jh(t){let e=t.size;for(let n=8;n<e-8;n++){let s=n%2===0;t.set(n,6,s,!0),t.set(6,n,s,!0)}}function Kh(t,e){let n=jh.getPositions(e);for(let s=0;s<n.length;s++){let r=n[s][0],i=n[s][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(r+o,i+a,!0,!0):t.set(r+o,i+a,!1,!0)}}function Xh(t,e){let n=t.size,s=ds.getEncodedBits(e),r,i,o;for(let a=0;a<18;a++)r=Math.floor(a/3),i=a%3+n-8-3,o=(s>>a&1)===1,t.set(r,i,o,!0),t.set(i,r,o,!0)}function ei(t,e,n){let s=t.size,r=Vh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(r>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(s-15+i,8,o,!0),i<8?t.set(8,s-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(s-8,8,1,!0)}function Zh(t,e){let n=t.size,s=-1,r=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(r,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(r,a-l,u),i--,i===-1&&(o++,i=7)}if(r+=s,r<0||n<=r){r-=s,s=-s;break}}}function eg(t,e,n){let s=new qh;n.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),Qh.getCharCountIndicator(l.mode,t)),l.write(s)});let r=fs.getSymbolTotalCodewords(t),i=ni.getTotalCodewordsCount(t,e),o=(r-i)*8;for(s.getLengthInBits()+4<=o&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let a=(o-s.getLengthInBits())/8;for(let l=0;l<a;l++)s.put(l%2?17:236,8);return tg(s,t,e)}function tg(t,e,n){let s=fs.getSymbolTotalCodewords(e),r=ni.getTotalCodewordsCount(e,n),i=s-r,o=ni.getBlocksCount(e,n),a=s%o,l=o-a,u=Math.floor(s/o),c=Math.floor(i/o),d=c+1,f=u-c,h=new zh(f),g=0,m=new Array(o),p=new Array(o),y=0,C=new Uint8Array(t.buffer);for(let R=0;R<o;R++){let X=R<l?c:d;m[R]=C.slice(g,g+X),p[R]=h.encode(m[R]),g+=X,y=Math.max(y,X)}let A=new Uint8Array(s),T=0,I,D;for(I=0;I<y;I++)for(D=0;D<o;D++)I<m[D].length&&(A[T++]=m[D][I]);for(I=0;I<f;I++)for(D=0;D<o;D++)A[T++]=p[D][I];return A}function ng(t,e,n,s){let r;if(Array.isArray(t))r=Zr.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=Zr.rawSplit(t);u=ds.getBestVersionForData(c,n)}r=Zr.fromString(t,u||40)}else throw new Error("Invalid data");let i=ds.getBestVersionForData(r,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=Zh(e,n,r),a=fs.getSymbolSize(e),l=new qh(a);return Qh(l,e),Yh(l),Jh(l,e),ei(l,n,0),e>=7&&Kh(l,e),Xh(l,o),isNaN(s)&&(s=ti.getBestMask(l,ei.bind(null,l,n))),ti.applyMask(s,l),ei(l,n,s),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:s,segments:r}}Rl.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let s=Xr.M,r,i;return typeof n<"u"&&(s=Xr.from(n.errorCorrectionLevel,Xr.M),r=ds.from(n.version),i=ti.from(n.maskPattern),n.toSJISFunc&&fs.setToSJISFunction(n.toSJISFunc)),tg(e,r,s,i)}});var ri=v((s0,Pl)=>{"use strict";var ng=require("util"),El=require("stream"),ue=Pl.exports=function(){El.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ng.inherits(ue,El);ue.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))};ue.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};ue.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()))};ue.prototype.destroySoon=ue.prototype.end;ue.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ue.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ue.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))};ue.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let r=this._buffers[n++],i=Math.min(r.length,t.length-e);r.copy(s,e,0,i),e+=i,i!==r.length&&(this._buffers[--n]=r.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};ue.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 oi=v(ii=>{"use strict";var Le=[{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]}];ii.getImagePasses=function(t,e){let n=[],s=t%8,r=e%8,i=(t-s)/8,o=(e-r)/8;for(let a=0;a<Le.length;a++){let l=Le[a],u=i*l.x.length,c=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<s;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<r;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};ii.getInterlaceIterator=function(t){return function(e,n,s){let r=e%Le[s].x.length,i=(e-r)/Le[s].x.length*8+Le[s].x[r],o=n%Le[s].y.length,a=(n-o)/Le[s].y.length*8+Le[s].y[o];return i*4+a*t*4}}});var ai=v((i0,Ml)=>{"use strict";Ml.exports=function(e,n,s){let r=e+n-s,i=Math.abs(r-e),o=Math.abs(r-n),a=Math.abs(r-s);return i<=o&&i<=a?e:o<=a?n:s}});var li=v((o0,Nl)=>{"use strict";var sg=oi(),rg=ai();function Ll(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var At=Nl.exports=function(t,e){let n=t.width,s=t.height,r=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=[],r){let a=sg.getImagePasses(n,s);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Ll(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Ll(n,i,o),height:s,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};At.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};At.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,r=s-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>r?e[i-s]:0;e[i]=o+a}};At.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let r=0;r<n;r++){let i=t[1+r],o=s?s[r]:0;e[r]=i+o}};At.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=Math.floor((u+l)/2);e[o]=a+c}};At.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=o>r&&i?i[o-s]:0,d=rg(u,l,c);e[o]=a+d}};At.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],r=s.byteWidth;if(e===0)n=t.slice(1,r+1);else switch(n=Buffer.alloc(r),e){case 1:this._unFilterType1(t,n,r);break;case 2:this._unFilterType2(t,n,r);break;case 3:this._unFilterType3(t,n,r);break;case 4:this._unFilterType4(t,n,r);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Bl=v((a0,Dl)=>{"use strict";var ig=require("util"),Ol=ri(),og=li(),ag=Dl.exports=function(t){Ol.call(this);let e=[],n=this;this._filter=new og(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};ig.inherits(ag,Ol)});var Tt=v((l0,Fl)=>{"use strict";Fl.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 di=v((c0,Hl)=>{"use strict";var ci=[];(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;ci[t]=e}})();var ui=Hl.exports=function(){this._crc=-1};ui.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ci[(this._crc^t[e])&255]^this._crc>>>8;return!0};ui.prototype.crc32=function(){return this._crc^-1};ui.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ci[(e^t[n])&255]^e>>>8;return e^-1}});var fi=v((u0,Ul)=>{"use strict";var U=Tt(),lg=di(),G=Ul.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[U.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[U.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[U.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[U.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[U.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[U.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(){}};G.prototype.start=function(){this.read(U.PNG_SIGNATURE.length,this._parseSignature.bind(this))};G.prototype._parseSignature=function(t){let e=U.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))};G.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let i=4;i<8;i++)s+=String.fromCharCode(t[i]);let r=!!(t[4]&32);if(!this._hasIHDR&&n!==U.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new lg,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!r){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};G.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};G.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};G.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))};G.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};G.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],r=t[9],i=t[10],o=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(r in U.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=r;let l=U.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(r&U.COLORTYPE_PALETTE),color:!!(r&U.COLORTYPE_COLOR),alpha:!!(r&U.COLORTYPE_ALPHA),bpp:l,colorType:r}),this._handleChunkEnd()};G.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};G.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()};G.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};G.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===U.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===U.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===U.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};G.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};G.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/U.GAMMA_DIVISION),this._handleChunkEnd()};G.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};G.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===U.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()};G.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};G.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var pi=v(ql=>{"use strict";var Wl=oi(),cg=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],ug=[function(){},function(t,e,n,s){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function dg(t,e){let n=[],s=0;function r(){if(s===t.length)throw new Error("Ran out of data");let i=t[s];s++;let o,a,l,u,c,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[s],s++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:c=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,c);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,u=i>>3&1,c=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)r();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function fg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<o;c++){let d=n(c,u,l);cg[s](e,r,d,i),i+=s}return i}function pg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<o;c++){let d=r.get(s),f=n(c,u,l);ug[s](e,d,f,i)}r.resetAfterLine()}}ql.dataToBitMap=function(t,e){let n=e.width,s=e.height,r=e.depth,i=e.bpp,o=e.interlace,a;r!==8&&(a=dg(t,r));let l;r<=8?l=Buffer.alloc(n*s*4):l=new Uint16Array(n*s*4);let u=Math.pow(2,r)-1,c=0,d,f;if(o)d=Wl.getImagePasses(n,s),f=Wl.getInterlaceIterator(n,s);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:s}]}for(let h=0;h<d.length;h++)r===8?c=fg(d[h],l,f,i,t,c):pg(d[h],l,f,i,a,u);if(r===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var hi=v((f0,Gl)=>{"use strict";function hg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=r[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function gg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=!1;if(r.length===1?r[0]===t[i]&&(l=!0):r[0]===t[i]&&r[1]===t[i+1]&&r[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function mg(t,e,n,s,r){let i=255,o=Math.pow(2,r)-1,a=0;for(let l=0;l<s;l++)for(let u=0;u<n;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*i/o+.5);a+=4}}Gl.exports=function(t,e){let n=e.depth,s=e.width,r=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?hg(t,l,s,r,a):(o&&gg(t,l,s,r,o),n!==8&&(n===16&&(l=Buffer.alloc(s*r*4)),mg(t,l,s,r,n))),l}});var zl=v((p0,$l)=>{"use strict";var yg=require("util"),gi=require("zlib"),jl=ri(),vg=Bl(),Sg=fi(),_g=pi(),bg=hi(),ge=$l.exports=function(t){jl.call(this),this._parser=new Sg(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()};yg.inherits(ge,jl);ge.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};ge.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=gi.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,s=Math.max(n,gi.Z_MIN_CHUNK);this._inflate=gi.createInflate({chunkSize:s});let r=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){r&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){r&&(a.length>r&&(a=a.slice(0,r)),r-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new vg(this._bitmapInfo)};ge.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ge.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ge.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ge.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ge.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ge.prototype._complete=function(t){if(this.errord)return;let e;try{let n=_g.dataToBitMap(t,this._bitmapInfo);e=bg(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ql=v((h0,Vl)=>{"use strict";var ie=Tt();Vl.exports=function(t,e,n,s){let r=[ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let g=(function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&g)return t}let i=s.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ie.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let l=ie.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=s.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,m,p,y=o;switch(s.inputColorType){case ie.COLORTYPE_COLOR_ALPHA:y=i[c+3],g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_COLOR:g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_ALPHA:y=i[c+1],g=i[c],m=g,p=g;break;case ie.COLORTYPE_GRAYSCALE:g=i[c],m=g,p=g;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(r||(y/=o,g=Math.min(Math.max(Math.round((1-y)*f.red+y*g),0),o),m=Math.min(Math.max(Math.round((1-y)*f.green+y*m),0),o),p=Math.min(Math.max(Math.round((1-y)*f.blue+y*p),0),o))),{red:g,green:m,blue:p,alpha:y}}for(let g=0;g<n;g++)for(let m=0;m<e;m++){let p=h(i,c);switch(s.colorType){case ie.COLORTYPE_COLOR_ALPHA:case ie.COLORTYPE_COLOR:s.bitDepth===8?(u[d]=p.red,u[d+1]=p.green,u[d+2]=p.blue,r&&(u[d+3]=p.alpha)):(u.writeUInt16BE(p.red,d),u.writeUInt16BE(p.green,d+2),u.writeUInt16BE(p.blue,d+4),r&&u.writeUInt16BE(p.alpha,d+6));break;case ie.COLORTYPE_ALPHA:case ie.COLORTYPE_GRAYSCALE:{let y=(p.red+p.green+p.blue)/3;s.bitDepth===8?(u[d]=y,r&&(u[d+1]=p.alpha)):(u.writeUInt16BE(y,d),r&&u.writeUInt16BE(p.alpha,d+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}c+=a,d+=l}return u}});var Kl=v((g0,Jl)=>{"use strict";var Yl=ai();function wg(t,e,n,s,r){for(let i=0;i<n;i++)s[r+i]=t[e+i]}function Ig(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++)s+=Math.abs(t[i]);return s}function Ag(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;s[r+o]=l}}function Tg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=t[e+i]-o;r+=Math.abs(a)}return r}function Cg(t,e,n,s,r){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;s[r+i]=a}}function kg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++){let o=e>0?t[i-n]:0,a=t[i]-o;s+=Math.abs(a)}return s}function xg(t,e,n,s,r,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,u=t[e+o]-(a+l>>1);s[r+o]=u}}function Rg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);r+=Math.abs(l)}return r}function Eg(t,e,n,s,r,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,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-Yl(a,l,u);s[r+o]=c}}function Pg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=s?t[e+i-(n+s)]:0,u=t[e+i]-Yl(o,a,l);r+=Math.abs(u)}return r}var Mg={0:wg,1:Ag,2:Cg,3:xg,4:Eg},Lg={0:Ig,1:Tg,2:kg,3:Rg,4:Pg};Jl.exports=function(t,e,n,s,r){let i;if(!("filterType"in s)||s.filterType===-1)i=[0,1,2,3,4];else if(typeof s.filterType=="number")i=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(r*=2);let o=e*r,a=0,l=0,u=Buffer.alloc((o+1)*n),c=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=Lg[i[h]](t,l,o,r);g<f&&(c=i[h],f=g)}}u[a]=c,a++,Mg[c](t,l,o,u,a,r),a+=o,l+=o}return u}});var mi=v((m0,Xl)=>{"use strict";var V=Tt(),Ng=di(),Og=Ql(),Dg=Kl(),Bg=require("zlib"),Ne=Xl.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||Bg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:V.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:V.COLORTYPE_COLOR_ALPHA,[V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.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")};Ne.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ne.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ne.prototype.filterData=function(t,e,n){let s=Og(t,e,n,this._options),r=V.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Dg(s,e,n,this._options,r)};Ne.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(Ng.crc32(s.slice(4,s.length-4)),s.length-4),s};Ne.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*V.GAMMA_DIVISION),0),this._packChunk(V.TYPE_gAMA,e)};Ne.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(V.TYPE_IHDR,n)};Ne.prototype.packIDAT=function(t){return this._packChunk(V.TYPE_IDAT,t)};Ne.prototype.packIEND=function(){return this._packChunk(V.TYPE_IEND,null)}});var nc=v((y0,tc)=>{"use strict";var Fg=require("util"),Zl=require("stream"),Hg=Tt(),Ug=mi(),ec=tc.exports=function(t){Zl.call(this);let e=t||{};this._packer=new Ug(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Fg.inherits(ec,Zl);ec.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(Hg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let r=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(r)}});var lc=v((un,ac)=>{"use strict";var sc=require("assert").ok,Ct=require("zlib"),Wg=require("util"),rc=require("buffer").kMaxLength;function Je(t){if(!(this instanceof Je))return new Je(t);t&&t.chunkSize<Ct.Z_MIN_CHUNK&&(t.chunkSize=Ct.Z_MIN_CHUNK),Ct.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function qg(t){return new Je(t)}function ic(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Je.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ct.Inflate._processChunk.call(this,t,e,n);let s=this,r=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(g){c=g});function d(g,m){if(s._hadError)return;let p=i-m;if(sc(p>=0,"have should not go down"),p>0){let y=s._buffer.slice(s._offset,s._offset+p);if(s._offset+=p,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(m===0||s._offset>=s._chunkSize)&&(i=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),m===0?(a+=r-g,r=g,!0):!1}sc(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,r,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=rc)throw ic(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+rc.toString(16)+" bytes");let h=Buffer.concat(l,u);return ic(this),h};Wg.inherits(Je,Ct.Inflate);function Gg(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Ct.Z_FINISH),t._processChunk(e,n)}function oc(t,e){return Gg(new Je(e),t)}ac.exports=un=oc;un.Inflate=Je;un.createInflate=qg;un.inflateSync=oc});var yi=v((v0,uc)=>{"use strict";var cc=uc.exports=function(t){this._buffer=t,this._reads=[]};cc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};cc.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 fc=v(dc=>{"use strict";var jg=yi(),$g=li();dc.process=function(t,e){let n=[],s=new jg(t);return new $g(e,{read:s.read.bind(s),write:function(i){n.push(i)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var mc=v((_0,gc)=>{"use strict";var pc=!0,hc=require("zlib"),zg=lc();hc.deflateSync||(pc=!1);var Vg=yi(),Qg=fc(),Yg=fi(),Jg=pi(),Kg=hi();gc.exports=function(t,e){if(!pc)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 s(T){n=T}let r;function i(T){r=T}function o(T){r.transColor=T}function a(T){r.palette=T}function l(){r.alpha=!0}let u;function c(T){u=T}let d=[];function f(T){d.push(T)}let h=new Vg(t);if(new Yg(e,{read:h.read.bind(h),error:s,metadata:i,gamma:c,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let m=Buffer.concat(d);d.length=0;let p;if(r.interlace)p=hc.inflateSync(m);else{let I=((r.width*r.bpp*r.depth+7>>3)+1)*r.height;p=zg(m,{chunkSize:I,maxLength:I})}if(m=null,!p||!p.length)throw new Error("bad png - invalid inflate data response");let y=Qg.process(p,r);m=null;let C=Jg.dataToBitMap(y,r);y=null;let A=Kg(C,r);return r.data=A,r.gamma=u||0,r}});var _c=v((b0,Sc)=>{"use strict";var yc=!0,vc=require("zlib");vc.deflateSync||(yc=!1);var Xg=Tt(),Zg=mi();Sc.exports=function(t,e){if(!yc)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||{},s=new Zg(n),r=[];r.push(Buffer.from(Xg.PNG_SIGNATURE)),r.push(s.packIHDR(t.width,t.height)),t.gamma&&r.push(s.packGAMA(t.gamma));let i=s.filterData(t.data,t.width,t.height),o=vc.deflateSync(i,s.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return r.push(s.packIDAT(o)),r.push(s.packIEND()),Buffer.concat(r)}});var bc=v(vi=>{"use strict";var em=mc(),tm=_c();vi.read=function(t,e){return em(t,e||{})};vi.write=function(t,e){return tm(t,e)}});var Ac=v(Ic=>{"use strict";var nm=require("util"),wc=require("stream"),sm=zl(),rm=nc(),im=bc(),Y=Ic.PNG=function(t){wc.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 sm(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 rm(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"))};nm.inherits(Y,wc);Y.sync=im;Y.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)};Y.prototype.parse=function(t,e){if(e){let n,s;n=function(r){this.removeListener("error",s),this.data=r,e(null,this)}.bind(this),s=function(r){this.removeListener("parsed",n),e(r,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};Y.prototype.write=function(t){return this._parser.write(t),!0};Y.prototype.end=function(t){this._parser.end(t)};Y.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Y.prototype._gamma=function(t){this.gamma=t};Y.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Y.bitblt=function(t,e,n,s,r,i,o,a){if(n|=0,s|=0,r|=0,i|=0,o|=0,a|=0,n>t.width||s>t.height||n+r>t.width||s+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+r>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,(s+l)*t.width+n<<2,(s+l)*t.width+n+r<<2)};Y.prototype.bitblt=function(t,e,n,s,r,i,o){return Y.bitblt(this,t,e,n,s,r,i,o),this};Y.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let s=t.width*e+n<<2;for(let r=0;r<3;r++){let i=t.data[s+r]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[s+r]=Math.round(i*255)}}t.gamma=0}};Y.prototype.adjustGamma=function(){Y.adjustGamma(this)}});var dn=v(Ke=>{function Tc(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(s){return[s,s]}))),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("")}}Ke.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,r=e.scale||4;return{width:s,scale:s?4:r,margin:n,color:{dark:Tc(e.color.dark||"#000000ff"),light:Tc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ke.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ke.getImageWidth=function(e,n){let s=Ke.getScale(e,n);return Math.floor((e+n.margin*2)*s)};Ke.qrToImageData=function(e,n,s){let r=n.modules.size,i=n.modules.data,o=Ke.getScale(r,s),a=Math.floor((r+s.margin*2)*o),l=s.margin*o,u=[s.color.light,s.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let f=(c*a+d)*4,h=s.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let g=Math.floor((c-l)/o),m=Math.floor((d-l)/o);h=u[i[g*r+m]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Cc=v(me=>{var om=require("fs"),am=Ac().PNG,Si=dn();me.render=function(e,n){let s=Si.getOptions(n),r=s.rendererOpts,i=Si.getImageWidth(e.modules.size,s);r.width=i,r.height=i;let o=new am(r);return Si.qrToImageData(o.data,e,s),o};me.renderToDataURL=function(e,n,s){typeof s>"u"&&(s=n,n=void 0),me.renderToBuffer(e,n,function(r,i){r&&s(r);let o="data:image/png;base64,";o+=i.toString("base64"),s(null,o)})};me.renderToBuffer=function(e,n,s){typeof s>"u"&&(s=n,n=void 0);let r=me.render(e,n),i=[];r.on("error",s),r.on("data",function(o){i.push(o)}),r.on("end",function(){s(null,Buffer.concat(i))}),r.pack()};me.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=!1,o=(...l)=>{i||(i=!0,r.apply(null,l))},a=om.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,s)};me.renderToFileStream=function(e,n,s){me.render(n,s).pack().pipe(e)}});var kc=v(ps=>{var lm=dn(),cm={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},um={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function dm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}ps.render=function(t,e,n){let s=lm.getOptions(e),r=cm;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(r=um);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+s.margin*2+1).join(r.WW);l=Array(s.margin/2+1).join(l+`
14
- `);let u=Array(s.margin+1).join(r.WW);a+=l;for(let c=0;c<i;c+=2){a+=u;for(let d=0;d<i;d++){let f=o[c*i+d],h=o[(c+1)*i+d];a+=dm(f,h,r)}a+=u+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};ps.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),o=ps.render(n,s);i.writeFile(e,o,r)}});var Rc=v(xc=>{xc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(s+3).join(o),u=Array(2).join(o);a+=l+`
13
+ `);let o=eg(e,n,r),a=fs.getSymbolSize(e),l=new Gh(a);return Yh(l,e),Jh(l),Kh(l,e),ei(l,n,0),e>=7&&Xh(l,e),Zh(l,o),isNaN(s)&&(s=ti.getBestMask(l,ei.bind(null,l,n))),ti.applyMask(s,l),ei(l,n,s),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:s,segments:r}}El.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let s=Xr.M,r,i;return typeof n<"u"&&(s=Xr.from(n.errorCorrectionLevel,Xr.M),r=ds.from(n.version),i=ti.from(n.maskPattern),n.toSJISFunc&&fs.setToSJISFunction(n.toSJISFunc)),ng(e,r,s,i)}});var ri=v((i0,Ml)=>{"use strict";var sg=require("util"),Pl=require("stream"),ue=Ml.exports=function(){Pl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};sg.inherits(ue,Pl);ue.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))};ue.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};ue.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()))};ue.prototype.destroySoon=ue.prototype.end;ue.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ue.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ue.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))};ue.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let r=this._buffers[n++],i=Math.min(r.length,t.length-e);r.copy(s,e,0,i),e+=i,i!==r.length&&(this._buffers[--n]=r.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};ue.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 oi=v(ii=>{"use strict";var Le=[{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]}];ii.getImagePasses=function(t,e){let n=[],s=t%8,r=e%8,i=(t-s)/8,o=(e-r)/8;for(let a=0;a<Le.length;a++){let l=Le[a],u=i*l.x.length,c=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<s;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<r;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};ii.getInterlaceIterator=function(t){return function(e,n,s){let r=e%Le[s].x.length,i=(e-r)/Le[s].x.length*8+Le[s].x[r],o=n%Le[s].y.length,a=(n-o)/Le[s].y.length*8+Le[s].y[o];return i*4+a*t*4}}});var ai=v((a0,Ll)=>{"use strict";Ll.exports=function(e,n,s){let r=e+n-s,i=Math.abs(r-e),o=Math.abs(r-n),a=Math.abs(r-s);return i<=o&&i<=a?e:o<=a?n:s}});var li=v((l0,Ol)=>{"use strict";var rg=oi(),ig=ai();function Nl(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var At=Ol.exports=function(t,e){let n=t.width,s=t.height,r=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=[],r){let a=rg.getImagePasses(n,s);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Nl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Nl(n,i,o),height:s,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};At.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};At.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,r=s-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>r?e[i-s]:0;e[i]=o+a}};At.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let r=0;r<n;r++){let i=t[1+r],o=s?s[r]:0;e[r]=i+o}};At.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=Math.floor((u+l)/2);e[o]=a+c}};At.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=o>r&&i?i[o-s]:0,d=ig(u,l,c);e[o]=a+d}};At.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],r=s.byteWidth;if(e===0)n=t.slice(1,r+1);else switch(n=Buffer.alloc(r),e){case 1:this._unFilterType1(t,n,r);break;case 2:this._unFilterType2(t,n,r);break;case 3:this._unFilterType3(t,n,r);break;case 4:this._unFilterType4(t,n,r);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Fl=v((c0,Bl)=>{"use strict";var og=require("util"),Dl=ri(),ag=li(),lg=Bl.exports=function(t){Dl.call(this);let e=[],n=this;this._filter=new ag(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};og.inherits(lg,Dl)});var Tt=v((u0,Hl)=>{"use strict";Hl.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 di=v((d0,Ul)=>{"use strict";var ci=[];(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;ci[t]=e}})();var ui=Ul.exports=function(){this._crc=-1};ui.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ci[(this._crc^t[e])&255]^this._crc>>>8;return!0};ui.prototype.crc32=function(){return this._crc^-1};ui.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ci[(e^t[n])&255]^e>>>8;return e^-1}});var fi=v((f0,Wl)=>{"use strict";var W=Tt(),cg=di(),j=Wl.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[W.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[W.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[W.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[W.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[W.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[W.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(){}};j.prototype.start=function(){this.read(W.PNG_SIGNATURE.length,this._parseSignature.bind(this))};j.prototype._parseSignature=function(t){let e=W.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))};j.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let i=4;i<8;i++)s+=String.fromCharCode(t[i]);let r=!!(t[4]&32);if(!this._hasIHDR&&n!==W.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new cg,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!r){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};j.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};j.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};j.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))};j.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};j.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],r=t[9],i=t[10],o=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(r in W.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=r;let l=W.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(r&W.COLORTYPE_PALETTE),color:!!(r&W.COLORTYPE_COLOR),alpha:!!(r&W.COLORTYPE_ALPHA),bpp:l,colorType:r}),this._handleChunkEnd()};j.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};j.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()};j.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};j.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===W.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===W.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===W.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};j.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};j.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/W.GAMMA_DIVISION),this._handleChunkEnd()};j.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};j.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===W.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()};j.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};j.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var pi=v(Gl=>{"use strict";var ql=oi(),ug=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],dg=[function(){},function(t,e,n,s){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function fg(t,e){let n=[],s=0;function r(){if(s===t.length)throw new Error("Ran out of data");let i=t[s];s++;let o,a,l,u,c,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[s],s++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:c=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,c);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,u=i>>3&1,c=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)r();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function pg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<o;c++){let d=n(c,u,l);ug[s](e,r,d,i),i+=s}return i}function hg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<o;c++){let d=r.get(s),f=n(c,u,l);dg[s](e,d,f,i)}r.resetAfterLine()}}Gl.dataToBitMap=function(t,e){let n=e.width,s=e.height,r=e.depth,i=e.bpp,o=e.interlace,a;r!==8&&(a=fg(t,r));let l;r<=8?l=Buffer.alloc(n*s*4):l=new Uint16Array(n*s*4);let u=Math.pow(2,r)-1,c=0,d,f;if(o)d=ql.getImagePasses(n,s),f=ql.getInterlaceIterator(n,s);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:s}]}for(let h=0;h<d.length;h++)r===8?c=pg(d[h],l,f,i,t,c):hg(d[h],l,f,i,a,u);if(r===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var hi=v((h0,jl)=>{"use strict";function gg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=r[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function mg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=!1;if(r.length===1?r[0]===t[i]&&(l=!0):r[0]===t[i]&&r[1]===t[i+1]&&r[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function yg(t,e,n,s,r){let i=255,o=Math.pow(2,r)-1,a=0;for(let l=0;l<s;l++)for(let u=0;u<n;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*i/o+.5);a+=4}}jl.exports=function(t,e){let n=e.depth,s=e.width,r=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?gg(t,l,s,r,a):(o&&mg(t,l,s,r,o),n!==8&&(n===16&&(l=Buffer.alloc(s*r*4)),yg(t,l,s,r,n))),l}});var Vl=v((g0,zl)=>{"use strict";var vg=require("util"),gi=require("zlib"),$l=ri(),Sg=Fl(),_g=fi(),bg=pi(),wg=hi(),ge=zl.exports=function(t){$l.call(this),this._parser=new _g(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()};vg.inherits(ge,$l);ge.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};ge.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=gi.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,s=Math.max(n,gi.Z_MIN_CHUNK);this._inflate=gi.createInflate({chunkSize:s});let r=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){r&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){r&&(a.length>r&&(a=a.slice(0,r)),r-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Sg(this._bitmapInfo)};ge.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ge.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ge.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ge.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ge.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ge.prototype._complete=function(t){if(this.errord)return;let e;try{let n=bg.dataToBitMap(t,this._bitmapInfo);e=wg(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Yl=v((m0,Ql)=>{"use strict";var ie=Tt();Ql.exports=function(t,e,n,s){let r=[ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let g=(function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&g)return t}let i=s.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ie.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let l=ie.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=s.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,m,p,y=o;switch(s.inputColorType){case ie.COLORTYPE_COLOR_ALPHA:y=i[c+3],g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_COLOR:g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_ALPHA:y=i[c+1],g=i[c],m=g,p=g;break;case ie.COLORTYPE_GRAYSCALE:g=i[c],m=g,p=g;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(r||(y/=o,g=Math.min(Math.max(Math.round((1-y)*f.red+y*g),0),o),m=Math.min(Math.max(Math.round((1-y)*f.green+y*m),0),o),p=Math.min(Math.max(Math.round((1-y)*f.blue+y*p),0),o))),{red:g,green:m,blue:p,alpha:y}}for(let g=0;g<n;g++)for(let m=0;m<e;m++){let p=h(i,c);switch(s.colorType){case ie.COLORTYPE_COLOR_ALPHA:case ie.COLORTYPE_COLOR:s.bitDepth===8?(u[d]=p.red,u[d+1]=p.green,u[d+2]=p.blue,r&&(u[d+3]=p.alpha)):(u.writeUInt16BE(p.red,d),u.writeUInt16BE(p.green,d+2),u.writeUInt16BE(p.blue,d+4),r&&u.writeUInt16BE(p.alpha,d+6));break;case ie.COLORTYPE_ALPHA:case ie.COLORTYPE_GRAYSCALE:{let y=(p.red+p.green+p.blue)/3;s.bitDepth===8?(u[d]=y,r&&(u[d+1]=p.alpha)):(u.writeUInt16BE(y,d),r&&u.writeUInt16BE(p.alpha,d+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}c+=a,d+=l}return u}});var Xl=v((y0,Kl)=>{"use strict";var Jl=ai();function Ig(t,e,n,s,r){for(let i=0;i<n;i++)s[r+i]=t[e+i]}function Ag(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++)s+=Math.abs(t[i]);return s}function Tg(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;s[r+o]=l}}function Cg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=t[e+i]-o;r+=Math.abs(a)}return r}function kg(t,e,n,s,r){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;s[r+i]=a}}function xg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++){let o=e>0?t[i-n]:0,a=t[i]-o;s+=Math.abs(a)}return s}function Rg(t,e,n,s,r,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,u=t[e+o]-(a+l>>1);s[r+o]=u}}function Eg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);r+=Math.abs(l)}return r}function Pg(t,e,n,s,r,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,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-Jl(a,l,u);s[r+o]=c}}function Mg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=s?t[e+i-(n+s)]:0,u=t[e+i]-Jl(o,a,l);r+=Math.abs(u)}return r}var Lg={0:Ig,1:Tg,2:kg,3:Rg,4:Pg},Ng={0:Ag,1:Cg,2:xg,3:Eg,4:Mg};Kl.exports=function(t,e,n,s,r){let i;if(!("filterType"in s)||s.filterType===-1)i=[0,1,2,3,4];else if(typeof s.filterType=="number")i=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(r*=2);let o=e*r,a=0,l=0,u=Buffer.alloc((o+1)*n),c=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=Ng[i[h]](t,l,o,r);g<f&&(c=i[h],f=g)}}u[a]=c,a++,Lg[c](t,l,o,u,a,r),a+=o,l+=o}return u}});var mi=v((v0,Zl)=>{"use strict";var V=Tt(),Og=di(),Dg=Yl(),Bg=Xl(),Fg=require("zlib"),Ne=Zl.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||Fg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:V.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:V.COLORTYPE_COLOR_ALPHA,[V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.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")};Ne.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ne.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ne.prototype.filterData=function(t,e,n){let s=Dg(t,e,n,this._options),r=V.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Bg(s,e,n,this._options,r)};Ne.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(Og.crc32(s.slice(4,s.length-4)),s.length-4),s};Ne.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*V.GAMMA_DIVISION),0),this._packChunk(V.TYPE_gAMA,e)};Ne.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(V.TYPE_IHDR,n)};Ne.prototype.packIDAT=function(t){return this._packChunk(V.TYPE_IDAT,t)};Ne.prototype.packIEND=function(){return this._packChunk(V.TYPE_IEND,null)}});var sc=v((S0,nc)=>{"use strict";var Hg=require("util"),ec=require("stream"),Ug=Tt(),Wg=mi(),tc=nc.exports=function(t){ec.call(this);let e=t||{};this._packer=new Wg(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Hg.inherits(tc,ec);tc.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(Ug.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let r=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(r)}});var cc=v((un,lc)=>{"use strict";var rc=require("assert").ok,Ct=require("zlib"),qg=require("util"),ic=require("buffer").kMaxLength;function Je(t){if(!(this instanceof Je))return new Je(t);t&&t.chunkSize<Ct.Z_MIN_CHUNK&&(t.chunkSize=Ct.Z_MIN_CHUNK),Ct.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Gg(t){return new Je(t)}function oc(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Je.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ct.Inflate._processChunk.call(this,t,e,n);let s=this,r=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(g){c=g});function d(g,m){if(s._hadError)return;let p=i-m;if(rc(p>=0,"have should not go down"),p>0){let y=s._buffer.slice(s._offset,s._offset+p);if(s._offset+=p,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(m===0||s._offset>=s._chunkSize)&&(i=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),m===0?(a+=r-g,r=g,!0):!1}rc(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,r,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=ic)throw oc(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+ic.toString(16)+" bytes");let h=Buffer.concat(l,u);return oc(this),h};qg.inherits(Je,Ct.Inflate);function jg(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Ct.Z_FINISH),t._processChunk(e,n)}function ac(t,e){return jg(new Je(e),t)}lc.exports=un=ac;un.Inflate=Je;un.createInflate=Gg;un.inflateSync=ac});var yi=v((_0,dc)=>{"use strict";var uc=dc.exports=function(t){this._buffer=t,this._reads=[]};uc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};uc.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 pc=v(fc=>{"use strict";var $g=yi(),zg=li();fc.process=function(t,e){let n=[],s=new $g(t);return new zg(e,{read:s.read.bind(s),write:function(i){n.push(i)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var yc=v((w0,mc)=>{"use strict";var hc=!0,gc=require("zlib"),Vg=cc();gc.deflateSync||(hc=!1);var Qg=yi(),Yg=pc(),Jg=fi(),Kg=pi(),Xg=hi();mc.exports=function(t,e){if(!hc)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 s(T){n=T}let r;function i(T){r=T}function o(T){r.transColor=T}function a(T){r.palette=T}function l(){r.alpha=!0}let u;function c(T){u=T}let d=[];function f(T){d.push(T)}let h=new Qg(t);if(new Jg(e,{read:h.read.bind(h),error:s,metadata:i,gamma:c,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let m=Buffer.concat(d);d.length=0;let p;if(r.interlace)p=gc.inflateSync(m);else{let I=((r.width*r.bpp*r.depth+7>>3)+1)*r.height;p=Vg(m,{chunkSize:I,maxLength:I})}if(m=null,!p||!p.length)throw new Error("bad png - invalid inflate data response");let y=Yg.process(p,r);m=null;let C=Kg.dataToBitMap(y,r);y=null;let A=Xg(C,r);return r.data=A,r.gamma=u||0,r}});var bc=v((I0,_c)=>{"use strict";var vc=!0,Sc=require("zlib");Sc.deflateSync||(vc=!1);var Zg=Tt(),em=mi();_c.exports=function(t,e){if(!vc)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||{},s=new em(n),r=[];r.push(Buffer.from(Zg.PNG_SIGNATURE)),r.push(s.packIHDR(t.width,t.height)),t.gamma&&r.push(s.packGAMA(t.gamma));let i=s.filterData(t.data,t.width,t.height),o=Sc.deflateSync(i,s.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return r.push(s.packIDAT(o)),r.push(s.packIEND()),Buffer.concat(r)}});var wc=v(vi=>{"use strict";var tm=yc(),nm=bc();vi.read=function(t,e){return tm(t,e||{})};vi.write=function(t,e){return nm(t,e)}});var Tc=v(Ac=>{"use strict";var sm=require("util"),Ic=require("stream"),rm=Vl(),im=sc(),om=wc(),Y=Ac.PNG=function(t){Ic.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 rm(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 im(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"))};sm.inherits(Y,Ic);Y.sync=om;Y.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)};Y.prototype.parse=function(t,e){if(e){let n,s;n=function(r){this.removeListener("error",s),this.data=r,e(null,this)}.bind(this),s=function(r){this.removeListener("parsed",n),e(r,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};Y.prototype.write=function(t){return this._parser.write(t),!0};Y.prototype.end=function(t){this._parser.end(t)};Y.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Y.prototype._gamma=function(t){this.gamma=t};Y.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Y.bitblt=function(t,e,n,s,r,i,o,a){if(n|=0,s|=0,r|=0,i|=0,o|=0,a|=0,n>t.width||s>t.height||n+r>t.width||s+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+r>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,(s+l)*t.width+n<<2,(s+l)*t.width+n+r<<2)};Y.prototype.bitblt=function(t,e,n,s,r,i,o){return Y.bitblt(this,t,e,n,s,r,i,o),this};Y.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let s=t.width*e+n<<2;for(let r=0;r<3;r++){let i=t.data[s+r]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[s+r]=Math.round(i*255)}}t.gamma=0}};Y.prototype.adjustGamma=function(){Y.adjustGamma(this)}});var dn=v(Ke=>{function Cc(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(s){return[s,s]}))),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("")}}Ke.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,r=e.scale||4;return{width:s,scale:s?4:r,margin:n,color:{dark:Cc(e.color.dark||"#000000ff"),light:Cc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ke.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ke.getImageWidth=function(e,n){let s=Ke.getScale(e,n);return Math.floor((e+n.margin*2)*s)};Ke.qrToImageData=function(e,n,s){let r=n.modules.size,i=n.modules.data,o=Ke.getScale(r,s),a=Math.floor((r+s.margin*2)*o),l=s.margin*o,u=[s.color.light,s.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let f=(c*a+d)*4,h=s.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let g=Math.floor((c-l)/o),m=Math.floor((d-l)/o);h=u[i[g*r+m]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var kc=v(me=>{var am=require("fs"),lm=Tc().PNG,Si=dn();me.render=function(e,n){let s=Si.getOptions(n),r=s.rendererOpts,i=Si.getImageWidth(e.modules.size,s);r.width=i,r.height=i;let o=new lm(r);return Si.qrToImageData(o.data,e,s),o};me.renderToDataURL=function(e,n,s){typeof s>"u"&&(s=n,n=void 0),me.renderToBuffer(e,n,function(r,i){r&&s(r);let o="data:image/png;base64,";o+=i.toString("base64"),s(null,o)})};me.renderToBuffer=function(e,n,s){typeof s>"u"&&(s=n,n=void 0);let r=me.render(e,n),i=[];r.on("error",s),r.on("data",function(o){i.push(o)}),r.on("end",function(){s(null,Buffer.concat(i))}),r.pack()};me.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=!1,o=(...l)=>{i||(i=!0,r.apply(null,l))},a=am.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,s)};me.renderToFileStream=function(e,n,s){me.render(n,s).pack().pipe(e)}});var xc=v(ps=>{var cm=dn(),um={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},dm={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function fm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}ps.render=function(t,e,n){let s=cm.getOptions(e),r=um;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(r=dm);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+s.margin*2+1).join(r.WW);l=Array(s.margin/2+1).join(l+`
14
+ `);let u=Array(s.margin+1).join(r.WW);a+=l;for(let c=0;c<i;c+=2){a+=u;for(let d=0;d<i;d++){let f=o[c*i+d],h=o[(c+1)*i+d];a+=fm(f,h,r)}a+=u+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};ps.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),o=ps.render(n,s);i.writeFile(e,o,r)}});var Ec=v(Rc=>{Rc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(s+3).join(o),u=Array(2).join(o);a+=l+`
16
16
  `;for(let c=0;c<s;++c){a+=o;for(let d=0;d<s;d++)a+=r[c*s+d]?i:o;a+=u+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var Lc=v(Mc=>{var fm="\x1B[47m",pm="\x1B[40m",_i="\x1B[37m",bi="\x1B[30m",Xe="\x1B[0m",hm=fm+bi,gm=pm+_i,mm=function(t,e,n){return{"00":Xe+" "+t,"01":Xe+e+"\u2584"+t,"02":Xe+n+"\u2584"+t,10:Xe+e+"\u2580"+t,11:" ",12:"\u2584",20:Xe+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Ec=function(t,e,n,s){let r=e+1;if(n>=r||s>=r||s<-1||n<-1)return"0";if(n>=e||s>=e||s<0||n<0)return"1";let i=s*e+n;return t[i]?"2":"1"},Pc=function(t,e,n,s){return Ec(t,e,n,s)+Ec(t,e,n,s+1)};Mc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?gm:hm,u=mm(o,i?bi:_i,i?_i:bi),c=Xe+`
19
- `+o,d=o;for(let f=-1;f<s+1;f+=2){for(let h=-1;h<s;h++)d+=u[Pc(r,s,h,f)];d+=u[Pc(r,s,s,f)]+c}return d+=Xe,typeof n=="function"&&n(null,d),d}});var Oc=v(Nc=>{var ym=Rc(),vm=Lc();Nc.render=function(t,e,n){return e&&e.small?vm.render(t,e,n):ym.render(t,e,n)}});var Ii=v(Bc=>{var Sm=dn();function Dc(t,e){let n=t.a/255,s=e+'="'+t.hex+'"';return n<1?s+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':s}function wi(t,e,n){let s=t+e;return typeof n<"u"&&(s+=" "+n),s}function _m(t,e,n){let s="",r=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(s+=i?wi("M",l+n,.5+u+n):wi("m",r,0),r=0,i=!1),l+1<e&&t[a+1]||(s+=wi("h",o),o=0)):r++}return s}Bc.render=function(e,n,s){let r=Sm.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+r.margin*2,l=r.color.light.a?"<path "+Dc(r.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+Dc(r.color.dark,"stroke")+' d="'+_m(o,i,r.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(r.width?'width="'+r.width+'" height="'+r.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
- `;return typeof s=="function"&&s(null,f),f}});var Fc=v(hs=>{var bm=Ii();hs.render=bm.render;hs.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=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">'+hs.render(n,s);i.writeFile(e,a,r)}});var Hc=v(gs=>{var Ai=dn();function wm(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 Im(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}gs.render=function(e,n,s){let r=s,i=n;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),n||(i=Im()),r=Ai.getOptions(r);let o=Ai.getImageWidth(e.modules.size,r),a=i.getContext("2d"),l=a.createImageData(o,o);return Ai.qrToImageData(l.data,e,r),wm(a,i,o),a.putImageData(l,0,0),i};gs.renderToDataURL=function(e,n,s){let r=s;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),r||(r={});let i=gs.render(e,n,r),o=r.type||"image/png",a=r.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Wc=v(fn=>{var Am=Fr(),Ti=si(),Uc=Hc(),Tm=Ii();function Ci(t,e,n,s,r){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Am())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(r=n,n=e,e=s=void 0):o===3&&(e.getContext&&typeof r>"u"?(r=s,s=void 0):(r=s,s=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=s=void 0):o===2&&!e.getContext&&(s=n,n=e,e=void 0),new Promise(function(l,u){try{let c=Ti.create(n,s);l(t(c,e,s))}catch(c){u(c)}})}try{let l=Ti.create(n,s);r(null,t(l,e,s))}catch(l){r(l)}}fn.create=Ti.create;fn.toCanvas=Ci.bind(null,Uc.render);fn.toDataURL=Ci.bind(null,Uc.renderToDataURL);fn.toString=Ci.bind(null,function(t,e,n){return Tm.render(t,n)})});var $c=v(Oe=>{var qc=Fr(),ki=si(),Cm=Cc(),Gc=kc(),km=Oc(),jc=Fc();function pn(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(qc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function xm(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function ms(t){switch(t){case"svg":return jc;case"txt":case"utf8":return Gc;case"png":case"image/png":default:return Cm}}function Rm(t){switch(t){case"svg":return jc;case"terminal":return km;case"utf8":default:return Gc}}function hn(t,e,n){if(!n.cb)return new Promise(function(s,r){try{let i=ki.create(e,n.opts);return t(i,n.opts,function(o,a){return o?r(o):s(a)})}catch(i){r(i)}});try{let s=ki.create(e,n.opts);return t(s,n.opts,n.cb)}catch(s){n.cb(s)}}Oe.create=ki.create;Oe.toCanvas=Wc().toCanvas;Oe.toString=function(e,n,s){let r=pn(e,n,s),i=r.opts?r.opts.type:void 0,o=Rm(i);return hn(o.render,e,r)};Oe.toDataURL=function(e,n,s){let r=pn(e,n,s),i=ms(r.opts.type);return hn(i.renderToDataURL,e,r)};Oe.toBuffer=function(e,n,s){let r=pn(e,n,s),i=ms(r.opts.type);return hn(i.renderToBuffer,e,r)};Oe.toFile=function(e,n,s,r){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!qc())throw new Error("Too few arguments provided");let i=pn(n,s,r),o=i.opts.type||xm(e),l=ms(o).renderToFile.bind(null,e);return hn(l,n,i)};Oe.toFileStream=function(e,n,s){if(arguments.length<2)throw new Error("Too few arguments provided");let r=pn(n,s,e.emit.bind(e,"error")),o=ms("png").renderToFileStream.bind(null,e);hn(o,n,r)}});var Vc=v((O0,zc)=>{zc.exports=$c()});var Nf=require("http");var dh=dt(Ra(),1),fh=dt(Cr(),1),ph=dt(Rr(),1),hh=dt(ts(),1),Br=dt(Fa(),1);var le=require("fs/promises"),Of=require("crypto"),Vt=require("path"),Df=require("os"),Lo=dt(Vc(),1);var Ze=require("child_process"),xt=require("fs"),E=require("path"),yn=require("os");var As=require("fs");var Qc=require("os"),Q=require("path"),Ie=(0,Q.join)((0,Qc.homedir)(),".vibelet"),ys=(0,Q.join)(Ie,"logs"),vs=(0,Q.join)(Ie,"data"),Em=(0,Q.join)(Ie,"runtime"),D0=(0,Q.join)(Em,"current"),Yc=(0,Q.join)(Ie,"identity.json"),Jc=(0,Q.join)(Ie,"pairings.json"),Kc=(0,Q.join)(vs,"push-subscriptions.json"),Ss=(0,Q.join)(vs,"sessions.json"),De=(0,Q.join)(vs,"audit.jsonl"),xi=(0,Q.join)(vs,"uploads"),_s=(0,Q.join)(ys,"daemon.stdout.log"),bs=(0,Q.join)(ys,"daemon.stderr.log"),Xc=(0,Q.join)(Ie,"update-check.json"),Ri=(0,Q.join)(Ie,"pairing-qr.png");var ws={stdout:!1,stderr:!1};function Zc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Pm(t){return!t.destroyed&&t.writable!==!1}function eu(t,e){if(ws[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Pm(n))return ws[t]=!0,!1;try{return n.write(e,s=>{Zc(s)&&(ws[t]=!0)}),!0}catch(s){return Zc(s)&&(ws[t]=!0),!1}}function kt(t){return eu("stdout",t)}function Is(t){return eu("stderr",t)}var tu={debug:10,info:20,warn:30,error:40},Mm=process.env.VIBE_LOG_LEVEL||"info";function Lm(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Nm(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var su=!Lm()&&!Nm();if(su)try{(0,As.mkdirSync)(ys,{recursive:!0})}catch{}function nu(t,e,n){if(tu[t]<tu[Mm])return;let s={level:t,ts:new Date().toISOString(),msg:n,...e},r=JSON.stringify(s);if(t==="error"||t==="warn"?Is(r+`
18
+ `,typeof n=="function"&&n(null,a),a}});var Nc=v(Lc=>{var pm="\x1B[47m",hm="\x1B[40m",_i="\x1B[37m",bi="\x1B[30m",Xe="\x1B[0m",gm=pm+bi,mm=hm+_i,ym=function(t,e,n){return{"00":Xe+" "+t,"01":Xe+e+"\u2584"+t,"02":Xe+n+"\u2584"+t,10:Xe+e+"\u2580"+t,11:" ",12:"\u2584",20:Xe+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Pc=function(t,e,n,s){let r=e+1;if(n>=r||s>=r||s<-1||n<-1)return"0";if(n>=e||s>=e||s<0||n<0)return"1";let i=s*e+n;return t[i]?"2":"1"},Mc=function(t,e,n,s){return Pc(t,e,n,s)+Pc(t,e,n,s+1)};Lc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?mm:gm,u=ym(o,i?bi:_i,i?_i:bi),c=Xe+`
19
+ `+o,d=o;for(let f=-1;f<s+1;f+=2){for(let h=-1;h<s;h++)d+=u[Mc(r,s,h,f)];d+=u[Mc(r,s,s,f)]+c}return d+=Xe,typeof n=="function"&&n(null,d),d}});var Dc=v(Oc=>{var vm=Ec(),Sm=Nc();Oc.render=function(t,e,n){return e&&e.small?Sm.render(t,e,n):vm.render(t,e,n)}});var Ii=v(Fc=>{var _m=dn();function Bc(t,e){let n=t.a/255,s=e+'="'+t.hex+'"';return n<1?s+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':s}function wi(t,e,n){let s=t+e;return typeof n<"u"&&(s+=" "+n),s}function bm(t,e,n){let s="",r=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(s+=i?wi("M",l+n,.5+u+n):wi("m",r,0),r=0,i=!1),l+1<e&&t[a+1]||(s+=wi("h",o),o=0)):r++}return s}Fc.render=function(e,n,s){let r=_m.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+r.margin*2,l=r.color.light.a?"<path "+Bc(r.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+Bc(r.color.dark,"stroke")+' d="'+bm(o,i,r.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(r.width?'width="'+r.width+'" height="'+r.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
+ `;return typeof s=="function"&&s(null,f),f}});var Hc=v(hs=>{var wm=Ii();hs.render=wm.render;hs.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=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">'+hs.render(n,s);i.writeFile(e,a,r)}});var Uc=v(gs=>{var Ai=dn();function Im(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 Am(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}gs.render=function(e,n,s){let r=s,i=n;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),n||(i=Am()),r=Ai.getOptions(r);let o=Ai.getImageWidth(e.modules.size,r),a=i.getContext("2d"),l=a.createImageData(o,o);return Ai.qrToImageData(l.data,e,r),Im(a,i,o),a.putImageData(l,0,0),i};gs.renderToDataURL=function(e,n,s){let r=s;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),r||(r={});let i=gs.render(e,n,r),o=r.type||"image/png",a=r.rendererOpts||{};return i.toDataURL(o,a.quality)}});var qc=v(fn=>{var Tm=Fr(),Ti=si(),Wc=Uc(),Cm=Ii();function Ci(t,e,n,s,r){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Tm())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(r=n,n=e,e=s=void 0):o===3&&(e.getContext&&typeof r>"u"?(r=s,s=void 0):(r=s,s=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=s=void 0):o===2&&!e.getContext&&(s=n,n=e,e=void 0),new Promise(function(l,u){try{let c=Ti.create(n,s);l(t(c,e,s))}catch(c){u(c)}})}try{let l=Ti.create(n,s);r(null,t(l,e,s))}catch(l){r(l)}}fn.create=Ti.create;fn.toCanvas=Ci.bind(null,Wc.render);fn.toDataURL=Ci.bind(null,Wc.renderToDataURL);fn.toString=Ci.bind(null,function(t,e,n){return Cm.render(t,n)})});var zc=v(Oe=>{var Gc=Fr(),ki=si(),km=kc(),jc=xc(),xm=Dc(),$c=Hc();function pn(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(Gc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Rm(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function ms(t){switch(t){case"svg":return $c;case"txt":case"utf8":return jc;case"png":case"image/png":default:return km}}function Em(t){switch(t){case"svg":return $c;case"terminal":return xm;case"utf8":default:return jc}}function hn(t,e,n){if(!n.cb)return new Promise(function(s,r){try{let i=ki.create(e,n.opts);return t(i,n.opts,function(o,a){return o?r(o):s(a)})}catch(i){r(i)}});try{let s=ki.create(e,n.opts);return t(s,n.opts,n.cb)}catch(s){n.cb(s)}}Oe.create=ki.create;Oe.toCanvas=qc().toCanvas;Oe.toString=function(e,n,s){let r=pn(e,n,s),i=r.opts?r.opts.type:void 0,o=Em(i);return hn(o.render,e,r)};Oe.toDataURL=function(e,n,s){let r=pn(e,n,s),i=ms(r.opts.type);return hn(i.renderToDataURL,e,r)};Oe.toBuffer=function(e,n,s){let r=pn(e,n,s),i=ms(r.opts.type);return hn(i.renderToBuffer,e,r)};Oe.toFile=function(e,n,s,r){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Gc())throw new Error("Too few arguments provided");let i=pn(n,s,r),o=i.opts.type||Rm(e),l=ms(o).renderToFile.bind(null,e);return hn(l,n,i)};Oe.toFileStream=function(e,n,s){if(arguments.length<2)throw new Error("Too few arguments provided");let r=pn(n,s,e.emit.bind(e,"error")),o=ms("png").renderToFileStream.bind(null,e);hn(o,n,r)}});var Qc=v((B0,Vc)=>{Vc.exports=zc()});var Of=require("http");var fh=dt(Ea(),1),ph=dt(Cr(),1),hh=dt(Rr(),1),gh=dt(ts(),1),Br=dt(Ha(),1);var le=require("fs/promises"),Df=require("crypto"),Vt=require("path"),Bf=require("os"),No=dt(Qc(),1);var Ze=require("child_process"),xt=require("fs"),P=require("path"),yn=require("os");var As=require("fs");var Yc=require("os"),Q=require("path"),Ie=(0,Q.join)((0,Yc.homedir)(),".vibelet"),ys=(0,Q.join)(Ie,"logs"),vs=(0,Q.join)(Ie,"data"),Pm=(0,Q.join)(Ie,"runtime"),F0=(0,Q.join)(Pm,"current"),Jc=(0,Q.join)(Ie,"identity.json"),Kc=(0,Q.join)(Ie,"pairings.json"),Xc=(0,Q.join)(vs,"push-subscriptions.json"),Ss=(0,Q.join)(vs,"sessions.json"),De=(0,Q.join)(vs,"audit.jsonl"),xi=(0,Q.join)(vs,"uploads"),_s=(0,Q.join)(ys,"daemon.stdout.log"),bs=(0,Q.join)(ys,"daemon.stderr.log"),Zc=(0,Q.join)(Ie,"update-check.json"),Ri=(0,Q.join)(Ie,"pairing-qr.png");var ws={stdout:!1,stderr:!1};function eu(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Mm(t){return!t.destroyed&&t.writable!==!1}function tu(t,e){if(ws[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Mm(n))return ws[t]=!0,!1;try{return n.write(e,s=>{eu(s)&&(ws[t]=!0)}),!0}catch(s){return eu(s)&&(ws[t]=!0),!1}}function kt(t){return tu("stdout",t)}function Is(t){return tu("stderr",t)}var nu={debug:10,info:20,warn:30,error:40},Lm=process.env.VIBE_LOG_LEVEL||"info";function Nm(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Om(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var ru=!Nm()&&!Om();if(ru)try{(0,As.mkdirSync)(ys,{recursive:!0})}catch{}function su(t,e,n){if(nu[t]<nu[Lm])return;let s={level:t,ts:new Date().toISOString(),msg:n,...e},r=JSON.stringify(s);if(t==="error"||t==="warn"?Is(r+`
21
21
  `):kt(r+`
22
- `),su){let i=t==="error"||t==="warn"?bs:_s;try{(0,As.appendFileSync)(i,r+`
23
- `)}catch{}}}function ru(t={}){function e(n,s,r){typeof s=="string"?nu(n,t,s):nu(n,{...t,...s},r)}return{debug:(n,s)=>e("debug",n,s),info:(n,s)=>e("info",n,s),warn:(n,s)=>e("warn",n,s),error:(n,s)=>e("error",n,s),child:n=>ru({...t,...n})}}var M=ru({module:"daemon"});var Om=["fnm_multishells"],Dm=6e4,Be=process.platform==="win32",Bm=300*1e3,Fm=900*1e3,Hm=M.child({module:"config"});function oe(t){return Om.some(e=>t.includes(e))}function Um(t){if(!t||!oe(t))return t;try{let e=(0,E.join)((0,xt.realpathSync)((0,E.dirname)(t)),(0,E.basename)(t));if((0,xt.existsSync)(e)&&!oe(e))return e}catch{}return t}function Wm(t){if(!t||!oe(t))return t;try{let e=(0,xt.realpathSync)(t);if(e&&!oe(e))return e}catch{}return t}function Pi(){return Be?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var gn=null;function au(){if(gn&&gn.PATH&&!oe(gn.PATH))return gn;for(let t of Pi())try{let e=(0,Ze.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let s of e.split(`
24
- `)){let r=s.indexOf("=");r>0&&(n[s.slice(0,r)]=s.slice(r+1))}return n.PATH&&!oe(n.PATH)&&(gn=n),n}catch{}return{}}function qm(t=au()){let e=(0,yn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Be?(0,E.join)(e,"pnpm"):(0,E.join)(e,"Library","pnpm")),s=t.PATH||process.env.PATH||"",r=Be?[(0,E.join)(e,".npm-global","bin"),(0,E.join)(e,".local","bin"),(0,E.join)(e,".claude","bin"),n,(0,E.join)(e,"AppData","Roaming","npm"),(0,E.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,E.join)(e,".npm-global","bin"),(0,E.join)(e,".local","bin"),(0,E.join)(e,".claude","bin"),n],i=s.split(E.delimiter).filter(Boolean).map(Wm),o=new Set(i);for(let a of r)o.has(a)||(i.push(a),o.add(a));return i.join(E.delimiter)}function Ei(t,e){let n=process.env[t];if(!n)return e;let s=Number(n);return Number.isFinite(s)&&s>0?Math.floor(s):e}function Ts(t,e){let n=process.env[t];if(n==null||n==="")return e;let s=Number(n);return Number.isFinite(s)&&s>=0?Math.floor(s):e}function et(){let t=au(),e={};for(let[n,s]of Object.entries(process.env))typeof s=="string"&&(e[n]=s);for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e.PATH=qm(t),e.HOME||(e.HOME=(0,yn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Mi(t){if(Be)try{let n=(0,Ze.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(r=>r.endsWith(".exe"))??n[0]}catch{return}}function mn(t,e=3e3){try{return(0,Ze.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:et(),...Be?{shell:!0}:{}}).trim()||null}catch{return null}}function Gm(t){for(let e of Pi())try{let n=(0,Ze.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function jm(){let t=(0,yn.homedir)();return[(0,E.join)(t,".local","bin","claude"),(0,E.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,E.join)(t,".npm-global","bin","claude")]}function $m(){if(Be){let t=Mi("claude");return t&&mn(t)?t:void 0}for(let t of jm())if(mn(t))return t;try{let t=(0,Ze.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:et()}).trim();if(t&&!t.includes("cmux")&&mn(t))return t}catch{}}function zm(){let t=(0,yn.homedir)(),e=[process.env.PNPM_HOME,(0,E.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,E.join)(t,".npm-global","bin","codex"),(0,E.join)(t,".local","bin","codex"),...e.map(n=>(0,E.join)(n,"codex"))]}function Vm(){if(Be){let r=Mi("codex");return r&&mn(r)?r:void 0}let t=r=>{let i=Um(r);return mn(i)?i:void 0},e;for(let r of zm()){let i=t(r);if(i){if(!oe(i))return i;e=i}}try{let r=(0,Ze.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:et()}).trim(),i=r?t(r):void 0;if(i){if(!oe(i))return i;e=e??i}}catch{}let n=Gm("codex"),s=n?t(n):void 0;if(s){if(!oe(s))return s;e=e??s}return e}function lu(t,e){let n=null,s=0;return()=>{let r=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[r])return process.env[r];let i=Date.now();if(!n||i-s>Dm||!(0,xt.existsSync)(n)||oe(n)){let o=t();n=o??e,s=i,Hm.info({name:e,path:n,transient:oe(n),isBare:o==null},"binary resolved")}return n}}var Qm=lu($m,"claude"),Ym=lu(Vm,"codex");function Jm(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--")&&n+1<e.length){let r=s.slice(2);t[r]=e[++n]}}return t}var iu=Jm(),Cs=Ts("VIBE_TURN_STALL_TIMEOUT_MS",Bm),ou=Ts("VIBE_TURN_STALL_HARD_TIMEOUT_MS",Math.max(Fm,Cs*3)),Km=Cs<=0||ou===0?0:Math.max(ou,Cs);function Xm(t,e){if(Be)return{command:Mi(t)??t,args:e};let n=Pi()[0]??"/bin/zsh",s=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",s,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:iu.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:iu["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ts("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Cs,turnStallHardTimeoutMs:Km,auditMaxBytes:Ei("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Ei("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Ei("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Ts("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",reviewMock:process.env.VIBE_REVIEW_MOCK==="1",get claudePath(){return Qm()},get codexPath(){return Ym()},isTransientPath:oe,execViaLoginShell:Xm,buildSanitizedEnv:et};var wo=require("crypto"),lf=require("fs/promises");var Iu=require("child_process"),Ps=require("fs");var ks=require("fs"),du=require("path");var J=require("fs");function Zm(t,e,n,s){let r=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,r,s??i))}function vn(t,e){if(!(0,J.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let s=(0,J.statSync)(t).size,r=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||s+r<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:s,afterBytes:s,reclaimedBytes:0};let i=Zm(s,e.maxBytes,r,e.retainBytes),o=(0,J.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,J.readSync)(o,l,0,i,s-i);let u=0;if(s>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,J.ftruncateSync)(o,0),a.length>0&&(0,J.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:s,afterBytes:a.length,reclaimedBytes:s-a.length}}finally{(0,J.closeSync)(o)}}function cu(t){let e=[vn(t.auditPath,{maxBytes:t.auditMaxBytes}),vn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),vn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,s)=>n+s.reclaimedBytes,0)}}var uu=!1,ey=new Set(["ts","event","source","appEvent","level"]);function ty(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function ny(t={}){let e={};for(let[n,s]of Object.entries(t))ey.has(n)||(e[n]=s);return e}function sy(t,e,n={},s){return{ts:s??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...ny(n)}}function ry(){uu||((0,ks.mkdirSync)((0,du.dirname)(De),{recursive:!0}),uu=!0)}var Li=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,s={},r){this.write(sy(e,n,s,r))}write(e){if(!ty()){ry();try{let n=JSON.stringify(e)+`
25
- `;vn(De,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,ks.appendFileSync)(De,n)}catch{}}}},w=new Li;var Fe=require("fs"),fu=require("os"),Sn=require("path"),pu=require("crypto"),Ni="claude-hook:",_n="x-vibelet-claude-hook-secret",bn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function iy(t,e){return`#!/usr/bin/env node
22
+ `),ru){let i=t==="error"||t==="warn"?bs:_s;try{(0,As.appendFileSync)(i,r+`
23
+ `)}catch{}}}function iu(t={}){function e(n,s,r){typeof s=="string"?su(n,t,s):su(n,{...t,...s},r)}return{debug:(n,s)=>e("debug",n,s),info:(n,s)=>e("info",n,s),warn:(n,s)=>e("warn",n,s),error:(n,s)=>e("error",n,s),child:n=>iu({...t,...n})}}var L=iu({module:"daemon"});var Dm=["fnm_multishells"],Bm=6e4,Be=process.platform==="win32",Fm=300*1e3,Hm=900*1e3,Um=L.child({module:"config"});function oe(t){return Dm.some(e=>t.includes(e))}function Wm(t){if(!t||!oe(t))return t;try{let e=(0,P.join)((0,xt.realpathSync)((0,P.dirname)(t)),(0,P.basename)(t));if((0,xt.existsSync)(e)&&!oe(e))return e}catch{}return t}function qm(t){if(!t||!oe(t))return t;try{let e=(0,xt.realpathSync)(t);if(e&&!oe(e))return e}catch{}return t}function Pi(){return Be?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var gn=null;function lu(){if(gn&&gn.PATH&&!oe(gn.PATH))return gn;for(let t of Pi())try{let e=(0,Ze.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let s of e.split(`
24
+ `)){let r=s.indexOf("=");r>0&&(n[s.slice(0,r)]=s.slice(r+1))}return n.PATH&&!oe(n.PATH)&&(gn=n),n}catch{}return{}}function Gm(t=lu()){let e=(0,yn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Be?(0,P.join)(e,"pnpm"):(0,P.join)(e,"Library","pnpm")),s=t.PATH||process.env.PATH||"",r=Be?[(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n,(0,P.join)(e,"AppData","Roaming","npm"),(0,P.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n],i=s.split(P.delimiter).filter(Boolean).map(qm),o=new Set(i);for(let a of r)o.has(a)||(i.push(a),o.add(a));return i.join(P.delimiter)}function Ei(t,e){let n=process.env[t];if(!n)return e;let s=Number(n);return Number.isFinite(s)&&s>0?Math.floor(s):e}function Ts(t,e){let n=process.env[t];if(n==null||n==="")return e;let s=Number(n);return Number.isFinite(s)&&s>=0?Math.floor(s):e}function et(){let t=lu(),e={};for(let[n,s]of Object.entries(process.env))typeof s=="string"&&(e[n]=s);for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e.PATH=Gm(t),e.HOME||(e.HOME=(0,yn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Mi(t){if(Be)try{let n=(0,Ze.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(r=>r.endsWith(".exe"))??n[0]}catch{return}}function mn(t,e=3e3){try{return(0,Ze.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:et(),...Be?{shell:!0}:{}}).trim()||null}catch{return null}}function jm(t){for(let e of Pi())try{let n=(0,Ze.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function $m(){let t=(0,yn.homedir)();return[(0,P.join)(t,".local","bin","claude"),(0,P.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,P.join)(t,".npm-global","bin","claude")]}function zm(){if(Be){let t=Mi("claude");return t&&mn(t)?t:void 0}for(let t of $m())if(mn(t))return t;try{let t=(0,Ze.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:et()}).trim();if(t&&!t.includes("cmux")&&mn(t))return t}catch{}}function Vm(){let t=(0,yn.homedir)(),e=[process.env.PNPM_HOME,(0,P.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,P.join)(t,".npm-global","bin","codex"),(0,P.join)(t,".local","bin","codex"),...e.map(n=>(0,P.join)(n,"codex"))]}function Qm(){if(Be){let r=Mi("codex");return r&&mn(r)?r:void 0}let t=r=>{let i=Wm(r);return mn(i)?i:void 0},e;for(let r of Vm()){let i=t(r);if(i){if(!oe(i))return i;e=i}}try{let r=(0,Ze.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:et()}).trim(),i=r?t(r):void 0;if(i){if(!oe(i))return i;e=e??i}}catch{}let n=jm("codex"),s=n?t(n):void 0;if(s){if(!oe(s))return s;e=e??s}return e}function cu(t,e){let n=null,s=0;return()=>{let r=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[r])return process.env[r];let i=Date.now();if(!n||i-s>Bm||!(0,xt.existsSync)(n)||oe(n)){let o=t();n=o??e,s=i,Um.info({name:e,path:n,transient:oe(n),isBare:o==null},"binary resolved")}return n}}var Ym=cu(zm,"claude"),Jm=cu(Qm,"codex");function Km(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--")&&n+1<e.length){let r=s.slice(2);t[r]=e[++n]}}return t}var ou=Km(),Cs=Ts("VIBE_TURN_STALL_TIMEOUT_MS",Fm),au=Ts("VIBE_TURN_STALL_HARD_TIMEOUT_MS",Math.max(Hm,Cs*3)),Xm=Cs<=0||au===0?0:Math.max(au,Cs);function Zm(t,e){if(Be)return{command:Mi(t)??t,args:e};let n=Pi()[0]??"/bin/zsh",s=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",s,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:ou.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:ou["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ts("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Cs,turnStallHardTimeoutMs:Xm,auditMaxBytes:Ei("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Ei("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Ei("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Ts("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",reviewMock:process.env.VIBE_REVIEW_MOCK==="1",get claudePath(){return Ym()},get codexPath(){return Jm()},isTransientPath:oe,execViaLoginShell:Zm,buildSanitizedEnv:et};var Io=require("crypto"),cf=require("fs/promises");var Au=require("child_process"),Ps=require("fs");var ks=require("fs"),fu=require("path");var J=require("fs");function ey(t,e,n,s){let r=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,r,s??i))}function vn(t,e){if(!(0,J.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let s=(0,J.statSync)(t).size,r=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||s+r<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:s,afterBytes:s,reclaimedBytes:0};let i=ey(s,e.maxBytes,r,e.retainBytes),o=(0,J.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,J.readSync)(o,l,0,i,s-i);let u=0;if(s>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,J.ftruncateSync)(o,0),a.length>0&&(0,J.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:s,afterBytes:a.length,reclaimedBytes:s-a.length}}finally{(0,J.closeSync)(o)}}function uu(t){let e=[vn(t.auditPath,{maxBytes:t.auditMaxBytes}),vn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),vn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,s)=>n+s.reclaimedBytes,0)}}var du=!1,ty=new Set(["ts","event","source","appEvent","level"]);function ny(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function sy(t={}){let e={};for(let[n,s]of Object.entries(t))ty.has(n)||(e[n]=s);return e}function ry(t,e,n={},s){return{ts:s??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...sy(n)}}function iy(){du||((0,ks.mkdirSync)((0,fu.dirname)(De),{recursive:!0}),du=!0)}var Li=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,s={},r){this.write(ry(e,n,s,r))}write(e){if(!ny()){iy();try{let n=JSON.stringify(e)+`
25
+ `;vn(De,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,ks.appendFileSync)(De,n)}catch{}}}},b=new Li;var Fe=require("fs"),pu=require("os"),Sn=require("path"),hu=require("crypto"),Ni="claude-hook:",_n="x-vibelet-claude-hook-secret",bn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function oy(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 oy(t,e){return`#!/usr/bin/env node
46
+ `}function ay(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
48
  const fallback = ${JSON.stringify(JSON.stringify(bn))};
49
49
  const chunks = [];
@@ -79,52 +79,52 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function hu(t,e){let n=(0,Sn.join)((0,fu.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,pu.randomUUID)()}`);(0,Fe.mkdirSync)(n,{recursive:!0});let s=(0,Sn.join)(n,"settings.json"),r=(0,Sn.join)(n,"session_hook_forwarder.cjs"),i=(0,Sn.join)(n,"permission_hook_forwarder.cjs");return(0,Fe.writeFileSync)(r,iy(t,e),"utf8"),(0,Fe.writeFileSync)(i,oy(t,e),"utf8"),(0,Fe.writeFileSync)(s,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(r)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:s,sessionScriptPath:r,permissionScriptPath:i}}function xs(t){if(t)try{(0,Fe.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var gu=require("os"),tt=require("path"),mu=require("fs/promises"),ay=new Set([".c",".cc",".cpp",".cs",".css",".dart",".elm",".ex",".exs",".fish",".go",".h",".hpp",".hrl",".java",".js",".jsx",".kt",".kts",".less",".lua",".m",".mm",".mjs",".php",".pl",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sql",".swift",".ts",".tsx",".vue",".xml",".yaml",".yml",".zsh"]),ly=5e3,yu="Generated file: ",vu=`Generated files:
83
- `;function Rt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function wn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Oi(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s?.[1]&&(e=s[1]),e}function nt(t,e){let n=Oi(t);return n?n.startsWith("~/")?(0,tt.resolve)((0,gu.homedir)(),n.slice(2)):(0,tt.isAbsolute)(n)?n:e?(0,tt.resolve)(e,n):n:""}function cy(t){return ay.has((0,tt.extname)(Oi(t)).toLowerCase())}function Et(t){let e=Oi(t);return e?!cy(e):!1}function Ae(t){let e=[...new Set(t.map(n=>nt(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${yu}${e[0]}`:`${vu}${e.join(`
84
- `)}`}function Su(t){return typeof t!="string"?!1:t.startsWith(yu)||t.startsWith(vu)}function uy(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),s=new Set;for(let r of n){let i=Rt(r[1]);if(!i)continue;let o=nt(i,e);!o||!Et(o)||s.add(o)}return[...s]}function dy(t){let e=Rt(t);return e?e.toLowerCase():""}function fy(t,e){let n=Rt(t?.file_path)??Rt(t?.path);if(!n)return null;let s=nt(n,e);return s&&Et(s)?s:null}function Rs(t,e,n){return dy(t)!=="write"?null:fy(e,n)}function py(t){let e=t.toLowerCase();return e.includes("updated successfully")||e.includes("updated. all occurrences were successfully replaced")||e.includes("all occurrences were successfully replaced")||e.includes("successfully replaced")}function hy(t){return/^\d+\t/m.test(t)}function Es(t,e){let n=typeof e=="string"?e.trim():"";if(n&&py(n))return!1;let s=wn(t);if(s?.type==="update"||s?.type==="replace"||s&&(Object.hasOwn(s,"oldString")||Object.hasOwn(s,"structuredPatch")||Object.hasOwn(s,"originalFile")||Object.hasOwn(s,"replaceAll")))return!1;if(typeof wn(s?.file)?.filePath=="string"||typeof s?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||hy(n))return!0}return!1}function Di(t,e){let n=wn(t);if(!n)return[];let s=new Set;if(n.type==="event_msg"){let r=wn(n.payload);if(r?.type==="image_generation_end"){let i=Rt(r.saved_path);if(i){let o=nt(i,e?.cwd);o&&Et(o)&&s.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let r=wn(n.payload);if(r?.type==="function_call"&&r.name==="apply_patch"){let i=Rt(r.arguments);if(i)for(let o of uy(i,e?.cwd))s.add(o)}}return[...s]}async function _u(t,e){let n=[...new Set(t.map(r=>nt(r)).filter(Boolean))],s=[];for(let r of n)if(Et(r))try{let i=await(0,mu.stat)(r);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+ly<e)continue;s.push(r)}catch{}return s}var ee=M.child({module:"claude"}),Au="claude-permission-denial:",gy=/\u001B\[[0-?]*[ -/]*[@-~]/g;function my(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Bi(t){my()&&Is(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
- `)}function yy(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(`
86
- `):""}function vy(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Sy(t){if(typeof t=="string")return t;let e=yy(t);return e||(vy(t)?"":JSON.stringify(t))}function _y(t){return/requested permissions|haven't granted/i.test(t)}function bu(t){return t.replace(gy,"").replace(/\s+/g," ").trim()}function by(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function wy(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 Iy(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function wu(t){let e=bu(t.resultText??""),n=(t.stderrLines??[]).map(bu).filter(Boolean).slice(-3),s=[e,...n].find(i=>!!i&&wy(i));if(s)return Iy(s);let r=[e,...n].find(i=>!!i&&!by(i));return r?t.exitCode!=null&&r!==e?`Claude exited with code ${t.exitCode}: ${r}`:r:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Ms(t){return t.startsWith(Au)}var In=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;toolCallContext=new Map;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,s){return this.cwd=e,this.approvalMode=s,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ee.info({sessionId:this.sessionId,cwd:e},"session initialized"),w.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 s=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&s.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&s.push("--resume",this.sessionId),xs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=hu(this.hookPort,this.hookSecret),s.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&s.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&s.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&s.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ee.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Bi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.toolCallContext.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=s;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",s);o=c.command,a=c.args}else o=i;this.proc=(0,Iu.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}});let u=this.proc;u.on("error",c=>{if(this.proc!==u)return;let d=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Ps.existsSync)(this.cwd)&&(d=`Working directory does not exist: ${this.cwd}`),ee.error({sessionId:this.sessionId,error:d,cwd:this.cwd},"spawn error"),w.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:d}),this.handler?.({type:"error",sessionId:this.sessionId,message:d})}),this.buffer="",u.stdout.on("data",c=>{if(this.proc!==u)return;this.buffer+=c.toString();let d=this.buffer.split(`
87
- `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{ee.warn({sessionId:this.sessionId,linePreview:f.slice(0,100)},"failed to parse stdout line")}}),u.stderr.on("data",c=>{if(this.proc!==u)return;let d=c.toString().trim();d&&(ee.debug({sessionId:this.sessionId,stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),u.on("exit",(c,d)=>{if(this.proc!==u){ee.debug({sessionId:this.sessionId,exitCode:c,signal:d},"stale proc exit ignored, current proc was replaced");return}ee.info({sessionId:this.sessionId,exitCode:c,signal:d},"process exited");let f=this.interrupted;this.proc=null,xs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),f&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ee.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:wu({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ee.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ee.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let s=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(s+`
88
- `),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.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,xs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),w.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Rs(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ps.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Sy(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ps.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Es(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&_y(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(w.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Bi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:wu({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;w.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Au}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Bi("Claude finished. Run `claude --continue` to continue on desktop."),w.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 xu=require("child_process"),Ru=require("fs");var Fi=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 s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}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)}},_=new Fi;var Tu=require("node:fs"),Hi=require("node:path"),Ay="@vibelet/cli";function Ty(t){try{let e=JSON.parse((0,Tu.readFileSync)(t,"utf8"));if(e.name===Ay&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Cy(){return"1.2.0"}var Pt=Cy();var P=M.child({module:"codex"});function ky(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 xy(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 L(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Ui(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ry=new Set(["aborted","interrupted","cancelled","canceled"]);function Ey(t){let e=L(t);return e?e.toLowerCase():null}function Py(t){let e=L(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Wi(t){return t?L(t.itemId)??L(t.id)??L(t.callId)??L(t.call_id):null}function qi(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Eu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Pu(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function My(t){if(!Array.isArray(t))return null;for(let e of t){let n=$(e);if(!n)continue;let s=L(n.id),r=Array.isArray(n.options)?n.options.map(l=>$(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>L(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Eu(l))??i[0],a=i.find(l=>Pu(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Ly(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>$(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>$(o)).filter(o=>!!o).map(o=>L(o.label)).filter(o=>!!o)),n=e.some(r=>Eu(r)),s=e.some(r=>Pu(r));return n&&s}function Cu(t){let e=Py(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:qi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:qi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=L(t.server),s=L(t.tool)??L(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:$(t.arguments)??$(t.input)??{}}:null}return null}function Ny(t,e){let n=L(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>$(o)?.kind==="create"))return null;let i=nt(n,e);return Et(i)?i:null}function Oy(t){if(!Array.isArray(t))return"";for(let e of t){let n=$(e);if(!n)continue;let s=L(n.question)??L(n.header);if(s)return s}return""}function Dy(t){let e=$(t);if(!e)return;let n=Ui(e.input_tokens??e.inputTokens)??0,s=Ui(e.output_tokens??e.outputTokens)??0,r=Ui(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function ku(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 An=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;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,P.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=r,P.info({spawnCmd:i,args:o},"spawning");w.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,xu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Ru.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),P.error({error:d,cwd:e},"spawn error"),w.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
89
- `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{P.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(P.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{P.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&P.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:d}]of this.pending)d(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 l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Pt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=ku(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,P.info({threadId:this.threadId},"thread resumed"),w.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",P.info({threadId:this.threadId},"thread created"),w.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 s=ku(this.approvalMode,this.cwd||process.cwd());this.latestTurnUsage=void 0,this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,P.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:s.approvalPolicy,sandboxPolicy:s.sandboxPolicy,...n?{model:n}:{}}).then(r=>{P.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,P.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let s=this.approvalRequests.get(e),r=s?.rpcId??Number(e);if(!Number.isFinite(r))return!1;let i;if(!s)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(s.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[s.questionId]:{answers:[n?s.approveLabel:s.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 P.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
90
- `),!0}restorePendingApproval(e){let n=xy(e);n&&this.approvalRequests.set(e.requestId,n)}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,P.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,this.latestTurnUsage=void 0;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 s=++this.rpcId,r=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(s,{resolve:a=>{r(),i(a)},reject:a=>{r(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(s),r(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:s,params:n})+`
91
- `),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),P.error({method:e,rpcId:s,threadId:this.threadId},"RPC timeout"),r(),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 gu(t,e){let n=(0,Sn.join)((0,pu.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,hu.randomUUID)()}`);(0,Fe.mkdirSync)(n,{recursive:!0});let s=(0,Sn.join)(n,"settings.json"),r=(0,Sn.join)(n,"session_hook_forwarder.cjs"),i=(0,Sn.join)(n,"permission_hook_forwarder.cjs");return(0,Fe.writeFileSync)(r,oy(t,e),"utf8"),(0,Fe.writeFileSync)(i,ay(t,e),"utf8"),(0,Fe.writeFileSync)(s,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(r)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:s,sessionScriptPath:r,permissionScriptPath:i}}function xs(t){if(t)try{(0,Fe.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var mu=require("os"),tt=require("path"),yu=require("fs/promises"),ly=new Set([".c",".cc",".cpp",".cs",".css",".dart",".elm",".ex",".exs",".fish",".go",".h",".hpp",".hrl",".java",".js",".jsx",".kt",".kts",".less",".lua",".m",".mm",".mjs",".php",".pl",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sql",".swift",".ts",".tsx",".vue",".xml",".yaml",".yml",".zsh"]),cy=5e3,vu="Generated file: ",Su=`Generated files:
83
+ `;function Rt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function wn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Oi(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s?.[1]&&(e=s[1]),e}function nt(t,e){let n=Oi(t);return n?n.startsWith("~/")?(0,tt.resolve)((0,mu.homedir)(),n.slice(2)):(0,tt.isAbsolute)(n)?n:e?(0,tt.resolve)(e,n):n:""}function uy(t){return ly.has((0,tt.extname)(Oi(t)).toLowerCase())}function Et(t){let e=Oi(t);return e?!uy(e):!1}function Ae(t){let e=[...new Set(t.map(n=>nt(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${vu}${e[0]}`:`${Su}${e.join(`
84
+ `)}`}function _u(t){return typeof t!="string"?!1:t.startsWith(vu)||t.startsWith(Su)}function dy(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),s=new Set;for(let r of n){let i=Rt(r[1]);if(!i)continue;let o=nt(i,e);!o||!Et(o)||s.add(o)}return[...s]}function fy(t){let e=Rt(t);return e?e.toLowerCase():""}function py(t,e){let n=Rt(t?.file_path)??Rt(t?.path);if(!n)return null;let s=nt(n,e);return s&&Et(s)?s:null}function Rs(t,e,n){return fy(t)!=="write"?null:py(e,n)}function hy(t){let e=t.toLowerCase();return e.includes("updated successfully")||e.includes("updated. all occurrences were successfully replaced")||e.includes("all occurrences were successfully replaced")||e.includes("successfully replaced")}function gy(t){return/^\d+\t/m.test(t)}function Es(t,e){let n=typeof e=="string"?e.trim():"";if(n&&hy(n))return!1;let s=wn(t);if(s?.type==="update"||s?.type==="replace"||s&&(Object.hasOwn(s,"oldString")||Object.hasOwn(s,"structuredPatch")||Object.hasOwn(s,"originalFile")||Object.hasOwn(s,"replaceAll")))return!1;if(typeof wn(s?.file)?.filePath=="string"||typeof s?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||gy(n))return!0}return!1}function Di(t,e){let n=wn(t);if(!n)return[];let s=new Set;if(n.type==="event_msg"){let r=wn(n.payload);if(r?.type==="image_generation_end"){let i=Rt(r.saved_path);if(i){let o=nt(i,e?.cwd);o&&Et(o)&&s.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let r=wn(n.payload);if(r?.type==="function_call"&&r.name==="apply_patch"){let i=Rt(r.arguments);if(i)for(let o of dy(i,e?.cwd))s.add(o)}}return[...s]}async function bu(t,e){let n=[...new Set(t.map(r=>nt(r)).filter(Boolean))],s=[];for(let r of n)if(Et(r))try{let i=await(0,yu.stat)(r);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+cy<e)continue;s.push(r)}catch{}return s}var ee=L.child({module:"claude"}),Tu="claude-permission-denial:",my=/\u001B\[[0-?]*[ -/]*[@-~]/g;function yy(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Bi(t){yy()&&Is(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
+ `)}function vy(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(`
86
+ `):""}function Sy(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function _y(t){if(typeof t=="string")return t;let e=vy(t);return e||(Sy(t)?"":JSON.stringify(t))}function by(t){return/requested permissions|haven't granted/i.test(t)}function wu(t){return t.replace(my,"").replace(/\s+/g," ").trim()}function wy(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Iy(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 Ay(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Iu(t){let e=wu(t.resultText??""),n=(t.stderrLines??[]).map(wu).filter(Boolean).slice(-3),s=[e,...n].find(i=>!!i&&Iy(i));if(s)return Ay(s);let r=[e,...n].find(i=>!!i&&!wy(i));return r?t.exitCode!=null&&r!==e?`Claude exited with code ${t.exitCode}: ${r}`:r:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Ms(t){return t.startsWith(Tu)}var In=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;toolCallContext=new Map;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,s){return this.cwd=e,this.approvalMode=s,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ee.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 s=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&s.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&s.push("--resume",this.sessionId),xs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=gu(this.hookPort,this.hookSecret),s.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&s.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&s.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&s.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ee.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Bi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.toolCallContext.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=s;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",s);o=c.command,a=c.args}else o=i;this.proc=(0,Au.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}});let u=this.proc;u.on("error",c=>{if(this.proc!==u)return;let d=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Ps.existsSync)(this.cwd)&&(d=`Working directory does not exist: ${this.cwd}`),ee.error({sessionId:this.sessionId,error:d,cwd:this.cwd},"spawn error"),b.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:d}),this.handler?.({type:"error",sessionId:this.sessionId,message:d})}),this.buffer="",u.stdout.on("data",c=>{if(this.proc!==u)return;this.buffer+=c.toString();let d=this.buffer.split(`
87
+ `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{ee.warn({sessionId:this.sessionId,linePreview:f.slice(0,100)},"failed to parse stdout line")}}),u.stderr.on("data",c=>{if(this.proc!==u)return;let d=c.toString().trim();d&&(ee.debug({sessionId:this.sessionId,stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),u.on("exit",(c,d)=>{if(this.proc!==u){ee.debug({sessionId:this.sessionId,exitCode:c,signal:d},"stale proc exit ignored, current proc was replaced");return}ee.info({sessionId:this.sessionId,exitCode:c,signal:d},"process exited");let f=this.interrupted;this.proc=null,xs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),f&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ee.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Iu({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ee.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ee.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let s=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(s+`
88
+ `),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.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,xs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),b.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Rs(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ps.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=_y(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ps.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Es(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&by(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(b.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Bi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Iu({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;b.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Tu}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Bi("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 Ru=require("child_process"),Eu=require("fs");var Fi=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 s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},_=new Fi;var Cu=require("node:fs"),Hi=require("node:path"),Ty="@vibelet/cli";function Cy(t){try{let e=JSON.parse((0,Cu.readFileSync)(t,"utf8"));if(e.name===Ty&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function ky(){return"1.2.2"}var Pt=ky();var x=L.child({module:"codex"});function xy(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 Ry(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 F(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function M(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Ui(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ey=new Set(["aborted","interrupted","cancelled","canceled","failed"]);function Py(t){let e=M(t);return e?e.toLowerCase():null}function My(t){try{let e=JSON.parse(t),n=F(F(e)?.error)?.message;if(typeof n=="string"&&n.trim())return n}catch{}return t}function Ly(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Wi(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function qi(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Pu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Mu(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Ny(t){if(!Array.isArray(t))return null;for(let e of t){let n=F(e);if(!n)continue;let s=M(n.id),r=Array.isArray(n.options)?n.options.map(l=>F(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Pu(l))??i[0],a=i.find(l=>Mu(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Oy(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>F(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>F(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(r=>Pu(r)),s=e.some(r=>Mu(r));return n&&s}function ku(t){let e=Ly(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:qi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:qi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=M(t.server),s=M(t.tool)??M(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:F(t.arguments)??F(t.input)??{}}:null}return null}function Dy(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>F(o)?.kind==="create"))return null;let i=nt(n,e);return Et(i)?i:null}function By(t){if(!Array.isArray(t))return"";for(let e of t){let n=F(e);if(!n)continue;let s=M(n.question)??M(n.header);if(s)return s}return""}function Fy(t){let e=F(t);if(!e)return;let n=Ui(e.input_tokens??e.inputTokens)??0,s=Ui(e.output_tokens??e.outputTokens)??0,r=Ui(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function xu(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 An=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;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){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=r,x.info({spawnCmd:i,args:o},"spawning");b.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Ru.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Eu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),x.error({error:d,cwd:e},"spawn error"),b.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
89
+ `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{x.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(x.debug({stderr:d},"stderr"),this.lastStderr.push(d),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:d}]of this.pending)d(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 l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Pt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=xu(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.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:u.approvalPolicy,sandbox:u.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.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 s=xu(this.approvalMode,this.cwd||process.cwd());this.latestTurnUsage=void 0,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:s.approvalPolicy,sandboxPolicy:s.sandboxPolicy,...n?{model:n}:{}}).then(r=>{x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let s=this.approvalRequests.get(e),r=s?.rpcId??Number(e);if(!Number.isFinite(r))return!1;let i;if(!s)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(s.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[s.questionId]:{answers:[n?s.approveLabel:s.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:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
90
+ `),!0}restorePendingApproval(e){let n=Ry(e);n&&this.approvalRequests.set(e.requestId,n)}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}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,this.latestTurnUsage=void 0;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 s=++this.rpcId,r=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(s,{resolve:a=>{r(),i(a)},reject:a=>{r(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(s),r(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:s,params:n})+`
91
+ `),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),x.error({method:e,rpcId:s,threadId:this.threadId},"RPC timeout"),r(),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})+`
92
92
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
93
- `)}resolveToolContext(e){let n=$(e?.item)??e??null,s=Wi(n);if(!s)return null;let r=n?Cu(n):null;if(r)return this.toolContextByCallId.set(s,r),{callId:s,toolContext:r};let i=this.toolContextByCallId.get(s);return i?{callId:s,toolContext:i}:null}createFallbackInput(e,n){return e?qi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,s){if(this.approvalRequests.set(e,n),w.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){P.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:s,approvalContext:ky(n)})}handleServerRequest(e,n,s){let r=String(n),i=this.resolveToolContext(s);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(r,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},L(s?.reason)??L(s?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(r,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},L(s?.reason)??L(s?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=s?.questions;if(!Ly(o)){P.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=My(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(r,{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(s,["itemId","questions"])},Oy(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(r,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,[])},L(s?.reason)??L(s?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(r,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,[])},L(s?.reason)??L(s?.description)??"");return}if(e==="item/permissions/requestApproval"){P.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}P.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(P.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let r=this.pending.get(e.id);this.pending.delete(e.id),e.error?r.reject(new Error(e.error.message??"RPC error")):r.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,s=$(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,s??void 0);return}switch(n&&P.debug({method:n,paramsPreview:JSON.stringify(s??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let r=s?.text??s?.delta??s?.content??"";r&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:r}):r||P.debug({paramsKeys:Object.keys(s??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":s?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:s.itemId??"",output:String(s.output)});break;case"item/started":{let r=$(s?.item),i=Wi(r),o=r?Cu(r):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 r=$(s?.item)??s,i=Wi(r),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Ny(o.input,this.cwd);if(a){let l=Ae([a]);l&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:i,output:l})}}i&&this.toolContextByCallId.delete(i);break}case"thread/tokenUsage/updated":{let r=$(s?.tokenUsage),i=$(r?.last);if(!i)break;this.latestTurnUsage=Dy({...i,modelContextWindow:r?.modelContextWindow});break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=L(s?.reason)??L($(s?.turn)?.reason);P.info({threadId:this.threadId,reason:r},"turn interrupted"),w.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...r?{reason:r}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let r=$(s?.turn),i=Ey(r?.status),o=this.latestTurnUsage;if(this.latestTurnUsage=void 0,i&&Ry.has(i)){P.info({threadId:this.threadId,status:i},"turn interrupted"),w.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...o?{usage:o}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}P.info({threadId:this.threadId,status:i??"completed"},"turn completed"),w.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:o}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:o});break}default:n&&P.debug({method:n},"unhandled notification");break}}};var Lu=require("crypto"),Mu=["Received. This is the hosted Vibelet review demo environment.","The app is connected to a public review backend and can send and receive assistant messages.","For review purposes, this backend returns deterministic demo responses without requiring a local computer on the same Wi-Fi network."].join(" ");function By(t){let e=t.replace(/\s+/g," ").trim();return e?e.length>120?`${e.slice(0,117)}...`:e:""}var Ls=class{sessionId="";messageHandler=null;exitHandler=null;pendingTimer=null;responding=!1;stopped=!1;async start(e,n){return this.stopped=!1,this.sessionId=n||`review-${(0,Lu.randomUUID)()}`,this.sessionId}sendPrompt(e){if(this.stopped||!this.sessionId)return;this.clearPendingTimer(),this.responding=!0;let n=By(e),s=n?`${Mu}
93
+ `)}resolveToolContext(e){let n=F(e?.item)??e??null,s=Wi(n);if(!s)return null;let r=n?ku(n):null;if(r)return this.toolContextByCallId.set(s,r),{callId:s,toolContext:r};let i=this.toolContextByCallId.get(s);return i?{callId:s,toolContext:i}:null}createFallbackInput(e,n){return e?qi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,s){if(this.approvalRequests.set(e,n),b.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:s,approvalContext:xy(n)})}handleServerRequest(e,n,s){let r=String(n),i=this.resolveToolContext(s);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(r,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(r,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=s?.questions;if(!Oy(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Ny(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(r,{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(s,["itemId","questions"])},By(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(r,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(r,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.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 r=this.pending.get(e.id);this.pending.delete(e.id),e.error?r.reject(new Error(e.error.message??"RPC error")):r.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,s=F(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,s??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(s??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let r=s?.text??s?.delta??s?.content??"";r&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:r}):r||x.debug({paramsKeys:Object.keys(s??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":s?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:s.itemId??"",output:String(s.output)});break;case"item/started":{let r=F(s?.item),i=Wi(r),o=r?ku(r):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 r=F(s?.item)??s,i=Wi(r),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Dy(o.input,this.cwd);if(a){let l=Ae([a]);l&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:i,output:l})}}i&&this.toolContextByCallId.delete(i);break}case"thread/tokenUsage/updated":{let r=F(s?.tokenUsage),i=F(r?.last);if(!i)break;this.latestTurnUsage=Fy({...i,modelContextWindow:r?.modelContextWindow});break}case"error":{let r=F(s?.error),i=M(r?.message)??"Codex error",o=My(i);this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0,x.error({threadId:this.threadId,message:o},"codex error notification"),b.emit("driver.error",{agent:"codex",sessionId:this.threadId,error:o}),this.handler?.({type:"error",sessionId:this.threadId,message:o});break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=M(s?.reason)??M(F(s?.turn)?.reason);x.info({threadId:this.threadId,reason:r},"turn interrupted"),b.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...r?{reason:r}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let r=F(s?.turn),i=Py(r?.status),o=this.latestTurnUsage;if(this.latestTurnUsage=void 0,i&&Ey.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),b.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...o?{usage:o}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),b.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:o}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:o});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var Nu=require("crypto"),Lu=["Received. This is the hosted Vibelet review demo environment.","The app is connected to a public review backend and can send and receive assistant messages.","For review purposes, this backend returns deterministic demo responses without requiring a local computer on the same Wi-Fi network."].join(" ");function Hy(t){let e=t.replace(/\s+/g," ").trim();return e?e.length>120?`${e.slice(0,117)}...`:e:""}var Ls=class{sessionId="";messageHandler=null;exitHandler=null;pendingTimer=null;responding=!1;stopped=!1;async start(e,n){return this.stopped=!1,this.sessionId=n||`review-${(0,Nu.randomUUID)()}`,this.sessionId}sendPrompt(e){if(this.stopped||!this.sessionId)return;this.clearPendingTimer(),this.responding=!0;let n=Hy(e),s=n?`${Lu}
94
94
 
95
- Your message was received: "${n}"`:Mu;this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!(this.stopped||!this.sessionId)&&(this.emit({type:"text.delta",sessionId:this.sessionId,content:s}),this.responding=!1,this.emit({type:"session.done",sessionId:this.sessionId,usage:{inputTokens:Math.max(1,Math.ceil(e.length/4)),outputTokens:Math.max(1,Math.ceil(s.length/4))}}))},25)}respondApproval(){return!1}getRespondingLivenessHint(){return this.responding?"alive":"unknown"}interrupt(){!this.responding||!this.sessionId||(this.clearPendingTimer(),this.responding=!1,this.emit({type:"session.interrupted",sessionId:this.sessionId}))}stop(){this.clearPendingTimer(),this.responding=!1,this.stopped=!0,this.exitHandler?.(0)}setApprovalMode(){}onMessage(e){this.messageHandler=e}onExit(e){this.exitHandler=e}emit(e){this.messageHandler?.(e)}clearPendingTimer(){this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null)}};var O=require("fs/promises"),ao=require("fs"),lo=require("readline"),F=require("path"),ye=require("os");var Fy=new Set(["New session","Resumed session","Untitled session"]),Hy=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Uy(t){return t.replace(/\s+/g," ").trim()}function Ns(t){return typeof t!="string"?void 0:Uy(t)||void 0}function Nu(t){let e=Ns(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 Mt(t){let e=Ns(t);return!e||Fy.has(e)||Nu(e)}function Wy(t){for(let e of t.replace(/\r/g,"").split(`
96
- `)){let n=Ns(e);if(n&&!qy(n)&&!Gy(n))return n}}function qy(t){return Hy.some(e=>t.startsWith(e))}function Gy(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function jy(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 s=t[e+1];if(!s||/\s/.test(s))return e+1}}return-1}function Gi(t,e=80){if(typeof t!="string")return;let n=Wy(t);if(!n)return;let s=jy(n),i=(s>0?n.slice(0,s):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Nu(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function st(t,e){for(let n of t){let s=Ns(n);if(!(!s||Mt(s)))return s}return Gi(e)}var Bu=require("child_process"),Fu=require("util");var Hu=(0,Fu.promisify)(Bu.execFile),Uu=5e3,$y=2500,zy=3e3,Wu=8,Os=new Map,ji=new Map,Ou=null;function Vy(t){let e=Os.get(t);return e?Date.now()>e.expiresAt?(Os.delete(t),null):e.value??void 0:null}function Qy(t,e){if(e===void 0){Os.delete(t);return}Os.set(t,{value:e,expiresAt:Date.now()+Uu})}async function Yy(t){if(!t)return;if(Ou)return Ou(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:s}=await Hu("git",["-C",t,...n],{env:et(),timeout:$y,maxBuffer:65536}),r=s.trim();if(r&&r!=="HEAD")return r}catch{}}async function Jy(t){let e=Vy(t);if(e!==null)return e;let n=ji.get(t);if(n)return n;let s=Yy(t).then(r=>(Qy(t,r),r)).finally(()=>{ji.delete(t)});return ji.set(t,s),s}async function qu(t,e,n){if(t.length===0)return;let s=Math.max(1,Math.min(e,t.length)),r=0;await Promise.all(Array.from({length:s},async()=>{for(;;){let i=r;if(r+=1,i>=t.length)return;await n(t[i])}}))}async function Gu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await qu(e,Wu,async s=>{n.set(s,await Jy(s))}),n}var zi=new Map,$i=new Map,Du=null;function Ky(t,e){if(e===void 0){zi.delete(t);return}zi.set(t,{value:e,expiresAt:Date.now()+Uu})}async function Xy(t){if(t){if(Du)return Du(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await Hu("git",["-C",t,"diff","HEAD","--shortstat"],{env:et(),timeout:zy,maxBuffer:65536}),s=n.trim();if(!s)return;let r=s.match(/(\d+) insertion/),i=s.match(/(\d+) deletion/),o=r?Number(r[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function Zy(t){let e=zi.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=$i.get(t);if(n)return n;let s=Xy(t).then(r=>(Ky(t,r),r)).finally(()=>{$i.delete(t)});return $i.set(t,s),s}async function ju(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await qu(e,Wu,async s=>{n.set(s,await Zy(s))}),n}var zu=require("child_process"),Fs=require("fs/promises"),rt=require("path"),Vu=require("os"),Qu=require("util");var ev=(0,Qu.promisify)(zu.execFile),Bs=M.child({module:"process-scanner"}),Yu=5e3,tv=1500,nv=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,sv=500,rv=15e3,Cn=null,Tn=null;function Hs(){Cn=null}var iv=new Set(["sh","bash","zsh","fish"]),ov=new Set(["env","nohup","timeout","gtimeout"]),av=new Set(["node","nodejs","bun","tsx"]),lv=new Set(["-e","--eval","-p","--print"]),cv=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function uv(t){return t.replace(/^['"]|['"]$/g,"")}function Ju(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(uv)}function $u(t){let e=(0,rt.basename)(t);return e==="claude"||e==="codex"?e:null}function dv(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=Ku(Ju(e.trim()),!0);if(n)return n}return null}function Ku(t,e=!1){let n=0;for(;n<t.length;){let s=t[n],r=(0,rt.basename)(s);if(ov.has(r)){if(n+=1,r==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(r==="timeout"||r==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(iv.has(r)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?dv(l):null}}return null}if(av.has(r)){let o=n+1;for(;o<t.length;){let l=t[o];if(lv.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,cv.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=$u(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=$u(s);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Vi(t,e=!1){return Ku(Ju(t),e)}function Us(t){let e=Vi(t);return e?{agent:e.agent,args:e.args}:null}function Xu(t){return nv.test(t)&&Vi(t)!==null}function fv(t,e){let n=Us(e);if(!n||n.agent!==t)return null;let{args:s}=n;if(t==="claude"){for(let r=0;r<s.length;r+=1){let i=s[r];if((i==="--resume"||i==="--session-id")&&s[r+1]&&!s[r+1].startsWith("-"))return s[r+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(s[0]!=="resume")return null;for(let r=1;r<s.length;r+=1){let i=s[r];if(!i.startsWith("-"))return i}return null}function pv(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],s=t[e+1],r=n==="--permission-mode"?s:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(r==="plan")return"plan";if(r==="acceptEdits")return"acceptEdits";if(r==="default")return"normal"}}function hv(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function gv(t,e){let n=Us(e);if(!(!n||n.agent!==t))return t==="claude"?pv(n.args):hv(n.args)}function Ds(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function mv(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function yv(t,e){let n=Vi(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(s=>s.startsWith("--listen=")))}function vv(t){let e=[...new Set(t.sessionFiles)].filter(i=>mv(t.agent,i)),n=fv(t.agent,t.command),s=gv(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...s?{approvalMode:s}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let r=Lt(t.agent,e[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",...s?{approvalMode:s}:{},sessionFilePath:e[0]}:null}function Sv(t,e){let n=t,s=e;(Ds(e.confidence)>Ds(t.confidence)||Ds(e.confidence)===Ds(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,s=t);let r=n.approvalMode??s.approvalMode;return{...n,cwd:n.cwd||s.cwd,...r?{approvalMode:r}:{},title:n.title??s.title,sessionFilePath:n.sessionFilePath??s.sessionFilePath,isResponding:n.isResponding??s.isResponding}}function Qi(t){let e=new Map;for(let n of t){let s=`${n.agent}:${n.sessionId}`,r=e.get(s);e.set(s,r?Sv(r,n):n)}return[...e.values()]}function _v(t){try{return process.kill(t,0),!0}catch{return!1}}async function Ws(t,e,n=tv){try{let{stdout:s}=await ev(t,e,{maxBuffer:8388608,timeout:n});return s}catch(s){let r=typeof s=="object"&&s!==null?{code:"code"in s?s.code:void 0,signal:"signal"in s?s.signal:void 0,killed:"killed"in s?s.killed:void 0}:{},i=String(s);return i.includes("ESRCH")||i.includes("No such process")?Bs.debug({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command skipped \u2014 process exited"):Bs.warn({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command failed"),""}}async function bv(t){if(!t.sessionFilePath)return t;let e=await it(t.sessionFilePath,t.agent);if(!e)return null;let n=await Ji(t.sessionFilePath,t.agent),s=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...s?{approvalMode:s}:{},title:t.title??e.title,isResponding:n.isResponding}}async function wv(t){return process.platform==="win32"?"":(await Ws("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
97
- `).find(s=>s.startsWith("n"))?.slice(1).trim()??""}async function Iv(t){if(process.platform==="win32")return[];let n=(await Ws("lsof",["-p",String(t),"-Fn"])).split(`
98
- `).filter(s=>s.startsWith("n")).map(s=>s.slice(1).trim()).filter(s=>s.endsWith(".jsonl")?s.includes("/.claude/projects/")||s.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Av(t){return t.split(`
99
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let s=Number(n[1]),r=n[2];if(!Xu(r))return null;let i=Us(r);return!Number.isFinite(s)||!i?null:{pid:s,command:r,agent:i.agent}}).filter(e=>!!e)}async function Tv(){let t=await Ws("ps",["-axo","pid=,command="],Yu);return Av(t)}async function Cv(){return(await Ws("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],Yu)).split(`
100
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let s=Number(n[n.length-1]),r=n.slice(1,n.length-1).join(",");if(!Number.isFinite(s)||s===0||!Xu(r))return null;let i=Us(r);return i?{pid:s,command:r,agent:i.agent}:null}).filter(e=>!!e)}async function kv(){return process.platform==="win32"?Cv():Tv()}async function xv(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await kv();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let s=n.filter(o=>_v(o.pid));t&&(t.aliveProcesses=s.length);let r=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(s.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await wv(o.pid),sessionFiles:await Iv(o.pid)})));return t&&(t.lsofMs+=r()),t&&(t.snapshots=i.length),i}function Rv(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Ev(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,rt.join)((0,Vu.homedir)(),".claude","projects",Rv(e)),r=(await(0,Fs.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(r.length===0)return null;let i=null;if(await Promise.all(r.map(async l=>{let u=await(0,Fs.stat)((0,rt.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,rt.join)(n,i.name),a=Lt(t,o);return a?{sessionId:a,filePath:o}:null}return ed(e)}catch{return null}}async function Pv(){let t={pgrepMs:0,lsofMs:0,fallbackMs:0,hydrateMs:0,totalMs:0,matchedProcesses:0,aliveProcesses:0,snapshots:0,directCandidates:0,fallbackLookups:0,fallbackHits:0,hydratedCandidates:0},e=_.startTimer("process.scan.total_ms"),n=await xv(t),s=[],r=[];for(let c of n){let d=vv(c);if(d){s.push(d);continue}yv(c.agent,c.command)&&r.push(c)}t.directCandidates=s.length,t.fallbackLookups=r.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(r.map(async c=>{let d=await Ev(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...s,...o.filter(c=>c!==null)].map(c=>bv(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Qi(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=sv||t.fallbackLookups>0)&&Bs.info({durationMs:t.totalMs,pgrepMs:t.pgrepMs,lsofMs:t.lsofMs,fallbackMs:t.fallbackMs,hydrateMs:t.hydrateMs,matchedProcesses:t.matchedProcesses,aliveProcesses:t.aliveProcesses,snapshots:t.snapshots,directCandidates:t.directCandidates,fallbackLookups:t.fallbackLookups,fallbackHits:t.fallbackHits,hydratedCandidates:t.hydratedCandidates,sessions:u.length},"process running sessions scanned"),Cn={value:u,expiresAt:Date.now()+rv},u}async function Yi(){return Cn&&Date.now()<Cn.expiresAt?Cn.value:Tn||(Tn=Pv().finally(()=>{Tn=null}),Tn)}async function Zu(t){try{return(await Yi()).some(n=>n.sessionId===t)}catch(e){return Bs.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var sd=require("fs"),He=require("fs/promises"),Xi=require("os"),xn=require("path");var kn=M.child({module:"activity-watcher"}),Mv=12e4,Lv=5e3,Nv=6e4,td=5;function Ov(){return(0,xn.join)((0,Xi.homedir)(),".claude","projects")}function Dv(){return(0,xn.join)((0,Xi.homedir)(),".codex","sessions")}async function nd(t){try{return await(0,He.realpath)(t)}catch{return t}}function qs(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Ki=class{entries=new Map;filePathIndex=new Map;metaInFlight=new Map;roots=new Map;watchers=[];pollTimers=[];rescanTimer=null;listeners=new Set;started=!1;async start(e){if(this.started)return;this.started=!0;let n=await nd(e?.claudeDir??Ov()),s=await nd(e?.codexDir??Dv());if(this.roots.set(n,"claude"),this.roots.set(s,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",s)]),this.updateGauges(),e?.usePolling){let r=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},r);a.unref?.(),this.pollTimers.push(a)}}else for(let[r,i]of this.roots)this.startNativeWatch(r,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(r=>{kn.warn({error:String(r)},"activity watcher rescan failed")})},Nv),this.rescanTimer.unref?.(),kn.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let s=(0,sd.watch)(e,{recursive:!0,persistent:!0},(r,i)=>{if(!i)return;let o=(0,xn.join)(e,i.toString());qs(o,n)&&this.resolveFsEvent(n,o)});s.on("error",r=>{kn.warn({error:String(r),root:e},"activity watcher error")}),this.watchers.push(s)}catch(s){kn.warn({error:String(s),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let s=await(0,He.stat)(n).catch(()=>null);if(!s){this.handleUnlink(n);return}s.isFile()&&await this.handleFsChange(n,s.mtimeMs)}async pollScan(e,n){let s=await this.walkSessionFiles(n,td),r=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of s){if(!qs(o,e))continue;r.add(o);let l=this.filePathIndex.get(o);if(l){let c=this.entries.get(l);if(!c||a<=c.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(r.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,s]of this.roots)if(e===n||e.startsWith(`${n}/`))return s;return null}listActive(e=Mv){let n=Date.now(),s=n-e,r=n-Lv,i=[];for(let o of this.entries.values())o.lastActivityMs<s||i.push({...o,isResponding:o.lastActivityMs>=r});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let s=await this.walkSessionFiles(n,td);await Promise.all(s.map(async({filePath:r,mtimeMs:i})=>{qs(r,e)&&await this.ingestPath(e,r,i,i)}))}async walkSessionFiles(e,n){let s=[],r=async(i,o)=>{if(o>n)return;let a=await(0,He.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,xn.join)(i,l.name);if(l.isDirectory()){await r(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,He.stat)(u).catch(()=>null);c&&s.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await r(e,0),s}async handleFsChange(e,n){let s=this.identifyAgent(e);if(!s||!qs(e,s))return;let r=Date.now(),i=n??r;await this.ingestPath(s,e,r,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,s,r){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,s,r);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await it(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,s),c.mtimeMs=Math.max(c.mtimeMs,r),c.filePath!==n&&(this.filePathIndex.delete(c.filePath),c.filePath=n),this.filePathIndex.set(n,u);return}this.entries.set(u,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:s,mtimeMs:r}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,s){let r=this.entries.get(e);if(!r)return!1;let i=Math.max(r.lastActivityMs,n),o=Math.max(r.mtimeMs,s);return i===r.lastActivityMs&&o===r.mtimeMs?!1:(r.lastActivityMs=i,r.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[s,r]of this.entries)e.push((async()=>{let i=await(0,He.stat)(r.filePath).catch(()=>null);return i?i.mtimeMs>r.mtimeMs?this.touchEntry(s,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(r.filePath),this.entries.delete(s),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){kn.warn({error:String(n)},"activity listener failed")}}updateGauges(){_.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[],this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},Nt=new Ki;var Ue=M.child({module:"inventory"}),ld=6e3,Bv=3e4,Fv=1e4;function Hv(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function Uv(){return Nt.listActive().map(Hv)}var cd={listScannedSessions:Mn,listWatcherSessions:Uv,scanRunningSessions:Yi,searchSessionContent:yd},de=Wv(),En=null,Gs=0,$s=0,js=0,Zi=0,eo=new Set;function Wv(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function qv(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,branch:t.branch,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,lastUsage:t.lastUsage,interruptReason:t.interruptReason,stallWarning:t.stallWarning})}function Gv(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 rd(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(qv).sort(),runningSessions:t.runningSessions.map(Gv).sort()})}function ud(){for(let t of eo)try{t()}catch(e){Ue.warn({error:String(e)},"session inventory backfill listener failed")}}function Rn(){_.gauge("session.inventory.external_cached_sessions",de.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",de.runningSessions.length),_.gauge("session.inventory.backfill_inflight",En?1:0)}function dd(t){return eo.add(t),()=>{eo.delete(t)}}function fd(){return{cachedSessions:de.scannedSessions.length,runningSessions:de.runningSessions.length,cacheAgeMs:de.refreshedAt?Math.max(0,Date.now()-de.refreshedAt):void 0,backfillInFlight:!!En,lastBackfillDurationMs:js||void 0,lastBackfillCompletedAt:$s?new Date($s).toISOString():void 0,lastBackfillAppliedAt:Zi?new Date(Zi).toISOString():void 0}}Rn();function pd(){return Nt.onActivity(()=>{md(cd,ld)})}var Ot={daemonActive:3,externalRunning:2,idle:1},id={high:3,medium:2,low:1};function hd(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function jv(t,e){let n=t.runtime.needsAttention?1:0,s=e.runtime.needsAttention?1:0,r=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return s-n||i-r||Ot[e.runtime.state]-Ot[t.runtime.state]||hd(t,e)}function $v(t,e){return Ot[e.state]>Ot[t.state]?e:Ot[e.state]<Ot[t.state]?t:id[e.confidence]>id[t.confidence]?e:t}function zv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Vv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Qv(t,e){return e?t?!(Mt(e)&&!Mt(t)):!0:!1}function to(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Yv(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...to(),...t.interruptReason||t.stallWarning?{needsAttention:!0}:{}},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function Jv(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",...t.pid!==void 0?{pid:t.pid}:{},...t.command!==void 0?{command:t.command}:{},isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function Kv(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||!!t.interruptReason||!!t.stallWarning||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function Xv(t,e){for(let n of e){let s=`${n.agent}:${n.sessionId}`,r=t.get(s);if(!r){t.set(s,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Qv(r.title,n.title)?n.title:r.title,o=n.cwd||r.cwd,a=n.branch??r.branch,l=$v(r.runtime,n.runtime),u=r.sources.slice();for(let h of n.sources)u.includes(h)||u.push(h);let c=n.sources.includes("process"),d=r.sources.includes("process")&&!r.sources.includes("daemon"),f=c?r.lastActivityAt:d?n.lastActivityAt:Vv(r.lastActivityAt,n.lastActivityAt);t.set(s,{...r,cwd:o,model:n.model??r.model,branch:a,title:i,createdAt:zv(r.createdAt,n.createdAt),lastActivityAt:f,sources:u,runtime:l,managed:r.managed||n.managed,approvalMode:n.approvalMode??r.approvalMode,observedApprovalMode:n.observedApprovalMode??r.observedApprovalMode,lastUsage:n.lastUsage??r.lastUsage,interruptReason:n.interruptReason??r.interruptReason,stallWarning:n.stallWarning??r.stallWarning})}}function Zv(...t){let e=new Map;for(let n of t)Xv(e,n);return[...e.values()]}function eS(t,e,n,s,r,i,o){let a=s?.toLowerCase(),l=o&&o>0?o:0,u=t.filter(c=>{if(e&&c.agent!==e||n&&c.cwd!==n)return!1;if(l>0&&c.runtime.state==="idle"){let d=Date.parse(c.lastActivityAt);if(Number.isFinite(d)&&d<l)return!1}if(a){let d=(c.title??"").toLowerCase(),f=i?.[c.sessionId]?.toLowerCase()??"",h=d.includes(a)||(f?f.includes(a):!1),g=r?.has(c.sessionId)??!1;if(!h&&!g)return!1}return!0});return(s||l>0)&&Ue.info({total:t.length,filtered:u.length,search:s,contentMatchIds:r?.size??0,sinceMs:l||void 0},"filter applied"),u}function tS(t,e){if(!e)return 0;let n=0,s=t.length;for(;n<s;){let r=n+s>>1,i=t[r];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?s=r:n=r+1}if(n>0){let r=t[n-1];if(r.lastActivityAt===e.lastActivityAt&&r.sessionId===e.sessionId)return n}return 0}function od(t,e,n,s,r,i,o,a,l){let u=i?1/0:Math.max(1,e||50),c=Zv(t.sessionRecords.map(Yv),t.scannedSessions,t.runningSessions.map(A=>Jv(A,t.scannedAt)),t.activeSessions.map(Kv)),d=t.deletedSessionIds?.size?c.filter(A=>!t.deletedSessionIds?.has(A.sessionId)):c,f=eS(d,s,r,i,o,a,l),h=f.filter(A=>A.runtime.state!=="idle"||A.managed).sort(jv),g=f.filter(A=>A.runtime.state==="idle"&&!A.managed).sort(hd),m=tS(g,n),p=g.slice(m,m+u),C=m+p.length<g.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...h,...p],nextCursor:C}}async function ad(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,s]=await Promise.all([Gu(e),ju(e)]),r=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=s.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(r=!0,{...o,branch:a,diffStat:l})});return r?{...t,sessions:i}:t}function Pn(t,e,n,s,r,i){return new Promise(o=>{let a=Date.now(),l=!1,u=!1,c=null,d=f=>{l||(l=!0,c&&(clearTimeout(c),c=null),o(f))};c=setTimeout(()=>{if(l)return;let f=Array.isArray(r)&&r.length>0;Ue.warn({source:t,timeoutMs:s,durationMs:Date.now()-a,partial:f?r.length:0},f?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u=!0,d(f?r:n)},s),typeof c=="object"&&"unref"in c&&c.unref(),e().then(f=>{let h=u;if(d(f),h&&i)try{i(f)}catch(g){Ue.warn({source:t,error:String(g)},"inventory source late-result handler failed")}}).catch(f=>{l||Ue.warn({source:t,error:String(f)},"session inventory source failed, using fallback"),d(n)})})}function nS(t=Date.now()){return de.refreshedAt===0||t-de.refreshedAt>=Fv}async function gd(t,e){let[n,s]=await Promise.all([Pn("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),Pn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Qi([...n,...s])}async function sS(t,e){let n=new Date().toISOString(),s=[],[r,i]=await Promise.all([Pn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,s),[],e,s),gd(t,e)]);return{scannedSessions:r,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function md(t,e){if(En)return;let n=Gs,s=_.startTimer("session.inventory.backfill_latency_ms");En=sS(t,e).then(r=>{if(n!==Gs)return;let i=rd(de);de=r;let o=rd(r),a=s();js=a,$s=Date.now(),Rn(),i!==o&&(Zi=Date.now(),_.increment("session.inventory.backfill_applied"),Ue.info({durationMs:a,scanned:r.scannedSessions.length,running:r.runningSessions.length},"session inventory external backfill applied"),ud())}).catch(r=>{n===Gs&&(js=s(),$s=Date.now(),Rn(),Ue.warn({error:String(r),durationMs:js},"session inventory external backfill failed"))}).finally(()=>{n===Gs&&(En=null,Rn())}),Rn()}async function zs(t){let e={...cd,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??ld),s=t.sourceTimeoutMs!==void 0?n:Bv;if(!t.search){let f=_.startTimer("session.inventory.fast_path_latency_ms");nS()&&md(e,n);let h=de,g=od({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:h.scannedSessions,runningSessions:h.runningSessions,scannedAt:h.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles,t.sinceMs);if(t.skipGitMetadata)return f(),g;let m=await ad(g);return f(),m}let r=[],i=new Date().toISOString(),o=t.search,a=t.sinceMs,[l,u,c]=await Promise.all([Pn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),gd(e,n),Pn("scanner.search_content",()=>e.searchSessionContent(o,t.agent,a),void 0,s,void 0,f=>{f&&f.size>0&&ud()})]);Ue.info({search:t.search,sinceMs:a&&a>0?a:void 0,contentMatches:c?.size??0,scanned:l.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let d=od({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:l,runningSessions:u,scannedAt:i,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,o,c,t.customTitles,a);return t.skipGitMetadata?d:ad(d)}var Te=M.child({module:"scanner"});function co(t){let e=new Map;return{get(n){let s=e.get(n);if(s){if(Date.now()>s.expiresAt){e.delete(n);return}return s.value}},set(n,s){e.set(n,{value:s,expiresAt:Date.now()+t})},clear(){e.clear()}}}var uo=3e4,io=co(uo),oo=co(uo),Qs=co(uo),no=new Map,so=new Map,Vs=null,ot=24;function Ks(){io.clear(),oo.clear(),Qs.clear()}function Td(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function at(t,e,n){if(t.length===0)return[];let s=Math.max(1,Math.min(e,t.length)),r=new Array(t.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;r[o]=await n(t[o],o)}})),r}async function Cd(t){let e=await at(t,ot,async n=>{let s=await(0,O.stat)(n).catch(()=>null);return{path:n,mtimeMs:s?.mtimeMs??0}});return e.sort((n,s)=>s.mtimeMs-n.mtimeMs),e}async function rS(){let t=(0,F.join)((0,ye.homedir)(),".claude","projects"),e=[],n=await(0,O.readdir)(t,{withFileTypes:!0}).catch(()=>[]);for(let s of n){if(!s.isDirectory())continue;let r=(0,F.join)(t,s.name),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i)o.endsWith(".jsonl")&&e.push((0,F.join)(r,o))}return e}async function iS(){let t=(0,F.join)((0,ye.homedir)(),".codex","sessions"),e=[],n=await(0,O.readdir)(t).catch(()=>[]);for(let s of n){let r=(0,F.join)(t,s),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i){let a=(0,F.join)(r,o),l=await(0,O.readdir)(a).catch(()=>[]);for(let u of l){let c=(0,F.join)(a,u),d=await(0,O.readdir)(c).catch(()=>[]);for(let f of d)f.endsWith(".jsonl")&&e.push((0,F.join)(c,f))}}}return e}async function fo(){let t=await iS();return Cd(t)}function oS(t){let e=`codex-latest:${(0,ye.homedir)()}`,n=new Map;for(let s of t)n.has(s.cwd)||n.set(s.cwd,s.match);Qs.set(e,n)}function*kd(t,e){let n=0,s=0;for(;n<t.length&&s<e;){let r=t.indexOf(`
101
- `,n);r===-1&&(r=t.length);let i=t.substring(n,r);n=r+1,!(i.length===0||i.trim().length===0)&&(yield i,s+=1)}}var ro=512*1024,vd=256*1024;async function xd(t,e){if(e<=ro)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Buffer.alloc(ro),{bytesRead:r}=await n.read(s,0,ro,0);return s.toString("utf-8",0,r)}finally{await n.close()}}async function Rd(t,e){if(e<=vd)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Math.max(0,e-vd),r=Buffer.alloc(e-s),{bytesRead:i}=await n.read(r,0,r.length,s);return r.toString("utf-8",0,i)}finally{await n.close()}}function Sd(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function aS(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,s=typeof n?.type=="string"?n.type:"",r=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&s==="danger-full-access")return"autoApprove";if(e==="on-request"&&s==="workspace-write")return r?.length?"normal":"plan"}function lS(t){return t?.type==="permission-mode"?Sd(t.permissionMode):Sd(t?.permissionMode)}function cS(t){if(t?.type==="turn_context")return aS(t.payload)}function uS(t){if(t?.type!=="event_msg"||t.payload?.type!=="token_count")return;let e=t.payload.info;if(!e||typeof e!="object")return;let n=e.last_token_usage;if(!n||typeof n!="object")return;let s=Number(n.input_tokens),r=Number(n.output_tokens);if(!Number.isFinite(s)||!Number.isFinite(r))return;let i=Number(e.model_context_window);return{inputTokens:s,outputTokens:r,...Number.isFinite(i)&&i>0?{contextWindowTokens:i}:{}}}async function dS(t,e){let n,s,r=await Rd(t,e);for(let i of r.split(`
102
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=cS(o);a&&(n=a);let l=uS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function _d(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.input_tokens??e.inputTokens),s=Number(e.output_tokens??e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.cache_creation_input_tokens??e.cacheCreationInputTokens),i=Number(e.cache_read_input_tokens??e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(r)?{cacheCreationInputTokens:r}:{},...Number.isFinite(i)?{cacheReadInputTokens:i}:{}}}function fS(t){return t?.type==="assistant"?_d(t.message?.usage??t.usage):_d(t?.toolUseResult?.usage)}async function Ed(t,e){let n,s,r=await Rd(t,e);for(let i of r.split(`
103
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=lS(o);a&&(n=a);let l=fS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function po(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 Pd(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?po(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Xs(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 pS=/^\[Attached image: ([^\n]+)\]$/gm;function hS(t){let e=[],n=new Set;for(let s of t.matchAll(pS)){let r=s[1]?.trim();!r||n.has(r)||(n.add(r),e.push(r))}return e}function gS(t){if(t.role!=="user")return t;let e=[...t.images??[],...hS(t.content)].filter((n,s,r)=>n&&r.indexOf(n)===s);return e.length?{...t,images:e}:t}var mS=["<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 yS(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?mS.some(s=>n.startsWith(s)):!1}function Zs(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Xs(t.message.content);return yS(t,e)?"":e}function vS(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function SS(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(s=>!s||typeof s!="object"?"":typeof s.text=="string"?s.text:typeof s.content=="string"?s.content:"").filter(Boolean).join(`
95
+ Your message was received: "${n}"`:Lu;this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!(this.stopped||!this.sessionId)&&(this.emit({type:"text.delta",sessionId:this.sessionId,content:s}),this.responding=!1,this.emit({type:"session.done",sessionId:this.sessionId,usage:{inputTokens:Math.max(1,Math.ceil(e.length/4)),outputTokens:Math.max(1,Math.ceil(s.length/4))}}))},25)}respondApproval(){return!1}getRespondingLivenessHint(){return this.responding?"alive":"unknown"}interrupt(){!this.responding||!this.sessionId||(this.clearPendingTimer(),this.responding=!1,this.emit({type:"session.interrupted",sessionId:this.sessionId}))}stop(){this.clearPendingTimer(),this.responding=!1,this.stopped=!0,this.exitHandler?.(0)}setApprovalMode(){}onMessage(e){this.messageHandler=e}onExit(e){this.exitHandler=e}emit(e){this.messageHandler?.(e)}clearPendingTimer(){this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null)}};var O=require("fs/promises"),ao=require("fs"),lo=require("readline"),H=require("path"),ye=require("os");var Uy=new Set(["New session","Resumed session","Untitled session"]),Wy=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function qy(t){return t.replace(/\s+/g," ").trim()}function Ns(t){return typeof t!="string"?void 0:qy(t)||void 0}function Ou(t){let e=Ns(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 Mt(t){let e=Ns(t);return!e||Uy.has(e)||Ou(e)}function Gy(t){for(let e of t.replace(/\r/g,"").split(`
96
+ `)){let n=Ns(e);if(n&&!jy(n)&&!$y(n))return n}}function jy(t){return Wy.some(e=>t.startsWith(e))}function $y(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function zy(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 s=t[e+1];if(!s||/\s/.test(s))return e+1}}return-1}function Gi(t,e=80){if(typeof t!="string")return;let n=Gy(t);if(!n)return;let s=zy(n),i=(s>0?n.slice(0,s):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Ou(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function st(t,e){for(let n of t){let s=Ns(n);if(!(!s||Mt(s)))return s}return Gi(e)}var Fu=require("child_process"),Hu=require("util");var Uu=(0,Hu.promisify)(Fu.execFile),Wu=5e3,Vy=2500,Qy=3e3,qu=8,Os=new Map,ji=new Map,Du=null;function Yy(t){let e=Os.get(t);return e?Date.now()>e.expiresAt?(Os.delete(t),null):e.value??void 0:null}function Jy(t,e){if(e===void 0){Os.delete(t);return}Os.set(t,{value:e,expiresAt:Date.now()+Wu})}async function Ky(t){if(!t)return;if(Du)return Du(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:s}=await Uu("git",["-C",t,...n],{env:et(),timeout:Vy,maxBuffer:65536}),r=s.trim();if(r&&r!=="HEAD")return r}catch{}}async function Xy(t){let e=Yy(t);if(e!==null)return e;let n=ji.get(t);if(n)return n;let s=Ky(t).then(r=>(Jy(t,r),r)).finally(()=>{ji.delete(t)});return ji.set(t,s),s}async function Gu(t,e,n){if(t.length===0)return;let s=Math.max(1,Math.min(e,t.length)),r=0;await Promise.all(Array.from({length:s},async()=>{for(;;){let i=r;if(r+=1,i>=t.length)return;await n(t[i])}}))}async function ju(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Gu(e,qu,async s=>{n.set(s,await Xy(s))}),n}var zi=new Map,$i=new Map,Bu=null;function Zy(t,e){if(e===void 0){zi.delete(t);return}zi.set(t,{value:e,expiresAt:Date.now()+Wu})}async function ev(t){if(t){if(Bu)return Bu(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await Uu("git",["-C",t,"diff","HEAD","--shortstat"],{env:et(),timeout:Qy,maxBuffer:65536}),s=n.trim();if(!s)return;let r=s.match(/(\d+) insertion/),i=s.match(/(\d+) deletion/),o=r?Number(r[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function tv(t){let e=zi.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=$i.get(t);if(n)return n;let s=ev(t).then(r=>(Zy(t,r),r)).finally(()=>{$i.delete(t)});return $i.set(t,s),s}async function $u(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Gu(e,qu,async s=>{n.set(s,await tv(s))}),n}var Vu=require("child_process"),Fs=require("fs/promises"),rt=require("path"),Qu=require("os"),Yu=require("util");var nv=(0,Yu.promisify)(Vu.execFile),Bs=L.child({module:"process-scanner"}),Ju=5e3,sv=1500,rv=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,iv=500,ov=15e3,Cn=null,Tn=null;function Hs(){Cn=null}var av=new Set(["sh","bash","zsh","fish"]),lv=new Set(["env","nohup","timeout","gtimeout"]),cv=new Set(["node","nodejs","bun","tsx"]),uv=new Set(["-e","--eval","-p","--print"]),dv=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function fv(t){return t.replace(/^['"]|['"]$/g,"")}function Ku(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(fv)}function zu(t){let e=(0,rt.basename)(t);return e==="claude"||e==="codex"?e:null}function pv(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=Xu(Ku(e.trim()),!0);if(n)return n}return null}function Xu(t,e=!1){let n=0;for(;n<t.length;){let s=t[n],r=(0,rt.basename)(s);if(lv.has(r)){if(n+=1,r==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(r==="timeout"||r==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(av.has(r)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?pv(l):null}}return null}if(cv.has(r)){let o=n+1;for(;o<t.length;){let l=t[o];if(uv.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,dv.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=zu(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=zu(s);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Vi(t,e=!1){return Xu(Ku(t),e)}function Us(t){let e=Vi(t);return e?{agent:e.agent,args:e.args}:null}function Zu(t){return rv.test(t)&&Vi(t)!==null}function hv(t,e){let n=Us(e);if(!n||n.agent!==t)return null;let{args:s}=n;if(t==="claude"){for(let r=0;r<s.length;r+=1){let i=s[r];if((i==="--resume"||i==="--session-id")&&s[r+1]&&!s[r+1].startsWith("-"))return s[r+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(s[0]!=="resume")return null;for(let r=1;r<s.length;r+=1){let i=s[r];if(!i.startsWith("-"))return i}return null}function gv(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],s=t[e+1],r=n==="--permission-mode"?s:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(r==="plan")return"plan";if(r==="acceptEdits")return"acceptEdits";if(r==="default")return"normal"}}function mv(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function yv(t,e){let n=Us(e);if(!(!n||n.agent!==t))return t==="claude"?gv(n.args):mv(n.args)}function Ds(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function vv(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Sv(t,e){let n=Vi(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(s=>s.startsWith("--listen=")))}function _v(t){let e=[...new Set(t.sessionFiles)].filter(i=>vv(t.agent,i)),n=hv(t.agent,t.command),s=yv(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...s?{approvalMode:s}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let r=Lt(t.agent,e[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",...s?{approvalMode:s}:{},sessionFilePath:e[0]}:null}function bv(t,e){let n=t,s=e;(Ds(e.confidence)>Ds(t.confidence)||Ds(e.confidence)===Ds(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,s=t);let r=n.approvalMode??s.approvalMode;return{...n,cwd:n.cwd||s.cwd,...r?{approvalMode:r}:{},title:n.title??s.title,sessionFilePath:n.sessionFilePath??s.sessionFilePath,isResponding:n.isResponding??s.isResponding}}function Qi(t){let e=new Map;for(let n of t){let s=`${n.agent}:${n.sessionId}`,r=e.get(s);e.set(s,r?bv(r,n):n)}return[...e.values()]}function wv(t){try{return process.kill(t,0),!0}catch{return!1}}async function Ws(t,e,n=sv){try{let{stdout:s}=await nv(t,e,{maxBuffer:8388608,timeout:n});return s}catch(s){let r=typeof s=="object"&&s!==null?{code:"code"in s?s.code:void 0,signal:"signal"in s?s.signal:void 0,killed:"killed"in s?s.killed:void 0}:{},i=String(s);return i.includes("ESRCH")||i.includes("No such process")?Bs.debug({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command skipped \u2014 process exited"):Bs.warn({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command failed"),""}}async function Iv(t){if(!t.sessionFilePath)return t;let e=await it(t.sessionFilePath,t.agent);if(!e)return null;let n=await Ji(t.sessionFilePath,t.agent),s=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...s?{approvalMode:s}:{},title:t.title??e.title,isResponding:n.isResponding}}async function Av(t){return process.platform==="win32"?"":(await Ws("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
97
+ `).find(s=>s.startsWith("n"))?.slice(1).trim()??""}async function Tv(t){if(process.platform==="win32")return[];let n=(await Ws("lsof",["-p",String(t),"-Fn"])).split(`
98
+ `).filter(s=>s.startsWith("n")).map(s=>s.slice(1).trim()).filter(s=>s.endsWith(".jsonl")?s.includes("/.claude/projects/")||s.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Cv(t){return t.split(`
99
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let s=Number(n[1]),r=n[2];if(!Zu(r))return null;let i=Us(r);return!Number.isFinite(s)||!i?null:{pid:s,command:r,agent:i.agent}}).filter(e=>!!e)}async function kv(){let t=await Ws("ps",["-axo","pid=,command="],Ju);return Cv(t)}async function xv(){return(await Ws("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],Ju)).split(`
100
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let s=Number(n[n.length-1]),r=n.slice(1,n.length-1).join(",");if(!Number.isFinite(s)||s===0||!Zu(r))return null;let i=Us(r);return i?{pid:s,command:r,agent:i.agent}:null}).filter(e=>!!e)}async function Rv(){return process.platform==="win32"?xv():kv()}async function Ev(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await Rv();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let s=n.filter(o=>wv(o.pid));t&&(t.aliveProcesses=s.length);let r=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(s.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await Av(o.pid),sessionFiles:await Tv(o.pid)})));return t&&(t.lsofMs+=r()),t&&(t.snapshots=i.length),i}function Pv(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Mv(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,rt.join)((0,Qu.homedir)(),".claude","projects",Pv(e)),r=(await(0,Fs.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(r.length===0)return null;let i=null;if(await Promise.all(r.map(async l=>{let u=await(0,Fs.stat)((0,rt.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,rt.join)(n,i.name),a=Lt(t,o);return a?{sessionId:a,filePath:o}:null}return td(e)}catch{return null}}async function Lv(){let t={pgrepMs:0,lsofMs:0,fallbackMs:0,hydrateMs:0,totalMs:0,matchedProcesses:0,aliveProcesses:0,snapshots:0,directCandidates:0,fallbackLookups:0,fallbackHits:0,hydratedCandidates:0},e=_.startTimer("process.scan.total_ms"),n=await Ev(t),s=[],r=[];for(let c of n){let d=_v(c);if(d){s.push(d);continue}Sv(c.agent,c.command)&&r.push(c)}t.directCandidates=s.length,t.fallbackLookups=r.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(r.map(async c=>{let d=await Mv(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...s,...o.filter(c=>c!==null)].map(c=>Iv(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Qi(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=iv||t.fallbackLookups>0)&&Bs.info({durationMs:t.totalMs,pgrepMs:t.pgrepMs,lsofMs:t.lsofMs,fallbackMs:t.fallbackMs,hydrateMs:t.hydrateMs,matchedProcesses:t.matchedProcesses,aliveProcesses:t.aliveProcesses,snapshots:t.snapshots,directCandidates:t.directCandidates,fallbackLookups:t.fallbackLookups,fallbackHits:t.fallbackHits,hydratedCandidates:t.hydratedCandidates,sessions:u.length},"process running sessions scanned"),Cn={value:u,expiresAt:Date.now()+ov},u}async function Yi(){return Cn&&Date.now()<Cn.expiresAt?Cn.value:Tn||(Tn=Lv().finally(()=>{Tn=null}),Tn)}async function ed(t){try{return(await Yi()).some(n=>n.sessionId===t)}catch(e){return Bs.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var rd=require("fs"),He=require("fs/promises"),Xi=require("os"),xn=require("path");var kn=L.child({module:"activity-watcher"}),Nv=12e4,Ov=5e3,Dv=6e4,nd=5;function Bv(){return(0,xn.join)((0,Xi.homedir)(),".claude","projects")}function Fv(){return(0,xn.join)((0,Xi.homedir)(),".codex","sessions")}async function sd(t){try{return await(0,He.realpath)(t)}catch{return t}}function qs(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Ki=class{entries=new Map;filePathIndex=new Map;metaInFlight=new Map;roots=new Map;watchers=[];pollTimers=[];rescanTimer=null;listeners=new Set;started=!1;async start(e){if(this.started)return;this.started=!0;let n=await sd(e?.claudeDir??Bv()),s=await sd(e?.codexDir??Fv());if(this.roots.set(n,"claude"),this.roots.set(s,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",s)]),this.updateGauges(),e?.usePolling){let r=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},r);a.unref?.(),this.pollTimers.push(a)}}else for(let[r,i]of this.roots)this.startNativeWatch(r,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(r=>{kn.warn({error:String(r)},"activity watcher rescan failed")})},Dv),this.rescanTimer.unref?.(),kn.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let s=(0,rd.watch)(e,{recursive:!0,persistent:!0},(r,i)=>{if(!i)return;let o=(0,xn.join)(e,i.toString());qs(o,n)&&this.resolveFsEvent(n,o)});s.on("error",r=>{kn.warn({error:String(r),root:e},"activity watcher error")}),this.watchers.push(s)}catch(s){kn.warn({error:String(s),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let s=await(0,He.stat)(n).catch(()=>null);if(!s){this.handleUnlink(n);return}s.isFile()&&await this.handleFsChange(n,s.mtimeMs)}async pollScan(e,n){let s=await this.walkSessionFiles(n,nd),r=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of s){if(!qs(o,e))continue;r.add(o);let l=this.filePathIndex.get(o);if(l){let c=this.entries.get(l);if(!c||a<=c.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(r.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,s]of this.roots)if(e===n||e.startsWith(`${n}/`))return s;return null}listActive(e=Nv){let n=Date.now(),s=n-e,r=n-Ov,i=[];for(let o of this.entries.values())o.lastActivityMs<s||i.push({...o,isResponding:o.lastActivityMs>=r});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let s=await this.walkSessionFiles(n,nd);await Promise.all(s.map(async({filePath:r,mtimeMs:i})=>{qs(r,e)&&await this.ingestPath(e,r,i,i)}))}async walkSessionFiles(e,n){let s=[],r=async(i,o)=>{if(o>n)return;let a=await(0,He.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,xn.join)(i,l.name);if(l.isDirectory()){await r(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,He.stat)(u).catch(()=>null);c&&s.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await r(e,0),s}async handleFsChange(e,n){let s=this.identifyAgent(e);if(!s||!qs(e,s))return;let r=Date.now(),i=n??r;await this.ingestPath(s,e,r,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,s,r){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,s,r);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await it(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,s),c.mtimeMs=Math.max(c.mtimeMs,r),c.filePath!==n&&(this.filePathIndex.delete(c.filePath),c.filePath=n),this.filePathIndex.set(n,u);return}this.entries.set(u,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:s,mtimeMs:r}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,s){let r=this.entries.get(e);if(!r)return!1;let i=Math.max(r.lastActivityMs,n),o=Math.max(r.mtimeMs,s);return i===r.lastActivityMs&&o===r.mtimeMs?!1:(r.lastActivityMs=i,r.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[s,r]of this.entries)e.push((async()=>{let i=await(0,He.stat)(r.filePath).catch(()=>null);return i?i.mtimeMs>r.mtimeMs?this.touchEntry(s,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(r.filePath),this.entries.delete(s),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){kn.warn({error:String(n)},"activity listener failed")}}updateGauges(){_.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[],this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},Nt=new Ki;var Ue=L.child({module:"inventory"}),cd=6e3,Hv=3e4,Uv=1e4;function Wv(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function qv(){return Nt.listActive().map(Wv)}var ud={listScannedSessions:Mn,listWatcherSessions:qv,scanRunningSessions:Yi,searchSessionContent:vd},de=Gv(),En=null,Gs=0,$s=0,js=0,Zi=0,eo=new Set;function Gv(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function jv(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,branch:t.branch,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,lastUsage:t.lastUsage,interruptReason:t.interruptReason,stallWarning:t.stallWarning})}function $v(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 id(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(jv).sort(),runningSessions:t.runningSessions.map($v).sort()})}function dd(){for(let t of eo)try{t()}catch(e){Ue.warn({error:String(e)},"session inventory backfill listener failed")}}function Rn(){_.gauge("session.inventory.external_cached_sessions",de.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",de.runningSessions.length),_.gauge("session.inventory.backfill_inflight",En?1:0)}function fd(t){return eo.add(t),()=>{eo.delete(t)}}function pd(){return{cachedSessions:de.scannedSessions.length,runningSessions:de.runningSessions.length,cacheAgeMs:de.refreshedAt?Math.max(0,Date.now()-de.refreshedAt):void 0,backfillInFlight:!!En,lastBackfillDurationMs:js||void 0,lastBackfillCompletedAt:$s?new Date($s).toISOString():void 0,lastBackfillAppliedAt:Zi?new Date(Zi).toISOString():void 0}}Rn();function hd(){return Nt.onActivity(()=>{yd(ud,cd)})}var Ot={daemonActive:3,externalRunning:2,idle:1},od={high:3,medium:2,low:1};function gd(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function zv(t,e){let n=t.runtime.needsAttention?1:0,s=e.runtime.needsAttention?1:0,r=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return s-n||i-r||Ot[e.runtime.state]-Ot[t.runtime.state]||gd(t,e)}function Vv(t,e){return Ot[e.state]>Ot[t.state]?e:Ot[e.state]<Ot[t.state]?t:od[e.confidence]>od[t.confidence]?e:t}function Qv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Yv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Jv(t,e){return e?t?!(Mt(e)&&!Mt(t)):!0:!1}function to(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Kv(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...to(),...t.interruptReason||t.stallWarning?{needsAttention:!0}:{}},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function Xv(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",...t.pid!==void 0?{pid:t.pid}:{},...t.command!==void 0?{command:t.command}:{},isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function Zv(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||!!t.interruptReason||!!t.stallWarning||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function eS(t,e){for(let n of e){let s=`${n.agent}:${n.sessionId}`,r=t.get(s);if(!r){t.set(s,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Jv(r.title,n.title)?n.title:r.title,o=n.cwd||r.cwd,a=n.branch??r.branch,l=Vv(r.runtime,n.runtime),u=r.sources.slice();for(let h of n.sources)u.includes(h)||u.push(h);let c=n.sources.includes("process"),d=r.sources.includes("process")&&!r.sources.includes("daemon"),f=c?r.lastActivityAt:d?n.lastActivityAt:Yv(r.lastActivityAt,n.lastActivityAt);t.set(s,{...r,cwd:o,model:n.model??r.model,branch:a,title:i,createdAt:Qv(r.createdAt,n.createdAt),lastActivityAt:f,sources:u,runtime:l,managed:r.managed||n.managed,approvalMode:n.approvalMode??r.approvalMode,observedApprovalMode:n.observedApprovalMode??r.observedApprovalMode,lastUsage:n.lastUsage??r.lastUsage,interruptReason:n.interruptReason??r.interruptReason,stallWarning:n.stallWarning??r.stallWarning})}}function tS(...t){let e=new Map;for(let n of t)eS(e,n);return[...e.values()]}function nS(t,e,n,s,r,i,o){let a=s?.toLowerCase(),l=o&&o>0?o:0,u=t.filter(c=>{if(e&&c.agent!==e||n&&c.cwd!==n)return!1;if(l>0&&c.runtime.state==="idle"){let d=Date.parse(c.lastActivityAt);if(Number.isFinite(d)&&d<l)return!1}if(a){let d=(c.title??"").toLowerCase(),f=i?.[c.sessionId]?.toLowerCase()??"",h=d.includes(a)||(f?f.includes(a):!1),g=r?.has(c.sessionId)??!1;if(!h&&!g)return!1}return!0});return(s||l>0)&&Ue.info({total:t.length,filtered:u.length,search:s,contentMatchIds:r?.size??0,sinceMs:l||void 0},"filter applied"),u}function sS(t,e){if(!e)return 0;let n=0,s=t.length;for(;n<s;){let r=n+s>>1,i=t[r];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?s=r:n=r+1}if(n>0){let r=t[n-1];if(r.lastActivityAt===e.lastActivityAt&&r.sessionId===e.sessionId)return n}return 0}function ad(t,e,n,s,r,i,o,a,l){let u=i?1/0:Math.max(1,e||50),c=tS(t.sessionRecords.map(Kv),t.scannedSessions,t.runningSessions.map(A=>Xv(A,t.scannedAt)),t.activeSessions.map(Zv)),d=t.deletedSessionIds?.size?c.filter(A=>!t.deletedSessionIds?.has(A.sessionId)):c,f=nS(d,s,r,i,o,a,l),h=f.filter(A=>A.runtime.state!=="idle"||A.managed).sort(zv),g=f.filter(A=>A.runtime.state==="idle"&&!A.managed).sort(gd),m=sS(g,n),p=g.slice(m,m+u),C=m+p.length<g.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...h,...p],nextCursor:C}}async function ld(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,s]=await Promise.all([ju(e),$u(e)]),r=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=s.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(r=!0,{...o,branch:a,diffStat:l})});return r?{...t,sessions:i}:t}function Pn(t,e,n,s,r,i){return new Promise(o=>{let a=Date.now(),l=!1,u=!1,c=null,d=f=>{l||(l=!0,c&&(clearTimeout(c),c=null),o(f))};c=setTimeout(()=>{if(l)return;let f=Array.isArray(r)&&r.length>0;Ue.warn({source:t,timeoutMs:s,durationMs:Date.now()-a,partial:f?r.length:0},f?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u=!0,d(f?r:n)},s),typeof c=="object"&&"unref"in c&&c.unref(),e().then(f=>{let h=u;if(d(f),h&&i)try{i(f)}catch(g){Ue.warn({source:t,error:String(g)},"inventory source late-result handler failed")}}).catch(f=>{l||Ue.warn({source:t,error:String(f)},"session inventory source failed, using fallback"),d(n)})})}function rS(t=Date.now()){return de.refreshedAt===0||t-de.refreshedAt>=Uv}async function md(t,e){let[n,s]=await Promise.all([Pn("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),Pn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Qi([...n,...s])}async function iS(t,e){let n=new Date().toISOString(),s=[],[r,i]=await Promise.all([Pn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,s),[],e,s),md(t,e)]);return{scannedSessions:r,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function yd(t,e){if(En)return;let n=Gs,s=_.startTimer("session.inventory.backfill_latency_ms");En=iS(t,e).then(r=>{if(n!==Gs)return;let i=id(de);de=r;let o=id(r),a=s();js=a,$s=Date.now(),Rn(),i!==o&&(Zi=Date.now(),_.increment("session.inventory.backfill_applied"),Ue.info({durationMs:a,scanned:r.scannedSessions.length,running:r.runningSessions.length},"session inventory external backfill applied"),dd())}).catch(r=>{n===Gs&&(js=s(),$s=Date.now(),Rn(),Ue.warn({error:String(r),durationMs:js},"session inventory external backfill failed"))}).finally(()=>{n===Gs&&(En=null,Rn())}),Rn()}async function zs(t){let e={...ud,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??cd),s=t.sourceTimeoutMs!==void 0?n:Hv;if(!t.search){let f=_.startTimer("session.inventory.fast_path_latency_ms");rS()&&yd(e,n);let h=de,g=ad({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:h.scannedSessions,runningSessions:h.runningSessions,scannedAt:h.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles,t.sinceMs);if(t.skipGitMetadata)return f(),g;let m=await ld(g);return f(),m}let r=[],i=new Date().toISOString(),o=t.search,a=t.sinceMs,[l,u,c]=await Promise.all([Pn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),md(e,n),Pn("scanner.search_content",()=>e.searchSessionContent(o,t.agent,a),void 0,s,void 0,f=>{f&&f.size>0&&dd()})]);Ue.info({search:t.search,sinceMs:a&&a>0?a:void 0,contentMatches:c?.size??0,scanned:l.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let d=ad({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:l,runningSessions:u,scannedAt:i,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,o,c,t.customTitles,a);return t.skipGitMetadata?d:ld(d)}var Te=L.child({module:"scanner"});function co(t){let e=new Map;return{get(n){let s=e.get(n);if(s){if(Date.now()>s.expiresAt){e.delete(n);return}return s.value}},set(n,s){e.set(n,{value:s,expiresAt:Date.now()+t})},clear(){e.clear()}}}var uo=3e4,io=co(uo),oo=co(uo),Qs=co(uo),no=new Map,so=new Map,Vs=null,ot=24;function Ks(){io.clear(),oo.clear(),Qs.clear()}function Cd(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function at(t,e,n){if(t.length===0)return[];let s=Math.max(1,Math.min(e,t.length)),r=new Array(t.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;r[o]=await n(t[o],o)}})),r}async function kd(t){let e=await at(t,ot,async n=>{let s=await(0,O.stat)(n).catch(()=>null);return{path:n,mtimeMs:s?.mtimeMs??0}});return e.sort((n,s)=>s.mtimeMs-n.mtimeMs),e}async function oS(){let t=(0,H.join)((0,ye.homedir)(),".claude","projects"),e=[],n=await(0,O.readdir)(t,{withFileTypes:!0}).catch(()=>[]);for(let s of n){if(!s.isDirectory())continue;let r=(0,H.join)(t,s.name),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i)o.endsWith(".jsonl")&&e.push((0,H.join)(r,o))}return e}async function aS(){let t=(0,H.join)((0,ye.homedir)(),".codex","sessions"),e=[],n=await(0,O.readdir)(t).catch(()=>[]);for(let s of n){let r=(0,H.join)(t,s),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i){let a=(0,H.join)(r,o),l=await(0,O.readdir)(a).catch(()=>[]);for(let u of l){let c=(0,H.join)(a,u),d=await(0,O.readdir)(c).catch(()=>[]);for(let f of d)f.endsWith(".jsonl")&&e.push((0,H.join)(c,f))}}}return e}async function fo(){let t=await aS();return kd(t)}function lS(t){let e=`codex-latest:${(0,ye.homedir)()}`,n=new Map;for(let s of t)n.has(s.cwd)||n.set(s.cwd,s.match);Qs.set(e,n)}function*xd(t,e){let n=0,s=0;for(;n<t.length&&s<e;){let r=t.indexOf(`
101
+ `,n);r===-1&&(r=t.length);let i=t.substring(n,r);n=r+1,!(i.length===0||i.trim().length===0)&&(yield i,s+=1)}}var ro=512*1024,Sd=256*1024;async function Rd(t,e){if(e<=ro)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Buffer.alloc(ro),{bytesRead:r}=await n.read(s,0,ro,0);return s.toString("utf-8",0,r)}finally{await n.close()}}async function Ed(t,e){if(e<=Sd)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Math.max(0,e-Sd),r=Buffer.alloc(e-s),{bytesRead:i}=await n.read(r,0,r.length,s);return r.toString("utf-8",0,i)}finally{await n.close()}}function _d(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function cS(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,s=typeof n?.type=="string"?n.type:"",r=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&s==="danger-full-access")return"autoApprove";if(e==="on-request"&&s==="workspace-write")return r?.length?"normal":"plan"}function uS(t){return t?.type==="permission-mode"?_d(t.permissionMode):_d(t?.permissionMode)}function dS(t){if(t?.type==="turn_context")return cS(t.payload)}function fS(t){if(t?.type!=="event_msg"||t.payload?.type!=="token_count")return;let e=t.payload.info;if(!e||typeof e!="object")return;let n=e.last_token_usage;if(!n||typeof n!="object")return;let s=Number(n.input_tokens),r=Number(n.output_tokens);if(!Number.isFinite(s)||!Number.isFinite(r))return;let i=Number(e.model_context_window);return{inputTokens:s,outputTokens:r,...Number.isFinite(i)&&i>0?{contextWindowTokens:i}:{}}}async function pS(t,e){let n,s,r=await Ed(t,e);for(let i of r.split(`
102
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=dS(o);a&&(n=a);let l=fS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function bd(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.input_tokens??e.inputTokens),s=Number(e.output_tokens??e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.cache_creation_input_tokens??e.cacheCreationInputTokens),i=Number(e.cache_read_input_tokens??e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(r)?{cacheCreationInputTokens:r}:{},...Number.isFinite(i)?{cacheReadInputTokens:i}:{}}}function hS(t){return t?.type==="assistant"?bd(t.message?.usage??t.usage):bd(t?.toolUseResult?.usage)}async function Pd(t,e){let n,s,r=await Ed(t,e);for(let i of r.split(`
103
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=uS(o);a&&(n=a);let l=hS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function po(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 Md(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?po(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Xs(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 gS=/^\[Attached image: ([^\n]+)\]$/gm;function mS(t){let e=[],n=new Set;for(let s of t.matchAll(gS)){let r=s[1]?.trim();!r||n.has(r)||(n.add(r),e.push(r))}return e}function yS(t){if(t.role!=="user")return t;let e=[...t.images??[],...mS(t.content)].filter((n,s,r)=>n&&r.indexOf(n)===s);return e.length?{...t,images:e}:t}var vS=["<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 SS(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?vS.some(s=>n.startsWith(s)):!1}function Zs(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Xs(t.message.content);return SS(t,e)?"":e}function _S(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function bS(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(s=>!s||typeof s!="object"?"":typeof s.text=="string"?s.text:typeof s.content=="string"?s.content:"").filter(Boolean).join(`
104
104
  `):""}).filter(Boolean).join(`
105
- `):""}function _S(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(`
106
- `):""}function bd(t){if(typeof t=="string")return t;let e=_S(t);return e||(Array.isArray(t)&&t.length>0&&t.every(s=>s&&typeof s=="object"&&s.type==="tool_reference")?"":JSON.stringify(t))}var bS=/Claude requested permissions to (?:edit|write to) (.+?) which is a sensitive file\.?$/i;function wS(t){let n=t.match(bS)?.[1]?.trim();return n||null}function IS(t){return{role:"assistant",type:"info",historyKey:`claude-sensitive-file:${t}`,content:`Vibelet \u63D0\u793A\uFF1AClaude \u628A ${t} \u89C6\u4E3A\u654F\u611F\u8DEF\u5F84\u3002\u8FD9\u7C7B\u6279\u51C6\u65E0\u6CD5\u4ECE\u5DF2\u6709\u4F1A\u8BDD\u8BB0\u5F55\u91CC\u8865\u56DE\u5230 Vibelet\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u8FD9\u6B21\u4FEE\u6539\u5E76\u5728 Claude \u4E2D\u660E\u786E\u6279\u51C6\uFF1B\u5982\u679C\u5E0C\u671B\u5728 Vibelet \u91CC\u770B\u5230\u5BA1\u6279\u5F39\u7A97\uFF0C\u8BF7\u4ECE Vibelet \u542F\u52A8\u6216\u7EE7\u7EED\u8FD9\u4E2A\u4F1A\u8BDD\u3002`}}function AS(t){let e=SS(t?.message?.content);if(/\[Request interrupted by user(?: for tool use)?\]/i.test(e))return!0;let n=t?.toolUseResult;return!!(n&&typeof n=="object"&&n.interrupted===!0||typeof n=="string"&&/\[Request interrupted by user(?: for tool use)?\]/i.test(n))}function Md(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Ys(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,lastUsage:t.lastUsage,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:to()}}function Lt(t,e){let n=(0,F.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 TS(t,e){let n=await xd(t,e),s=kd(n,64),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(!r&&typeof d.cwd=="string"&&(r=d.cwd),!i&&typeof d.sessionId=="string"&&(i=d.sessionId),o||(o=st([d.customTitle,d.summary])),!l){let f=Zs(d),h=st([],f);h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await Ed(t,e);return{sessionId:i||Lt("claude",t)||(0,F.basename)(t,".jsonl"),cwd:r,title:o??l??st([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function CS(t,e){let n=await xd(t,e),s=kd(n,96),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(r||(r=d.payload?.cwd??d.cwd??""),i||(i=d.payload?.id??d.id??""),o||(o=st([d.payload?.title,d.title])),!l){let f=Pd(d),h=f&&!Md(f)?st([],f):void 0;h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await dS(t,e);return{sessionId:i||Lt("codex",t)||(0,F.basename)(t,".jsonl"),cwd:r,title:o??l??st([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function it(t,e){let n=await(0,O.stat)(t).catch(()=>null);if(!n)return null;try{let s=n.size;if(e==="claude"){let i=await TS(t,s);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,lastUsage:i.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let r=await CS(t,s);return r?{sessionId:r.sessionId,agent:e,cwd:r.cwd,title:r.title,approvalMode:r.approvalMode,lastUsage:r.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function wd(t,e){let n=(0,F.join)((0,ye.homedir)(),".claude","projects");try{let s;t?s=[Td(t)]:s=(await(0,O.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let r=[];for(let l of s){let u=(0,F.join)(n,l),c=await(0,O.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&r.push((0,F.join)(u,d))}let i=await at(r,ot,async l=>{let u=await(0,O.stat)(l).catch(()=>null);return{path:l,mtimeMs:u?.mtimeMs??0}});return i.sort((l,u)=>u.mtimeMs-l.mtimeMs),(await at(i,ot,async l=>{let u=await it(l.path,"claude");return u&&e&&e.push(Ys(u)),u})).filter(l=>l!==null).map(l=>Ys(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(s){return Te.warn({error:String(s)},"failed to list claude sessions"),[]}}async function Id(t,e){try{let n=await fo(),s=await at(n,ot,async i=>{let o=await it(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Ys(o)),o});return oS(s.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),s.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Ys(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Te.warn({error:String(n)},"failed to list codex sessions"),[]}}async function ed(t){if(!t)return null;let e=`codex-latest:${(0,ye.homedir)()}`,n=Qs.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Vs||(Vs=(async()=>{let i=await fo(),o=await at(i,ot,async l=>{let u=await it(l.path,"codex");return u?{cwd:u.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:u.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return Qs.set(e,a),a})().finally(()=>{Vs=null}));let r=(await Vs).get(t);return r?{sessionId:r.sessionId,filePath:r.path}:null}async function Mn(t,e,n){let r=`list:${(0,ye.homedir)()}:${t??"all"}:${e??""}`,i=io.get(r);if(i)return i;let o=no.get(r);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await wd(e,n);else if(t==="codex")l=await Id(e,n);else{let[u,c]=await Promise.all([wd(e,n),Id(e,n)]);l=[...u,...c].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return io.set(r,l),l})();return no.set(r,a),a.finally(()=>no.delete(r)),a}async function yd(t,e,n){let r=`search:${(0,ye.homedir)()}:${t}:${e??"all"}:${n??"all"}`,i=oo.get(r);if(i)return i;let o=so.get(r);if(o)return o;let a=(async()=>{let l=new Set,u=t.toLowerCase(),c=n??0;function d(g){if(c<=0)return g;let m=g.findIndex(p=>p.mtimeMs<c);return m===-1?g:g.slice(0,m)}async function f(){try{let g=await rS(),m=d(await Cd(g)),p=await at(m,ot,y=>Ad(y.path,u,"claude"));for(let y of p)y&&l.add(y)}catch(g){Te.warn({error:String(g)},"failed to search claude files")}}async function h(){try{let g=d(await fo()),m=await at(g,ot,p=>Ad(p.path,u,"codex"));for(let p of m)p&&l.add(p)}catch(g){Te.warn({error:String(g)},"failed to search codex files")}}return e==="claude"?await f():e==="codex"?await h():await Promise.all([f(),h()]),oo.set(r,l),l})();return so.set(r,a),a.finally(()=>so.delete(r)),a}async function Ad(t,e,n){let s=(0,ao.createReadStream)(t,{encoding:"utf-8"}),r=(0,lo.createInterface)({input:s,crlfDelay:1/0}),i=n==="claude"?kS:xS,o="",a=!1;try{for await(let l of r){if(!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof u.sessionId=="string"&&(o=u.sessionId):o=u.payload?.id??u.id??""),!a){let c=i(u);c&&c.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{r.close(),s.destroy()}return a?o||Lt(n,t):null}function kS(t){return t?.type==="user"&&t.message?.role==="user"?Zs(t):t?.type==="assistant"&&t.message?.role==="assistant"?Xs(t.message.content):""}function xS(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return po(t.payload.content)}let e=Pd(t);return e||""}async function Js(t,e){let n=(0,ao.createReadStream)(t,{encoding:"utf-8"}),s=(0,lo.createInterface)({input:n,crlfDelay:1/0});try{for await(let r of s){if(!r.trim())continue;let i;try{i=JSON.parse(r)}catch{continue}if(e(i))break}}finally{s.close(),n.destroy()}}async function ho(t,e){let n=(0,F.join)((0,ye.homedir)(),".claude","projects"),s=e?Td(e):null,r=await(0,O.readdir)(n).catch(()=>[]),i=s?[s,...r.filter(o=>o!==s)]:r;for(let o of i){let a=(0,F.join)(n,o,`${t}.jsonl`);if((await(0,O.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Ld(t,e){let n=await ho(t,e);if(!n)return;let s=await(0,O.stat)(n).catch(()=>null);return s?.isFile()?(await Ed(n,s.size)).lastUsage:void 0}async function go(t,e,n){if(e==="claude")return ho(t,n);let s=(0,F.join)((0,ye.homedir)(),".codex","sessions");return Od(s,t)}function RS(t){if(t?.type==="user"&&t.message?.role==="user")return vS(t.message.content)?{kind:"toolResult",...AS(t)?{interrupted:!0}:{}}:Zs(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Xs(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 ES(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 t.kind==="toolResult"&&t.interrupted?{}:{isResponding:!0}}async function Ji(t,e){if(e!=="claude")return{};let n=null;try{await Js(t,s=>{let r=RS(s);r&&(n=r)})}catch(s){return s.code!=="ENOENT"&&Te.warn({filePath:t,error:String(s)},"failed to read session runtime hints"),{}}return ES(n)}async function mo(t,e,n){let s=await go(t,e,n);return s?Ji(s,e):{}}function PS(t){if(typeof t?.timestamp!="string")return null;let e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}async function Nd(t,e,n,s){if(e!=="codex"||!s||s<=0)return[];let r=await go(t,e,n);if(!r)return[];let i=[];try{await Js(r,l=>{let u=PS(l);u!=null&&u<s||i.push(...Di(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Te.warn({filePath:r,error:String(l)},"failed to read generated file notices"),[]}let o=await _u(i,s),a=Ae(o);return a?[a]:[]}async function Ln(t,e,n){let s=[],r=(i,o)=>{let a=gS(i);if(o?.coalesceConsecutiveAssistant&&a.role==="assistant"){let l=s[s.length-1];if(l?.role==="assistant"&&l.type!=="info"&&a.type!=="info"&&!Su(l.content)){s[s.length-1]=a;return}}s.push(a)};if(e==="claude")try{let i=await ho(t,n);if(i){let o=new Map;await Js(i,a=>{if(a.type==="assistant"&&a.message?.role==="assistant"&&Array.isArray(a.message.content))for(let l of a.message.content){if(!l||typeof l!="object"||l.type!=="tool_use"||typeof l.id!="string")continue;let u=Rs(typeof l.name=="string"?l.name:null,l.input&&typeof l.input=="object"?l.input:null,n);u&&o.set(l.id,u)}if(a.type==="user"&&a.message?.role==="user"){if(Array.isArray(a.message.content))for(let u of a.message.content){if(!u||typeof u!="object"||u.type!=="tool_result")continue;if(u.is_error===!0){let g=bd(u.content),m=wS(g);m&&r(IS(m));continue}let c=typeof u.tool_use_id=="string"?u.tool_use_id:"",d=c?o.get(c):void 0;if(!d)continue;let f=bd(u.content);if(!Es(a.toolUseResult,f))continue;let h=Ae([d]);h&&r({role:"assistant",content:h})}let l=Zs(a);l&&r({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=Xs(a.message.content);l&&r({role:"assistant",content:l})}})}}catch(i){Te.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await go(t,e,n);i&&await Js(i,o=>{let a=Di(o,{cwd:n,includePatchCalls:!0}),l=Ae(a);if(l&&r({role:"assistant",content:l}),o.type!=="response_item"||o.payload?.type!=="message")return;let u=o.payload.role;if(u!=="user"&&u!=="assistant")return;let c=po(o.payload.content);c&&(u==="user"&&Md(c)||r({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Te.warn({error:String(i)},"failed to read codex session history")}return s}async function Od(t,e){try{let n=await(0,O.readdir)(t,{withFileTypes:!0});for(let s of n){let r=(0,F.join)(t,s.name);if(s.isDirectory()){let i=await Od(r,e);if(i)return i}else if(s.name.includes(e)&&s.name.endsWith(".jsonl"))return r}}catch(n){Te.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Dt=require("fs"),Hd=require("path");var MS=500,Dd=200;function Bd(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Dd?e:e.slice(-Dd)}function LS(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 NS(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 OS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof n!="string"||n.length===0||typeof s!="string"||s.length===0||n===s||(e[n]=s);return e}function DS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",s=typeof e.toolName=="string"?e.toolName:"",r=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!s||!r)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:s,input:i,description:r,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:s,input:i,description:r}}function BS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),n}function FS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.content!="string"||typeof e.enqueuedAt!="string"||!e.enqueuedAt)return;let n={content:e.content,enqueuedAt:e.enqueuedAt};if(typeof e.clientMessageId=="string"&&e.clientMessageId&&(n.clientMessageId=e.clientMessageId),typeof e.model=="string"&&e.model&&(n.model=e.model),Array.isArray(e.images)){let s=e.images.filter(r=>typeof r=="string"&&r.length>0);s.length>0&&(n.images=s)}return n}function HS(t){if(!Array.isArray(t))return;let e=[];for(let n of t){let s=FS(n);s&&e.push(s)}return e.length>0?e:void 0}function US(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={at:e.at,humanText:e.humanText};return typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.hardTimeoutMs=="number"&&Number.isFinite(e.hardTimeoutMs)&&(n.hardTimeoutMs=e.hardTimeoutMs),n}function WS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.inputTokens),s=Number(e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.contextWindowTokens),i=Number(e.cacheCreationInputTokens),o=Number(e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(i)&&i>=0?{cacheCreationInputTokens:i}:{},...Number.isFinite(o)&&o>=0?{cacheReadInputTokens:o}:{},...Number.isFinite(r)&&r>0?{contextWindowTokens:r}:{}}}function Fd(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Bd(t.acceptedClientMessageIds),interruptedClientMessageIds:Bd(t.interruptedClientMessageIds),pendingApproval:DS(t.pendingApproval),lastUsage:WS(t.lastUsage),interruptReason:BS(t.interruptReason),stallWarning:US(t.stallWarning),pendingQueue:HS(t.pendingQueue)}}var qS=new Set(["records","deletedSessionIds","sessionAliases","archivedSessionIds"]);function GS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))qS.has(n)||(e[n]=s);return e}function jS(t){if(Array.isArray(t))return{records:t.map(Fd),deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Fd):[],deletedSessionIds:LS(e.deletedSessionIds),sessionAliases:OS(e.sessionAliases),archivedSessionIds:NS(e.archivedSessionIds)}}return{records:[],deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]}}var er=class{records;deletedSessionIds;sessionAliases;archivedSessionIds;unknownFields={};debounceTimer=null;constructor(){let e=this.readRawFromDisk(),n=jS(e);this.records=n.records,this.deletedSessionIds=new Set(n.deletedSessionIds),this.sessionAliases=new Map(Object.entries(n.sessionAliases)),this.archivedSessionIds=new Set(n.archivedSessionIds),this.unknownFields=GS(e)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,s=new Set;for(;!s.has(n);){s.add(n);let r=this.sessionAliases.get(n);if(!r||r===n)break;n=r}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(s=>s.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}isArchived(e){let n=this.resolveSessionId(e);return this.archivedSessionIds.has(e)||this.archivedSessionIds.has(n)}getArchivedSessionIds(){return[...this.archivedSessionIds]}setArchived(e,n){let s=this.resolveSessionId(e),r=this.archivedSessionIds.has(e)||this.archivedSessionIds.has(s);return n&&!r?(this.archivedSessionIds.add(s),this.scheduleSave(),!0):!n&&r?(this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(s),this.scheduleSave(),!0):!1}replaceArchivedSessionIds(e){let n=new Set;for(let s of e)typeof s!="string"||s.length===0||n.add(this.resolveSessionId(s));return this.archivedSessionIds=n,this.scheduleSave(),[...this.archivedSessionIds]}mergeArchivedSessionIds(e){for(let n of e)typeof n!="string"||n.length===0||this.archivedSessionIds.add(this.resolveSessionId(n));return this.scheduleSave(),[...this.archivedSessionIds]}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(s=>s.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let s=this.resolveSessionId(n);if(!s||e===s){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,s),this.archivedSessionIds.delete(e)&&this.archivedSessionIds.add(s),this.scheduleSave()}forget(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.delete(e),this.scheduleSave()}remove(e){let n=this.resolveSessionId(e);this.records=this.records.filter(r=>r.sessionId!==e&&r.sessionId!==n);let s=[];for(let[r,i]of this.sessionAliases)(r===e||r===n||i===n)&&(this.sessionAliases.delete(r),s.push(r));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let r of s)this.deletedSessionIds.add(r);this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(n);for(let r of s)this.archivedSessionIds.delete(r);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()},MS)}readRawFromDisk(){try{let e=(0,Dt.readFileSync)(Ss,"utf-8");return JSON.parse(e)}catch{return null}}saveToDisk(){(0,Dt.mkdirSync)((0,Hd.dirname)(Ss),{recursive:!0}),(0,Dt.writeFileSync)(Ss,JSON.stringify({...this.unknownFields,records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases),archivedSessionIds:[...this.archivedSessionIds]},null,2))}};var Bt=require("path"),Ud=require("os");function tr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Bt.join)((0,Ud.homedir)(),t.slice(2)):t}function $S(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s&&(e=s[1]??e),e}function yo(t,e){let n=tr($S(t));if(!n||(0,Bt.isAbsolute)(n))return n;let s=tr(e??"");return s?(0,Bt.resolve)(s,n):n}var Wd={approvalRequestV1:"vibelet.approvalRequest.v1"};var Ft=require("fs"),qd=require("path");function zS(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")&&(typeof t.locale=="string"||typeof t.locale>"u"))}function VS(t){try{let e=(0,Ft.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(zS):[]}catch{return[]}}function Nn(t,e){(0,Ft.mkdirSync)((0,qd.dirname)(t),{recursive:!0}),(0,Ft.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
- `,"utf8")}var nr=class{constructor(e=Kc){this.pushSubscriptionsPath=e;this.records=VS(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}listRecipients(){return this.records.map(e=>({pushToken:e.pushToken,...e.locale?{locale:e.locale}:{}}))}count(){return this.records.length}register(e,n,s){let r=new Date().toISOString(),i=this.records.find(l=>l.deviceId===e),o=s??i?.locale,a={deviceId:e,pushToken:n,platform:"expo",createdAt:i?.createdAt??r,updatedAt:r,...i?.lastSentAt?{lastSentAt:i.lastSentAt}:{},...o?{locale:o}:{}};this.records=[a,...this.records.filter(l=>l.deviceId!==e&&l.pushToken!==n)],Nn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let s=this.records.filter(r=>!(r.deviceId===e&&r.pushToken===n));return s.length===this.records.length?!1:(this.records=s,Nn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(s=>s.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,Nn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),s=new Date().toISOString(),r=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=s,r=!0);r&&Nn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],Nn(this.pushSubscriptionsPath,this.records)}};var K=M.child({module:"push"}),QS="https://exp.host/--/api/v2/push/send",YS="https://exp.host/--/api/v2/push/getReceipts",JS=[0,1e3,3e3],On=new nr;function KS(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 XS(t){return new Promise(e=>{setTimeout(e,t)})}function Gd(t){return t==="DeviceNotRegistered"}function ZS(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],s=[];for(let[r,i]of t.data.entries()){let o=e[r];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}s.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:s}}function e_(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[s,r]of t.data.entries()){let i=e[s];!i||!r||r.status!=="ok"||typeof r.id!="string"||r.id.length===0||n.set(r.id,i)}return n}function t_(t,e){let n=[],s=[],r=t.data;for(let[i,o]of e.entries()){let a=r?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&s.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:s}}async function n_(t,e,n,s){let r=new Map(t);for(let i of JS){if(r.size===0)return;i>0&&await n(i);let o;try{o=await e(YS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...r.keys()]})})}catch(c){K.error({error:String(c),count:r.size},"push receipt request failed");return}if(!o.ok){K.error({status:o.status,statusText:o.statusText,count:r.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){K.error({count:r.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=t_(a,r);for(let{token:c,receipt:d}of u){let f=d.details?.error;if(K.error({token:c,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Gd(f)){let h=s.unregisterToken(c);K.info({token:c,errorCode:f,removed:h},"push token removed after receipt rejection")}}r=new Map(l.map(c=>[c,r.get(c)]))}r.size>0&&K.warn({pendingReceipts:r.size},"push receipts still pending after polling")}function s_(t){let e=t?.pushStore??On,n=t?.fetchImpl??globalThis.fetch,s=t?.sleepImpl??XS;return async function(i,o){let a=e.listRecipients();if(a.length===0)return;let l=typeof i=="function"?i:()=>i,u=a.map(d=>d.pushToken),c=a.map(({pushToken:d,locale:f})=>{let{title:h,body:g}=l(f);return{to:d,sound:"default",title:h,body:g,data:o,badge:1,priority:"high",_contentAvailable:!0,...KS(o)&&o.eventType==="approval_request"?{categoryId:Wd.approvalRequestV1}:{}}});try{let d=await n(QS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){K.error({status:d.status,statusText:d.statusText},"push send failed");return}let f=await d.json().catch(()=>null);if(!f){K.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:h,ticketErrors:g}=ZS(f,u),m=e_(f,u);for(let{token:p,ticket:y}of g){let C=y.details?.error;if(K.error({token:p,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),Gd(C)){let A=e.unregisterToken(p);K.info({token:p,errorCode:C,removed:A},"push token removed after ticket rejection")}}h.length>0&&(K.debug({count:h.length},"push sent"),e.markSent(h)),m.size>0&&await n_(m,n,s,e)}catch(d){K.error({error:String(d)},"push send error")}}}function vo(t,e,n){On.register(t,e,n),K.info({deviceId:t,token:e,locale:n,total:On.count()},"push token registered")}function So(t,e){let n=On.unregister(t,e);K.info({deviceId:t,token:e,total:On.count(),removed:n},"push token unregistered")}var sr=s_();var zd=require("child_process"),Ht=require("fs"),Bn=require("os"),_o=require("path"),Vd=require("util");var Fn=M.child({module:"usage-limits"}),r_=(0,Vd.promisify)(zd.execFile),i_=6e4,Qd=8e3,o_="https://api.anthropic.com/api/oauth/usage",a_="https://chatgpt.com/backend-api/codex/usage",l_="https://chatgpt.com/backend-api/codex/responses",c_="claude-cli/2.1 (vibelet-daemon)",u_="codex_cli_rs/0.20.0 (vibelet-daemon)",rr=new Map,Dn=null;function d_(){let t=(process.env.VIBE_USAGE_LIMITS??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="disabled"}async function Yd(t,e={}){if(d_())return{limits:null,reason:"disabled"};let n=Date.now(),s=rr.get(t);if(!e.force&&s&&n-s.at<i_)return s.payload;if(s?.inflight)return s.inflight;let r=(t==="claude"?p_():y_()).then(i=>(rr.set(t,{at:Date.now(),payload:i}),i)).catch(i=>{let o=i instanceof Error?i.message:String(i);Fn.warn({agent:t,error:o},"usage-limits fetch failed");let a={limits:null,reason:"unknown",detail:o};return rr.set(t,{at:Date.now(),payload:a}),a});return rr.set(t,{at:s?.at??0,payload:s?.payload??{limits:null},inflight:r}),r}async function f_(){if((0,Bn.platform)()==="darwin")try{let{stdout:e}=await r_("security",["find-generic-password","-s","Claude Code-credentials","-w"],{timeout:5e3}),n=e.trim();if(!n)return null;let s=JSON.parse(n);return s.claudeAiOauth??s.oauth??s}catch(e){return Fn.debug({error:e instanceof Error?e.message:String(e)},"keychain read failed"),null}let t=(0,_o.join)((0,Bn.homedir)(),".claude",".credentials.json");if(!(0,Ht.existsSync)(t))return null;try{let e=(0,Ht.readFileSync)(t,"utf8"),n=JSON.parse(e);return n.claudeAiOauth??n.oauth??n}catch{return null}}function ir(t){if(!t)return;let e=Number(t.utilization);if(Number.isFinite(e))return t.resets_at?{usedPercent:e,resetsAt:t.resets_at}:{usedPercent:e,resetsAt:""}}async function p_(){let t=await f_(),e=t?.accessToken??t?.access_token;if(!e)return{limits:null,reason:"no_credentials"};let n=new AbortController,s=setTimeout(()=>n.abort(),Qd),r;try{r=await fetch(o_,{method:"GET",headers:{Authorization:`Bearer ${e}`,"anthropic-beta":"oauth-2025-04-20","User-Agent":c_,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(s)}if(!r.ok){let a=await r.text().catch(()=>"");return Fn.warn({agent:"claude",status:r.status,statusText:r.statusText,bodyPreview:a.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${r.status} ${r.statusText} ${a.slice(0,200)}`}}let i;try{i=await r.json()}catch(a){return{limits:null,reason:"parse_error",detail:a instanceof Error?a.message:String(a)}}return{limits:{agent:"claude",fiveHour:ir(i.five_hour),weekly:ir(i.seven_day),weeklyOpus:ir(i.seven_day_opus),weeklySonnet:ir(i.seven_day_sonnet),planType:t?.subscriptionType??t?.rateLimitTier,fetchedAt:Date.now()}}}function h_(){let t=(0,_o.join)((0,Bn.homedir)(),".codex","auth.json");if(!(0,Ht.existsSync)(t))return null;try{return JSON.parse((0,Ht.readFileSync)(t,"utf8"))}catch{return null}}function or(t){if(!t)return;let e=Number(t.used_percent);if(!Number.isFinite(e))return;let n="";return typeof t.reset_at=="number"&&Number.isFinite(t.reset_at)?n=new Date(t.reset_at*1e3).toISOString():typeof t.reset_after_seconds=="number"&&Number.isFinite(t.reset_after_seconds)&&(n=new Date(Date.now()+t.reset_after_seconds*1e3).toISOString()),{usedPercent:e,resetsAt:n}}function g_(t){let e=t.getSetCookie,s=(typeof e=="function"?e.call(t):t.get("set-cookie")?[t.get("set-cookie")]:[]).flatMap(r=>r.split(/,(?=\s*[^;,]+=)/g)).map(r=>r.split(";")[0]?.trim()??"").filter(Boolean);return s.length>0?s.join("; "):null}function m_(t){return Dn?{...t,Cookie:Dn}:t}async function jd(t,e){try{let n=await fetch(l_,{method:"HEAD",headers:t,signal:e}),s=g_(n.headers);s&&(Dn=s)}catch(n){if(e.aborted)throw n;Fn.debug({error:n instanceof Error?n.message:String(n)},"usage-limits codex cookie warmup failed")}}async function $d(t,e){return fetch(a_,{method:"GET",headers:m_(t),signal:e})}async function y_(){let t=h_();if(!t)return{limits:null,reason:"no_credentials"};if(t.auth_mode!=="chatgpt")return{limits:null,reason:"unsupported_auth"};let e=t.tokens?.access_token,n=t.tokens?.account_id;if(!e)return{limits:null,reason:"no_credentials"};let s=new AbortController,r=setTimeout(()=>s.abort(),Qd),i,o={Authorization:`Bearer ${e}`,"User-Agent":u_,Accept:"application/json","OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};n&&(o["chatgpt-account-id"]=n);try{Dn||await jd(o,s.signal),i=await $d(o,s.signal),i.status===403&&(i.headers.get("content-type")??"").includes("text/html")&&(await i.text().catch(()=>""),Dn=null,await jd(o,s.signal),i=await $d(o,s.signal))}finally{clearTimeout(r)}if(!i.ok){let c=await i.text().catch(()=>"");return Fn.warn({agent:"codex",status:i.status,statusText:i.statusText,bodyPreview:c.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${i.status} ${i.statusText} ${c.slice(0,200)}`}}let a;try{a=await i.json()}catch(c){return{limits:null,reason:"parse_error",detail:c instanceof Error?c.message:String(c)}}let l=(a.additional_rate_limits??[]).map(c=>({name:c.limit_name??"",primary:or(c.rate_limit?.primary_window),secondary:or(c.rate_limit?.secondary_window)})).filter(c=>c.name&&(c.primary||c.secondary));return{limits:{agent:"codex",fiveHour:or(a.rate_limit?.primary_window),weekly:or(a.rate_limit?.secondary_window),additional:l.length?l:void 0,planType:a.plan_type,fetchedAt:Date.now()}}}var b=M.child({module:"manager"}),v_="Done.",S_="Approval required",Jd=180,Wt=200,__=6e4,Kd=9e4,b_=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]);function cf(t,e){let n=e?.length?e.map(s=>{let r=s.lastIndexOf("."),i=r>=0?s.slice(r).toLowerCase():"";return`[Attached ${b_.has(i)?"image":"file"}: ${s}]`}).join(`
105
+ `):""}function wS(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(`
106
+ `):""}function wd(t){if(typeof t=="string")return t;let e=wS(t);return e||(Array.isArray(t)&&t.length>0&&t.every(s=>s&&typeof s=="object"&&s.type==="tool_reference")?"":JSON.stringify(t))}var IS=/Claude requested permissions to (?:edit|write to) (.+?) which is a sensitive file\.?$/i;function AS(t){let n=t.match(IS)?.[1]?.trim();return n||null}function TS(t){return{role:"assistant",type:"info",historyKey:`claude-sensitive-file:${t}`,content:`Vibelet \u63D0\u793A\uFF1AClaude \u628A ${t} \u89C6\u4E3A\u654F\u611F\u8DEF\u5F84\u3002\u8FD9\u7C7B\u6279\u51C6\u65E0\u6CD5\u4ECE\u5DF2\u6709\u4F1A\u8BDD\u8BB0\u5F55\u91CC\u8865\u56DE\u5230 Vibelet\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u8FD9\u6B21\u4FEE\u6539\u5E76\u5728 Claude \u4E2D\u660E\u786E\u6279\u51C6\uFF1B\u5982\u679C\u5E0C\u671B\u5728 Vibelet \u91CC\u770B\u5230\u5BA1\u6279\u5F39\u7A97\uFF0C\u8BF7\u4ECE Vibelet \u542F\u52A8\u6216\u7EE7\u7EED\u8FD9\u4E2A\u4F1A\u8BDD\u3002`}}function CS(t){let e=bS(t?.message?.content);if(/\[Request interrupted by user(?: for tool use)?\]/i.test(e))return!0;let n=t?.toolUseResult;return!!(n&&typeof n=="object"&&n.interrupted===!0||typeof n=="string"&&/\[Request interrupted by user(?: for tool use)?\]/i.test(n))}function Ld(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Ys(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,lastUsage:t.lastUsage,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:to()}}function Lt(t,e){let n=(0,H.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 kS(t,e){let n=await Rd(t,e),s=xd(n,64),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(!r&&typeof d.cwd=="string"&&(r=d.cwd),!i&&typeof d.sessionId=="string"&&(i=d.sessionId),o||(o=st([d.customTitle,d.summary])),!l){let f=Zs(d),h=st([],f);h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await Pd(t,e);return{sessionId:i||Lt("claude",t)||(0,H.basename)(t,".jsonl"),cwd:r,title:o??l??st([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function xS(t,e){let n=await Rd(t,e),s=xd(n,96),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(r||(r=d.payload?.cwd??d.cwd??""),i||(i=d.payload?.id??d.id??""),o||(o=st([d.payload?.title,d.title])),!l){let f=Md(d),h=f&&!Ld(f)?st([],f):void 0;h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await pS(t,e);return{sessionId:i||Lt("codex",t)||(0,H.basename)(t,".jsonl"),cwd:r,title:o??l??st([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function it(t,e){let n=await(0,O.stat)(t).catch(()=>null);if(!n)return null;try{let s=n.size;if(e==="claude"){let i=await kS(t,s);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,lastUsage:i.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let r=await xS(t,s);return r?{sessionId:r.sessionId,agent:e,cwd:r.cwd,title:r.title,approvalMode:r.approvalMode,lastUsage:r.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Id(t,e){let n=(0,H.join)((0,ye.homedir)(),".claude","projects");try{let s;t?s=[Cd(t)]:s=(await(0,O.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let r=[];for(let l of s){let u=(0,H.join)(n,l),c=await(0,O.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&r.push((0,H.join)(u,d))}let i=await at(r,ot,async l=>{let u=await(0,O.stat)(l).catch(()=>null);return{path:l,mtimeMs:u?.mtimeMs??0}});return i.sort((l,u)=>u.mtimeMs-l.mtimeMs),(await at(i,ot,async l=>{let u=await it(l.path,"claude");return u&&e&&e.push(Ys(u)),u})).filter(l=>l!==null).map(l=>Ys(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(s){return Te.warn({error:String(s)},"failed to list claude sessions"),[]}}async function Ad(t,e){try{let n=await fo(),s=await at(n,ot,async i=>{let o=await it(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Ys(o)),o});return lS(s.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),s.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Ys(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Te.warn({error:String(n)},"failed to list codex sessions"),[]}}async function td(t){if(!t)return null;let e=`codex-latest:${(0,ye.homedir)()}`,n=Qs.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Vs||(Vs=(async()=>{let i=await fo(),o=await at(i,ot,async l=>{let u=await it(l.path,"codex");return u?{cwd:u.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:u.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return Qs.set(e,a),a})().finally(()=>{Vs=null}));let r=(await Vs).get(t);return r?{sessionId:r.sessionId,filePath:r.path}:null}async function Mn(t,e,n){let r=`list:${(0,ye.homedir)()}:${t??"all"}:${e??""}`,i=io.get(r);if(i)return i;let o=no.get(r);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Id(e,n);else if(t==="codex")l=await Ad(e,n);else{let[u,c]=await Promise.all([Id(e,n),Ad(e,n)]);l=[...u,...c].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return io.set(r,l),l})();return no.set(r,a),a.finally(()=>no.delete(r)),a}async function vd(t,e,n){let r=`search:${(0,ye.homedir)()}:${t}:${e??"all"}:${n??"all"}`,i=oo.get(r);if(i)return i;let o=so.get(r);if(o)return o;let a=(async()=>{let l=new Set,u=t.toLowerCase(),c=n??0;function d(g){if(c<=0)return g;let m=g.findIndex(p=>p.mtimeMs<c);return m===-1?g:g.slice(0,m)}async function f(){try{let g=await oS(),m=d(await kd(g)),p=await at(m,ot,y=>Td(y.path,u,"claude"));for(let y of p)y&&l.add(y)}catch(g){Te.warn({error:String(g)},"failed to search claude files")}}async function h(){try{let g=d(await fo()),m=await at(g,ot,p=>Td(p.path,u,"codex"));for(let p of m)p&&l.add(p)}catch(g){Te.warn({error:String(g)},"failed to search codex files")}}return e==="claude"?await f():e==="codex"?await h():await Promise.all([f(),h()]),oo.set(r,l),l})();return so.set(r,a),a.finally(()=>so.delete(r)),a}async function Td(t,e,n){let s=(0,ao.createReadStream)(t,{encoding:"utf-8"}),r=(0,lo.createInterface)({input:s,crlfDelay:1/0}),i=n==="claude"?RS:ES,o="",a=!1;try{for await(let l of r){if(!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof u.sessionId=="string"&&(o=u.sessionId):o=u.payload?.id??u.id??""),!a){let c=i(u);c&&c.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{r.close(),s.destroy()}return a?o||Lt(n,t):null}function RS(t){return t?.type==="user"&&t.message?.role==="user"?Zs(t):t?.type==="assistant"&&t.message?.role==="assistant"?Xs(t.message.content):""}function ES(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return po(t.payload.content)}let e=Md(t);return e||""}async function Js(t,e){let n=(0,ao.createReadStream)(t,{encoding:"utf-8"}),s=(0,lo.createInterface)({input:n,crlfDelay:1/0});try{for await(let r of s){if(!r.trim())continue;let i;try{i=JSON.parse(r)}catch{continue}if(e(i))break}}finally{s.close(),n.destroy()}}async function ho(t,e){let n=(0,H.join)((0,ye.homedir)(),".claude","projects"),s=e?Cd(e):null,r=await(0,O.readdir)(n).catch(()=>[]),i=s?[s,...r.filter(o=>o!==s)]:r;for(let o of i){let a=(0,H.join)(n,o,`${t}.jsonl`);if((await(0,O.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Nd(t,e){let n=await ho(t,e);if(!n)return;let s=await(0,O.stat)(n).catch(()=>null);return s?.isFile()?(await Pd(n,s.size)).lastUsage:void 0}async function go(t,e,n){if(e==="claude")return ho(t,n);let s=(0,H.join)((0,ye.homedir)(),".codex","sessions");return Dd(s,t)}function PS(t){if(t?.type==="user"&&t.message?.role==="user")return _S(t.message.content)?{kind:"toolResult",...CS(t)?{interrupted:!0}:{}}:Zs(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Xs(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 MS(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 t.kind==="toolResult"&&t.interrupted?{}:{isResponding:!0}}async function Ji(t,e){if(e!=="claude")return{};let n=null;try{await Js(t,s=>{let r=PS(s);r&&(n=r)})}catch(s){return s.code!=="ENOENT"&&Te.warn({filePath:t,error:String(s)},"failed to read session runtime hints"),{}}return MS(n)}async function mo(t,e,n){let s=await go(t,e,n);return s?Ji(s,e):{}}function LS(t){if(typeof t?.timestamp!="string")return null;let e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}async function Od(t,e,n,s){if(e!=="codex"||!s||s<=0)return[];let r=await go(t,e,n);if(!r)return[];let i=[];try{await Js(r,l=>{let u=LS(l);u!=null&&u<s||i.push(...Di(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Te.warn({filePath:r,error:String(l)},"failed to read generated file notices"),[]}let o=await bu(i,s),a=Ae(o);return a?[a]:[]}async function Ln(t,e,n){let s=[],r=(i,o)=>{let a=yS(i);if(o?.coalesceConsecutiveAssistant&&a.role==="assistant"){let l=s[s.length-1];if(l?.role==="assistant"&&l.type!=="info"&&a.type!=="info"&&!_u(l.content)){s[s.length-1]=a;return}}s.push(a)};if(e==="claude")try{let i=await ho(t,n);if(i){let o=new Map;await Js(i,a=>{if(a.type==="assistant"&&a.message?.role==="assistant"&&Array.isArray(a.message.content))for(let l of a.message.content){if(!l||typeof l!="object"||l.type!=="tool_use"||typeof l.id!="string")continue;let u=Rs(typeof l.name=="string"?l.name:null,l.input&&typeof l.input=="object"?l.input:null,n);u&&o.set(l.id,u)}if(a.type==="user"&&a.message?.role==="user"){if(Array.isArray(a.message.content))for(let u of a.message.content){if(!u||typeof u!="object"||u.type!=="tool_result")continue;if(u.is_error===!0){let g=wd(u.content),m=AS(g);m&&r(TS(m));continue}let c=typeof u.tool_use_id=="string"?u.tool_use_id:"",d=c?o.get(c):void 0;if(!d)continue;let f=wd(u.content);if(!Es(a.toolUseResult,f))continue;let h=Ae([d]);h&&r({role:"assistant",content:h})}let l=Zs(a);l&&r({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=Xs(a.message.content);l&&r({role:"assistant",content:l})}})}}catch(i){Te.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await go(t,e,n);i&&await Js(i,o=>{let a=Di(o,{cwd:n,includePatchCalls:!0}),l=Ae(a);if(l&&r({role:"assistant",content:l}),o.type!=="response_item"||o.payload?.type!=="message")return;let u=o.payload.role;if(u!=="user"&&u!=="assistant")return;let c=po(o.payload.content);c&&(u==="user"&&Ld(c)||r({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Te.warn({error:String(i)},"failed to read codex session history")}return s}async function Dd(t,e){try{let n=await(0,O.readdir)(t,{withFileTypes:!0});for(let s of n){let r=(0,H.join)(t,s.name);if(s.isDirectory()){let i=await Dd(r,e);if(i)return i}else if(s.name.includes(e)&&s.name.endsWith(".jsonl"))return r}}catch(n){Te.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Dt=require("fs"),Ud=require("path");var NS=500,Bd=200;function Fd(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Bd?e:e.slice(-Bd)}function OS(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 DS(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 BS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof n!="string"||n.length===0||typeof s!="string"||s.length===0||n===s||(e[n]=s);return e}function FS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",s=typeof e.toolName=="string"?e.toolName:"",r=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!s||!r)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:s,input:i,description:r,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:s,input:i,description:r}}function HS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),n}function US(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.content!="string"||typeof e.enqueuedAt!="string"||!e.enqueuedAt)return;let n={content:e.content,enqueuedAt:e.enqueuedAt};if(typeof e.clientMessageId=="string"&&e.clientMessageId&&(n.clientMessageId=e.clientMessageId),typeof e.model=="string"&&e.model&&(n.model=e.model),Array.isArray(e.images)){let s=e.images.filter(r=>typeof r=="string"&&r.length>0);s.length>0&&(n.images=s)}return n}function WS(t){if(!Array.isArray(t))return;let e=[];for(let n of t){let s=US(n);s&&e.push(s)}return e.length>0?e:void 0}function qS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={at:e.at,humanText:e.humanText};return typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.hardTimeoutMs=="number"&&Number.isFinite(e.hardTimeoutMs)&&(n.hardTimeoutMs=e.hardTimeoutMs),n}function GS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.inputTokens),s=Number(e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.contextWindowTokens),i=Number(e.cacheCreationInputTokens),o=Number(e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(i)&&i>=0?{cacheCreationInputTokens:i}:{},...Number.isFinite(o)&&o>=0?{cacheReadInputTokens:o}:{},...Number.isFinite(r)&&r>0?{contextWindowTokens:r}:{}}}function Hd(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Fd(t.acceptedClientMessageIds),interruptedClientMessageIds:Fd(t.interruptedClientMessageIds),pendingApproval:FS(t.pendingApproval),lastUsage:GS(t.lastUsage),interruptReason:HS(t.interruptReason),stallWarning:qS(t.stallWarning),pendingQueue:WS(t.pendingQueue)}}var jS=new Set(["records","deletedSessionIds","sessionAliases","archivedSessionIds"]);function $S(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))jS.has(n)||(e[n]=s);return e}function zS(t){if(Array.isArray(t))return{records:t.map(Hd),deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Hd):[],deletedSessionIds:OS(e.deletedSessionIds),sessionAliases:BS(e.sessionAliases),archivedSessionIds:DS(e.archivedSessionIds)}}return{records:[],deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]}}var er=class{records;deletedSessionIds;sessionAliases;archivedSessionIds;unknownFields={};debounceTimer=null;constructor(){let e=this.readRawFromDisk(),n=zS(e);this.records=n.records,this.deletedSessionIds=new Set(n.deletedSessionIds),this.sessionAliases=new Map(Object.entries(n.sessionAliases)),this.archivedSessionIds=new Set(n.archivedSessionIds),this.unknownFields=$S(e)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,s=new Set;for(;!s.has(n);){s.add(n);let r=this.sessionAliases.get(n);if(!r||r===n)break;n=r}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(s=>s.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}isArchived(e){let n=this.resolveSessionId(e);return this.archivedSessionIds.has(e)||this.archivedSessionIds.has(n)}getArchivedSessionIds(){return[...this.archivedSessionIds]}setArchived(e,n){let s=this.resolveSessionId(e),r=this.archivedSessionIds.has(e)||this.archivedSessionIds.has(s);return n&&!r?(this.archivedSessionIds.add(s),this.scheduleSave(),!0):!n&&r?(this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(s),this.scheduleSave(),!0):!1}replaceArchivedSessionIds(e){let n=new Set;for(let s of e)typeof s!="string"||s.length===0||n.add(this.resolveSessionId(s));return this.archivedSessionIds=n,this.scheduleSave(),[...this.archivedSessionIds]}mergeArchivedSessionIds(e){for(let n of e)typeof n!="string"||n.length===0||this.archivedSessionIds.add(this.resolveSessionId(n));return this.scheduleSave(),[...this.archivedSessionIds]}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(s=>s.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let s=this.resolveSessionId(n);if(!s||e===s){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,s),this.archivedSessionIds.delete(e)&&this.archivedSessionIds.add(s),this.scheduleSave()}forget(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.delete(e),this.scheduleSave()}remove(e){let n=this.resolveSessionId(e);this.records=this.records.filter(r=>r.sessionId!==e&&r.sessionId!==n);let s=[];for(let[r,i]of this.sessionAliases)(r===e||r===n||i===n)&&(this.sessionAliases.delete(r),s.push(r));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let r of s)this.deletedSessionIds.add(r);this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(n);for(let r of s)this.archivedSessionIds.delete(r);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()},NS)}readRawFromDisk(){try{let e=(0,Dt.readFileSync)(Ss,"utf-8");return JSON.parse(e)}catch{return null}}saveToDisk(){(0,Dt.mkdirSync)((0,Ud.dirname)(Ss),{recursive:!0}),(0,Dt.writeFileSync)(Ss,JSON.stringify({...this.unknownFields,records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases),archivedSessionIds:[...this.archivedSessionIds]},null,2))}};var Bt=require("path"),tr=require("os");function yo(t){return t=t.replace(/^~/,"~"),t==="~"?(0,tr.homedir)():t.startsWith("~/")||t.startsWith("~\\")?(0,Bt.join)((0,tr.homedir)(),t.slice(2)):t}function Wd(t){let e=(t??"").trim();return e?yo(e):(0,tr.homedir)()}function VS(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s&&(e=s[1]??e),e}function vo(t,e){let n=yo(VS(t));if(!n||(0,Bt.isAbsolute)(n))return n;let s=yo(e??"");return s?(0,Bt.resolve)(s,n):n}var qd={approvalRequestV1:"vibelet.approvalRequest.v1"};var Ft=require("fs"),Gd=require("path");function QS(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")&&(typeof t.locale=="string"||typeof t.locale>"u"))}function YS(t){try{let e=(0,Ft.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(QS):[]}catch{return[]}}function Nn(t,e){(0,Ft.mkdirSync)((0,Gd.dirname)(t),{recursive:!0}),(0,Ft.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
+ `,"utf8")}var nr=class{constructor(e=Xc){this.pushSubscriptionsPath=e;this.records=YS(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}listRecipients(){return this.records.map(e=>({pushToken:e.pushToken,...e.locale?{locale:e.locale}:{}}))}count(){return this.records.length}register(e,n,s){let r=new Date().toISOString(),i=this.records.find(l=>l.deviceId===e),o=s??i?.locale,a={deviceId:e,pushToken:n,platform:"expo",createdAt:i?.createdAt??r,updatedAt:r,...i?.lastSentAt?{lastSentAt:i.lastSentAt}:{},...o?{locale:o}:{}};this.records=[a,...this.records.filter(l=>l.deviceId!==e&&l.pushToken!==n)],Nn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let s=this.records.filter(r=>!(r.deviceId===e&&r.pushToken===n));return s.length===this.records.length?!1:(this.records=s,Nn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(s=>s.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,Nn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),s=new Date().toISOString(),r=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=s,r=!0);r&&Nn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],Nn(this.pushSubscriptionsPath,this.records)}};var K=L.child({module:"push"}),JS="https://exp.host/--/api/v2/push/send",KS="https://exp.host/--/api/v2/push/getReceipts",XS=[0,1e3,3e3],On=new nr;function ZS(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 e_(t){return new Promise(e=>{setTimeout(e,t)})}function jd(t){return t==="DeviceNotRegistered"}function t_(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],s=[];for(let[r,i]of t.data.entries()){let o=e[r];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}s.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:s}}function n_(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[s,r]of t.data.entries()){let i=e[s];!i||!r||r.status!=="ok"||typeof r.id!="string"||r.id.length===0||n.set(r.id,i)}return n}function s_(t,e){let n=[],s=[],r=t.data;for(let[i,o]of e.entries()){let a=r?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&s.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:s}}async function r_(t,e,n,s){let r=new Map(t);for(let i of XS){if(r.size===0)return;i>0&&await n(i);let o;try{o=await e(KS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...r.keys()]})})}catch(c){K.error({error:String(c),count:r.size},"push receipt request failed");return}if(!o.ok){K.error({status:o.status,statusText:o.statusText,count:r.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){K.error({count:r.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=s_(a,r);for(let{token:c,receipt:d}of u){let f=d.details?.error;if(K.error({token:c,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),jd(f)){let h=s.unregisterToken(c);K.info({token:c,errorCode:f,removed:h},"push token removed after receipt rejection")}}r=new Map(l.map(c=>[c,r.get(c)]))}r.size>0&&K.warn({pendingReceipts:r.size},"push receipts still pending after polling")}function i_(t){let e=t?.pushStore??On,n=t?.fetchImpl??globalThis.fetch,s=t?.sleepImpl??e_;return async function(i,o){let a=e.listRecipients();if(a.length===0)return;let l=typeof i=="function"?i:()=>i,u=a.map(d=>d.pushToken),c=a.map(({pushToken:d,locale:f})=>{let{title:h,body:g}=l(f);return{to:d,sound:"default",title:h,body:g,data:o,badge:1,priority:"high",_contentAvailable:!0,...ZS(o)&&o.eventType==="approval_request"?{categoryId:qd.approvalRequestV1}:{}}});try{let d=await n(JS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){K.error({status:d.status,statusText:d.statusText},"push send failed");return}let f=await d.json().catch(()=>null);if(!f){K.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:h,ticketErrors:g}=t_(f,u),m=n_(f,u);for(let{token:p,ticket:y}of g){let C=y.details?.error;if(K.error({token:p,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),jd(C)){let A=e.unregisterToken(p);K.info({token:p,errorCode:C,removed:A},"push token removed after ticket rejection")}}h.length>0&&(K.debug({count:h.length},"push sent"),e.markSent(h)),m.size>0&&await r_(m,n,s,e)}catch(d){K.error({error:String(d)},"push send error")}}}function So(t,e,n){On.register(t,e,n),K.info({deviceId:t,token:e,locale:n,total:On.count()},"push token registered")}function _o(t,e){let n=On.unregister(t,e);K.info({deviceId:t,token:e,total:On.count(),removed:n},"push token unregistered")}var sr=i_();var Vd=require("child_process"),Ht=require("fs"),Bn=require("os"),bo=require("path"),Qd=require("util");var Fn=L.child({module:"usage-limits"}),o_=(0,Qd.promisify)(Vd.execFile),a_=6e4,Yd=8e3,l_="https://api.anthropic.com/api/oauth/usage",c_="https://chatgpt.com/backend-api/codex/usage",u_="https://chatgpt.com/backend-api/codex/responses",d_="claude-cli/2.1 (vibelet-daemon)",f_="codex_cli_rs/0.20.0 (vibelet-daemon)",rr=new Map,Dn=null;function p_(){let t=(process.env.VIBE_USAGE_LIMITS??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="disabled"}async function Jd(t,e={}){if(p_())return{limits:null,reason:"disabled"};let n=Date.now(),s=rr.get(t);if(!e.force&&s&&n-s.at<a_)return s.payload;if(s?.inflight)return s.inflight;let r=(t==="claude"?g_():S_()).then(i=>(rr.set(t,{at:Date.now(),payload:i}),i)).catch(i=>{let o=i instanceof Error?i.message:String(i);Fn.warn({agent:t,error:o},"usage-limits fetch failed");let a={limits:null,reason:"unknown",detail:o};return rr.set(t,{at:Date.now(),payload:a}),a});return rr.set(t,{at:s?.at??0,payload:s?.payload??{limits:null},inflight:r}),r}async function h_(){if((0,Bn.platform)()==="darwin")try{let{stdout:e}=await o_("security",["find-generic-password","-s","Claude Code-credentials","-w"],{timeout:5e3}),n=e.trim();if(!n)return null;let s=JSON.parse(n);return s.claudeAiOauth??s.oauth??s}catch(e){return Fn.debug({error:e instanceof Error?e.message:String(e)},"keychain read failed"),null}let t=(0,bo.join)((0,Bn.homedir)(),".claude",".credentials.json");if(!(0,Ht.existsSync)(t))return null;try{let e=(0,Ht.readFileSync)(t,"utf8"),n=JSON.parse(e);return n.claudeAiOauth??n.oauth??n}catch{return null}}function ir(t){if(!t)return;let e=Number(t.utilization);if(Number.isFinite(e))return t.resets_at?{usedPercent:e,resetsAt:t.resets_at}:{usedPercent:e,resetsAt:""}}async function g_(){let t=await h_(),e=t?.accessToken??t?.access_token;if(!e)return{limits:null,reason:"no_credentials"};let n=new AbortController,s=setTimeout(()=>n.abort(),Yd),r;try{r=await fetch(l_,{method:"GET",headers:{Authorization:`Bearer ${e}`,"anthropic-beta":"oauth-2025-04-20","User-Agent":d_,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(s)}if(!r.ok){let a=await r.text().catch(()=>"");return Fn.warn({agent:"claude",status:r.status,statusText:r.statusText,bodyPreview:a.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${r.status} ${r.statusText} ${a.slice(0,200)}`}}let i;try{i=await r.json()}catch(a){return{limits:null,reason:"parse_error",detail:a instanceof Error?a.message:String(a)}}return{limits:{agent:"claude",fiveHour:ir(i.five_hour),weekly:ir(i.seven_day),weeklyOpus:ir(i.seven_day_opus),weeklySonnet:ir(i.seven_day_sonnet),planType:t?.subscriptionType??t?.rateLimitTier,fetchedAt:Date.now()}}}function m_(){let t=(0,bo.join)((0,Bn.homedir)(),".codex","auth.json");if(!(0,Ht.existsSync)(t))return null;try{return JSON.parse((0,Ht.readFileSync)(t,"utf8"))}catch{return null}}function or(t){if(!t)return;let e=Number(t.used_percent);if(!Number.isFinite(e))return;let n="";return typeof t.reset_at=="number"&&Number.isFinite(t.reset_at)?n=new Date(t.reset_at*1e3).toISOString():typeof t.reset_after_seconds=="number"&&Number.isFinite(t.reset_after_seconds)&&(n=new Date(Date.now()+t.reset_after_seconds*1e3).toISOString()),{usedPercent:e,resetsAt:n}}function y_(t){let e=t.getSetCookie,s=(typeof e=="function"?e.call(t):t.get("set-cookie")?[t.get("set-cookie")]:[]).flatMap(r=>r.split(/,(?=\s*[^;,]+=)/g)).map(r=>r.split(";")[0]?.trim()??"").filter(Boolean);return s.length>0?s.join("; "):null}function v_(t){return Dn?{...t,Cookie:Dn}:t}async function $d(t,e){try{let n=await fetch(u_,{method:"HEAD",headers:t,signal:e}),s=y_(n.headers);s&&(Dn=s)}catch(n){if(e.aborted)throw n;Fn.debug({error:n instanceof Error?n.message:String(n)},"usage-limits codex cookie warmup failed")}}async function zd(t,e){return fetch(c_,{method:"GET",headers:v_(t),signal:e})}async function S_(){let t=m_();if(!t)return{limits:null,reason:"no_credentials"};if(t.auth_mode!=="chatgpt")return{limits:null,reason:"unsupported_auth"};let e=t.tokens?.access_token,n=t.tokens?.account_id;if(!e)return{limits:null,reason:"no_credentials"};let s=new AbortController,r=setTimeout(()=>s.abort(),Yd),i,o={Authorization:`Bearer ${e}`,"User-Agent":f_,Accept:"application/json","OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};n&&(o["chatgpt-account-id"]=n);try{Dn||await $d(o,s.signal),i=await zd(o,s.signal),i.status===403&&(i.headers.get("content-type")??"").includes("text/html")&&(await i.text().catch(()=>""),Dn=null,await $d(o,s.signal),i=await zd(o,s.signal))}finally{clearTimeout(r)}if(!i.ok){let c=await i.text().catch(()=>"");return Fn.warn({agent:"codex",status:i.status,statusText:i.statusText,bodyPreview:c.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${i.status} ${i.statusText} ${c.slice(0,200)}`}}let a;try{a=await i.json()}catch(c){return{limits:null,reason:"parse_error",detail:c instanceof Error?c.message:String(c)}}let l=(a.additional_rate_limits??[]).map(c=>({name:c.limit_name??"",primary:or(c.rate_limit?.primary_window),secondary:or(c.rate_limit?.secondary_window)})).filter(c=>c.name&&(c.primary||c.secondary));return{limits:{agent:"codex",fiveHour:or(a.rate_limit?.primary_window),weekly:or(a.rate_limit?.secondary_window),additional:l.length?l:void 0,planType:a.plan_type,fetchedAt:Date.now()}}}var w=L.child({module:"manager"}),__="Done.",b_="Approval required",Kd=180,Wt=200,w_=6e4,Xd=9e4,I_=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]);function uf(t,e){let n=e?.length?e.map(s=>{let r=s.lastIndexOf("."),i=r>=0?s.slice(r).toLowerCase():"";return`[Attached ${I_.has(i)?"image":"file"}: ${s}]`}).join(`
108
108
  `):"";return n?t?`${t}
109
109
 
110
- ${n}`:n:t}function Ut(t){return t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},enqueuedAt:e.enqueuedAt}))}function Xd(t){return t?.length?t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},prompt:cf(e.content,e.images),enqueuedAt:e.enqueuedAt})):[]}function w_(t,e){let n=t?.length?t:void 0,s=e?.length?e:void 0;return!n||!s?n===s:n.length!==s.length?!1:n.every((r,i)=>r===s[i])}function bo(t,e,n){return{content:t,...e?.length?{images:e}:{},...n!==void 0?{model:n}:{}}}function Zd(t,e){return t?t.content===e.content&&w_(t.images,e.images)&&t.model===e.model:!1}var ef=200;function tf(t){return t?.replace(/_/g,"-").toLowerCase()?.startsWith("zh")?"zh":"en"}var I_={zh:"Agent \u5361\u4F4F",en:"Agent stalled"},A_={zh:"Agent \u5D29\u6E83",en:"Agent crashed"};function qt(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),s=e%60;return s===0?`${n} \u5206\u949F`:`${n} \u5206 ${s} \u79D2`}function uf(t){if(!t)return;let e=t.trim();if(e)return e.length>ef?`${e.slice(0,ef-1)}\u2026`:e}function T_(t,e,n,s){let r=qt(t),i=qt(n),o=qt(e),a=uf(s),l=a?`
111
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${a}"\u3002`:"",u=n>e?`Agent \u957F\u65F6\u95F4\u6CA1\u6709\u8F93\u51FA\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\u540E\u88AB\u81EA\u52A8\u505C\u6B62\uFF08${o} \u65F6\u5DF2\u6807\u8BB0\u7591\u4F3C\u5361\u4F4F\uFF09\u3002`:`Agent \u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u9608\u503C\u540E\u88AB\u81EA\u52A8\u505C\u6B62\u3002`;return{kind:"stall_timeout",at:new Date().toISOString(),humanText:`${u}${l}`,...a?{lastPrompt:a}:{},idleMs:t,softThresholdMs:e,stopThresholdMs:n}}function C_(t,e,n){let s=qt(t),r=qt(e),i=n>0?qt(n):void 0;return{at:new Date().toISOString(),humanText:i?`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5982\u679C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\uFF0C\u5C06\u81EA\u52A8\u505C\u6B62\u3002`:`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5F53\u524D\u4E0D\u4F1A\u81EA\u52A8\u505C\u6B62\uFF0C\u4F60\u53EF\u4EE5\u7EE7\u7EED\u7B49\u5F85\u6216\u624B\u52A8\u505C\u6B62\u3002`,idleMs:t,softThresholdMs:e,...n>0?{hardTimeoutMs:n}:{}}}function k_(t,e){let n=uf(e),s=n?`
112
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"driver_crash",at:new Date().toISOString(),humanText:`Agent \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${t}\uFF09\u3002${s}`,...n?{lastPrompt:n}:{},exitCode:t}}function x_(t,e){return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,...Number.isFinite(e.cacheCreationInputTokens)?{cacheCreationInputTokens:e.cacheCreationInputTokens}:Number.isFinite(t?.cacheCreationInputTokens)?{cacheCreationInputTokens:t?.cacheCreationInputTokens}:{},...Number.isFinite(e.cacheReadInputTokens)?{cacheReadInputTokens:e.cacheReadInputTokens}:Number.isFinite(t?.cacheReadInputTokens)?{cacheReadInputTokens:t?.cacheReadInputTokens}:{},...Number.isFinite(e.contextWindowTokens)?{contextWindowTokens:e.contextWindowTokens}:Number.isFinite(t?.contextWindowTokens)?{contextWindowTokens:t?.contextWindowTokens}:{}}:t}function nf(t){if(t)return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,...Number.isFinite(t.cacheCreationInputTokens)?{cacheCreationInputTokens:t.cacheCreationInputTokens}:{},...Number.isFinite(t.cacheReadInputTokens)?{cacheReadInputTokens:t.cacheReadInputTokens}:{},...Number.isFinite(t.contextWindowTokens)?{contextWindowTokens:t.contextWindowTokens}:{}}}function R_(t,e){return t?.inputTokens===e?.inputTokens&&t?.outputTokens===e?.outputTokens&&t?.cacheCreationInputTokens===e?.cacheCreationInputTokens&&t?.cacheReadInputTokens===e?.cacheReadInputTokens&&t?.contextWindowTokens===e?.contextWindowTokens}function Ce(...t){let e=[];for(let n of t)if(n?.length)for(let s of n)!s||e.includes(s)||(e.push(s),e.length>Wt&&e.splice(0,e.length-Wt));return e}function ar(t){return t?.length?{acceptedClientMessageIds:Ce(t)}:{}}function j(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,model:t.model,acceptedClientMessageIds:Ce(t.acceptedClientMessageIds),interruptedClientMessageIds:Ce(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,lastUsage:t.lastUsage,managed:t.managed,isResponding:t.isResponding||void 0,interruptReason:t.interruptReason,stallWarning:t.stallWarning,pendingQueue:t.pendingQueue.length>0?Ut(t.pendingQueue):void 0}}function sf(t){t.managed||(t.managed=!0)}function rf(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Ms(e)}function of(t,e,n){return{sessionId:t,agent:e,...n}}function E_(t){return t.startsWith(Ni)}function af(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 lr=class{constructor(e=sr,n=Zu){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=dd(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.updateGauges(),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new er;idleSweepInterval=null;watchdogNowMs=Date.now();lastWatchdogWallClockMs=this.watchdogNowMs;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),__),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=this.advanceWatchdogClock(Date.now(),"sweep"),n=S.idleTimeoutMs,s=S.turnStallTimeoutMs,r=S.turnStallHardTimeoutMs;if(n<=0&&s<=0)return;let i=3600*1e3;for(let[o,a]of this.sessions){if(!a.active&&!a.driver){if(a.clients.size===0){let u=e-a.lastActivityTs;u>=i&&(b.info({sessionId:a.sessionId,inactiveMs:u},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(a),this.sessions.delete(o))}continue}if(!a.active||!a.driver)continue;let l=e-a.lastActivityTs;if(a.isResponding){if(s<=0||a.pendingApproval||l<s)continue;let u=this.getRespondingLivenessHint(a),c=r>0&&l>=r,d=u==="dead";if(!d&&!c){if(!a.stallWarningAt){let m=C_(l,s,r);a.stallWarningAt=e,a.stallWarning=m,this.updateGauges(),b.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"responding session exceeded soft stall threshold; waiting before forced stop"),_.increment("driver.stall_warning",{agent:a.agent}),w.emit("driver.stall_warning",{sessionId:a.sessionId,agent:a.agent,idleMs:l,hardTimeoutMs:r||void 0}),this.broadcast(a.sessionId,{type:"session.stall_warning",sessionId:a.sessionId,warning:m}),this.store.upsert(j(a)),this.noteInventoryChanged("session_updated")}continue}let f=d||r<=0?s:r;b.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:a.agent}),w.emit("driver.stall_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l});let h=T_(l,s,f,a.lastUserMessage);a.interruptReason=h,this.clearStallWarning(a),this.resolvePendingClaudeHookApprovals(a),a.driver.stop(),a.active=!1,a.driver=null,a.isResponding=!1,a.currentReplyText="",delete a.currentTurn,this.updateGauges(),this.broadcast(a.sessionId,{type:"session.interrupted_notice",sessionId:a.sessionId,reason:h});let g=this.buildPushBody(`${a.title||a.sessionId}: ${h.lastPrompt??""}`.trim());this.pushSender(m=>({title:I_[tf(m)],body:g}),{sessionId:a.sessionId,agent:a.agent,eventType:"agent_stalled"}),this.touchSession(a.sessionId),this.store.upsert(j(a)),this.noteInventoryChanged("session_updated");continue}a.pendingApproval||n<=0||l<n||(b.info({sessionId:a.sessionId,agent:a.agent,idleMs:l,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:a.agent}),w.emit("driver.idle_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l}),a.driver.stop(),a.active=!1,a.driver=null,this.updateGauges(),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,s,r){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){b.info({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(b.debug({agent:n,context:s,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,r),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,delete e.currentTurn,o.type==="session.done"&&(n==="claude"?(e.lastUsage=nf(o.usage),this.reconcileClaudeSessionUsage(e,o.usage)):o.usage&&(e.lastUsage=x_(e.lastUsage,o.usage))),o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!rf(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){w.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}b.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({title:S_,body: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"&&Ms(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:b.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry"));let a=this.clearStallWarning(e);this.touchSession(e.sessionId,o.type!=="text.delta"||a),(a||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"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.pendingQueue.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){b.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}b.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"driver exited"),w.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;_.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&rf(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.clearStallWarning(e),l||(e.pendingApproval=void 0),a){let u=k_(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u});let c=this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim());this.pushSender(d=>({title:A_[tf(d)],body:c}),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert(j(e)),this.noteInventoryChanged("session_updated")})}async reconcileClaudeSessionUsage(e,n){let s=await Ld(e.sessionId,e.cwd),r=nf(s??n);!r||R_(e.lastUsage,r)||(e.lastUsage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"))}remapSessionId(e,n,s){if(!n||n===e.sessionId)return;let r=this.sessions.get(n);if(r&&r!==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.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(j(e)),this.noteInventoryChanged("session_remapped"),s&&this.reply(s,`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 s=e.pendingQueue.shift();return s?(s.clientMessageId&&this.rememberAcceptedClientMessage(e,s.clientMessageId),s.model!==void 0&&(e.model=s.model||void 0),e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=s.content,e.currentTurn=bo(s.content,s.images,s.model),e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),this.store.upsert(j(e)),this.broadcastPendingQueue(e),e.driver.sendPrompt(s.prompt,e.model),!0):!1}broadcastPendingQueue(e){this.broadcast(e.sessionId,{type:"session.queue",sessionId:e.sessionId,pending:Ut(e.pendingQueue)})}cancelQueuedTurn(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){this.reply(e,n,!1,void 0,"Session not found");return}if(!r){this.reply(e,n,!1,void 0,"clientMessageId required");return}let a=o.pendingQueue.length;o.pendingQueue=o.pendingQueue.filter(u=>u.clientMessageId!==r);let l=a-o.pendingQueue.length;l>0&&(w.emit("session.queue.cancel",{sessionId:s,agent:o.agent,clientMessageId:r,removed:l}),this.store.upsert(j(o)),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.broadcastPendingQueue(o)),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s,removed:l}))}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&Nd(e.sessionId,e.agent,e.cwd,n).then(s=>{for(let r of s)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:r})}).catch(s=>{b.warn({sessionId:e.sessionId,error:String(s)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let s=e.driver,r=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await s.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(r)!==e||e.startupToken!==i||e.driver!==s){b.info({pendingSessionId:r,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:r,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==r&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(r)!==e||e.startupToken!==i){b.info({pendingSessionId:r,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1;let u=e.pendingQueue.length>0;e.pendingQueue=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),u&&this.broadcastPendingQueue(e),b.error({sessionId:r,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,s,r){if(e==="codex"&&n instanceof An&&r&&n.setModel(r),e!=="claude"||!(n instanceof In))return;let i=s??(0,wo.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=bn){for(let s of e.pendingClaudeHookApprovals.values())s.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&E_(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 s=this.resolveClaudeHookSession(e);return s?(this.touchSession(s.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let s=this.resolveClaudeHookSession(e);if(!s||s.agent!=="claude"||!s.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),bn;if(s.approvalMode==="autoApprove")return af(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return bn;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:"",u=`${Ni}${l.trim()||(0,wo.randomUUID)()}`,c=s.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return s.pendingClaudeHookApprovals.set(u,{requestId:u,promise:h,resolve:g=>{s.pendingClaudeHookApprovals.delete(u),f(g)}}),s.pendingApproval={requestId:u,toolName:i,input:a,description:d},w.emit("approval.request",{agent:"claude",sessionId:s.sessionId,toolName:i}),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"approval.request",sessionId:s.sessionId,requestId:u,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,s){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let r=new Date().toISOString(),i=s?.agent,o=s?.cwd??"",a=s?.approvalMode,l=s?.model,u=s?.pendingApproval,c=s?.title??"",d=s?.createdAt??r,f=s?.lastActivityAt??r,h=s?.lastUsage,g=Ce(s?.acceptedClientMessageIds),m=Ce(s?.interruptedClientMessageIds),p=s?.isResponding,y=s?.interruptReason,C=s?.stallWarning,A=s?[...s.pendingQueue]:[],T=s?"memory":"client",I=this.store.find(e);if(I)i=I.agent,o=I.cwd||o,a=I.approvalMode??a,l=I.model??l,u=I.pendingApproval??u,c=I.title||c,d=I.createdAt||d,f=I.lastActivityAt||f,h=I.lastUsage??h,g=Ce(I.acceptedClientMessageIds,g),m=Ce(I.interruptedClientMessageIds,m),y=y??I.interruptReason,C=C??I.stallWarning,s||(A=Xd(I.pendingQueue)),T="record";else if(!s){let x=(await Mn(n??i)).find(X=>X.sessionId===e);x&&(i=x.agent,o=x.cwd||o,c=x.title??c,d=x.createdAt,f=x.lastActivityAt,h=x.lastUsage??h,p=x.runtime.isResponding??p,T="scanner")}if(!i&&n&&(i=n,T=s?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,model:l,pendingApproval:u,title:c,createdAt:d,lastActivityAt:f,lastUsage:h,acceptedClientMessageIds:g,interruptedClientMessageIds:m,source:T,managed:s?.managed??I?.managed,isResponding:p||void 0,...y?{interruptReason:y}:{},...C?{stallWarning:C}:{},pendingQueue:A}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let s of this.sessions.values()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(of(s.sessionId,s.agent,s.pendingApproval)))}for(let s of this.store.getAll()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(of(s.sessionId,s.agent,s.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),s=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="",delete e.currentTurn,e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=s??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(j(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<=Jd?n:`${n.slice(0,Math.max(1,Jd-3)).trimEnd()}...`:v_}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}currentWatchdogTime(){return this.advanceWatchdogClock(Date.now(),"activity")}getRespondingLivenessHint(e){return e.driver?.getRespondingLivenessHint?.()??"unknown"}clearStallWarning(e){return!e.stallWarning&&!e.stallWarningAt?!1:(e.stallWarning=void 0,e.stallWarningAt=void 0,this.updateGauges(),!0)}advanceWatchdogClock(e,n){let s=Math.max(0,e-this.lastWatchdogWallClockMs);return this.lastWatchdogWallClockMs=e,s<=0?this.watchdogNowMs:s>Kd?(n==="sweep"&&b.warn({elapsedWallMs:s,toleratedGapMs:Kd},"watchdog gap detected; discounting paused wall-clock time"),this.watchdogNowMs):(this.watchdogNowMs+=s,this.watchdogNowMs)}touchSession(e,n=!0){let s=Date.now(),r=new Date(s).toISOString(),i=this.advanceWatchdogClock(s,"activity"),o=this.sessions.get(e);if(o){o.lastActivityAt=r,o.lastActivityTs=i,n&&this.store.upsert(j(o));return}let a=this.store.find(e);a&&this.store.upsert({...a,lastActivityAt:r})}updateGauges(){let e=0,n=0;for(let s of this.sessions.values())s.active&&e++,s.stallWarning&&n++;_.gauge("session.active",e),_.gauge("session.stall_warning_active",n)}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,model:n.model,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,lastUsage:n.lastUsage,...n.pendingApproval||n.stallWarning?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{},...n.stallWarning?{stallWarning:n.stallWarning}:{}});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}resolveSessionRef(e){let n=this.store.resolveSessionId(e);return{requestedSessionId:e,resolvedSessionId:n,remapped:n!==e}}buildResolvedSessionResponseData(e,n){let s=n?{...n}:{};return e.remapped&&(s.sessionId=e.resolvedSessionId,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s:void 0}buildSessionResponseData(e,n,s){let r=s?{...s}:{};return n&&n!==e.requestedSessionId&&(r.sessionId=n,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}canResumeDriverSession(e,n){return!(e==="codex"&&n.startsWith("pending_"))}rememberSessionAlias(e,n){!e||!n||e===n||(this.store.forget(e),this.store.addAlias(e,n),this.noteInventoryChanged("session_remapped"))}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return Mn(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.queue.cancel":this.cancelQueuedTurn(e,n.id,n.sessionId,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.clearInterrupt":this.clearInterrupt(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,n.customTitles,n.sinceMs);break;case"sessions.list":{let s=typeof n.skipGitMetadata=="boolean"?n.skipGitMetadata:void 0;await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles,n.sinceMs,s);break}case"sessions.archiveableManaged":this.listArchiveableManagedSessions(e,n.id);break;case"session.setArchived":this.setSessionArchived(e,n.id,n.sessionId,n.archived);break;case"sessions.archiveSync":this.archiveSync(e,n.id,n.mode,n.archivedSessionIds);break;case"usage.limits.fetch":await this.handleUsageLimitsFetch(e,n.id,n.agent,n.force);break}}async handleUsageLimitsFetch(e,n,s,r){let i=await Yd(s,{force:!!r});this.reply(e,n,!0,i)}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(){zs({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).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},s=JSON.stringify(n);for(let r of this.globalClients)r.readyState===1&&r.send(s)}async createSession(e,n,s,r,i,o,a){r=tr(r),b.info({agent:s,cwd:r,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,lf.stat)(r)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${r}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${r}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(s,r)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return b.info({sessionId:u.sessionId,cwd:r},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,s,r,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(s),u=this.configureDriverBeforeStart(s,l,void 0,a);if(s==="codex"){let g=`pending_${Date.now()}`;b.info({sessionId:g,agent:s,cwd:r},"session created (pending codex startup)"),_.increment("session.create",{agent:s}),w.emit("session.create",{sessionId:g,agent:s,cwd:r,approvalMode:i});let m={sessionId:g,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,pendingQueue:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(g,m),this.registerClaudeHookSession(m),this.store.upsert(j(m)),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(m,s,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(m,e);return}let c=_.startTimer("driver.spawn"),d=await l.start(r,void 0,i),f=c();b.info({sessionId:d,agent:s,spawnMs:f},"session created"),_.increment("session.create",{agent:s}),w.emit("session.create",{sessionId:d,agent:s,cwd:r,approvalMode:i});let h={sessionId:d,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(j(h)),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,s,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){b.error({agent:s,cwd:r,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,s,r,i,o){let a=this.resolveSessionRef(s);if(s=a.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(s);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let h=await Ln(s,r,l.cwd),g=this.annotateHistoryMessages(h,l.acceptedClientMessageIds,l.interruptedClientMessageIds),m=this.currentPartialReplyText(l),p=l.pendingQueue.length>0?Ut(l.pendingQueue):void 0;if(h.length>0||m||l.approvalMode||l.pendingApproval||l.stallWarning||p){let y={type:"session.history",sessionId:s,messages:g,...ar(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:m,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval,stallWarning:l.stallWarning,...p?{pendingQueue:p}:{}};e.readyState===1&&e.send(JSON.stringify(y))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:s}));return}let u=this.store.find(s),c=i||u?.cwd||"",d=o??u?.approvalMode,f=u?.title??"Resumed session";try{let h=_.startTimer("driver.spawn"),g=this.createDriver(r),m=this.configureDriverBeforeStart(r,g),p=this.canResumeDriverSession(r,s),y=await g.start(c,p?s:void 0,d),C=h();b.info({sessionId:y,agent:r,spawnMs:C},"session resumed"),_.increment("session.resume",{agent:r}),w.emit("session.resume",{sessionId:y,agent:r,cwd:c});let A={sessionId:y,agent:r,cwd:c,approvalMode:d,model:u?.model,driver:g,clients:new Set([e]),title:f,createdAt:u?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),lastUsage:u?.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:u?.acceptedClientMessageIds??[],interruptedClientMessageIds:u?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:Xd(u?.pendingQueue),startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,stallWarning:u?.stallWarning,claudeHookSecret:m,pendingClaudeHookApprovals:new Map};this.sessions.set(y,A),this.rememberSessionAlias(s,y),this.registerClaudeHookSession(A),this.store.upsert(j(A)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(A,r," (resumed)",e),this.restoreDriverPendingApproval(g,A.pendingApproval);let I=await Ln(p?s:y,r,c),D=this.annotateHistoryMessages(I,A.acceptedClientMessageIds,A.interruptedClientMessageIds),x=A.pendingQueue.length>0?Ut(A.pendingQueue):void 0;if(I.length>0||A.pendingApproval||A.stallWarning||x){b.info({sessionId:s,historyCount:I.length},"sending history messages");let X={type:"session.history",sessionId:y,messages:D,...ar(A.acceptedClientMessageIds),approvalMode:d,pendingApproval:A.pendingApproval,stallWarning:A.stallWarning,...x?{pendingQueue:x}:{}};e.readyState===1&&e.send(JSON.stringify(X))}this.reply(e,n,!0,this.buildSessionResponseData(a,y,{sessionId:y}))}catch(h){this.reply(e,n,!1,void 0,String(h))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Wt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Wt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Wt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Wt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,s){if(!e.length||!n?.length||!s?.length)return e;let r=new Set(s),i=[];for(let c=0;c<e.length;c+=1)e[c]?.role==="user"&&i.push(c);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,u=i.length-o;for(let c=0;c<o;c+=1){let d=n[l+c];r.has(d)&&a.set(i[u+c],"interrupted")}return a.size===0?e:e.map((c,d)=>c.role==="user"&&a.has(d)?{...c,delivery:"interrupted"}:c)}hasDuplicateInFlightTurn(e,n){return(e.isResponding||e.pendingApproval)&&Zd(e.currentTurn,n)?!0:e.pendingQueue.some(s=>Zd(s,n))}async sendMessage(e,n,s,r,i,o,a,l){let u=this.resolveSessionRef(s);if(s=u.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(s);if(!c||!c.driver){let p=await this.resolveReconnectSession(s,i,c);if(!p){b.warn({sessionId:s},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:s,agent:p.agent,source:p.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:p.agent,source:p.source}),w.emit("session.reconnect",{sessionId:s,agent:p.agent,source:p.source});try{let y=this.createDriver(p.agent),C=this.configureDriverBeforeStart(p.agent,y,c?.claudeHookSecret),A=this.canResumeDriverSession(p.agent,s),T=await y.start(p.cwd,A?s:void 0,p.approvalMode);this.restoreDriverPendingApproval(y,p.pendingApproval),c?(c.approvalMode=p.approvalMode,c.model=p.model,c.pendingApproval=p.pendingApproval,c.driver=y,c.active=!0,c.clients.add(e),c.lastActivityAt=p.lastActivityAt,c.lastUsage=p.lastUsage,c.lastActivityTs=this.currentWatchdogTime(),c.isResponding=!1,c.currentReplyText="",delete c.currentTurn,c.acceptedClientMessageIds=Ce(c.acceptedClientMessageIds,p.acceptedClientMessageIds),c.interruptedClientMessageIds=Ce(c.interruptedClientMessageIds,p.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,(!c.pendingQueue||c.pendingQueue.length===0)&&(c.pendingQueue=p.pendingQueue),c.startupToken=c.startupToken??0,c.claudeHookSecret=C??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,T&&T!==c.sessionId&&this.remapSessionId(c,T)):(c={sessionId:T,agent:p.agent,cwd:p.cwd,approvalMode:p.approvalMode,model:p.model,driver:y,clients:new Set([e]),title:p.title,createdAt:p.createdAt,lastActivityAt:p.lastActivityAt,lastUsage:p.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:p.acceptedClientMessageIds,interruptedClientMessageIds:p.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:p.pendingQueue,startupToken:0,managed:p.managed,pendingApproval:p.pendingApproval,claudeHookSecret:C,pendingClaudeHookApprovals:new Map,interruptReason:p.interruptReason},this.sessions.set(T,c),this.rememberSessionAlias(s,T)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,p.agent," (reconnected)"),this.store.upsert(j(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),s=c.sessionId,c.pendingQueue.length>0&&this.flushBufferedPrompt(c)}catch(y){this.reply(e,n,!1,void 0,`Failed to reconnect: ${y}`);return}}if(c.clients.add(e),o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,clientMessageId:o,duplicate:!0}));return}let d=cf(r,a),f=l!==void 0&&l||void 0,h=bo(r,a,f);if(this.hasDuplicateInFlightTurn(c,h)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,...o?{clientMessageId:o}:{},duplicate:!0})),b.debug({sessionId:s,hasClientMessageId:!!o,imageCount:a?.length??0},"duplicate in-flight session.send suppressed");return}b.info({sessionId:s,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),w.emit("session.send",{sessionId:s,agent:c.agent,messagePreview:r.slice(0,100),imageCount:a?.length??0}),sf(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert(j(c)),this.noteInventoryChanged("session_updated"));let g=this.clearStallWarning(c);if(Mt(c.title)){let p=Gi(r,50);p&&p!==c.title&&(c.title=p),this.store.upsert(j(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId),g&&this.noteInventoryChanged("session_updated");let m=p=>{let y={...o?{clientMessageId:o}:{},content:h.content,...h.images?.length?{images:h.images}:{},...f!==void 0?{model:f}:{},prompt:d,enqueuedAt:new Date().toISOString()};c.pendingQueue.push(y),this.store.upsert(j(c)),this.broadcastPendingQueue(c);let C=o?{sessionId:s,clientMessageId:o,queued:!0}:{sessionId:s,queued:!0};this.reply(e,n,!0,this.buildSessionResponseData(u,s,C)),b.debug({sessionId:s,reason:p,queueLength:c.pendingQueue.length},"message enqueued on daemon")};if(l!==void 0&&(c.model=l||void 0),c.pendingApproval){m("pending_approval");return}if(c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,this.noteInventoryChanged("session_updated"),m("startup");return}if(c.isResponding||c.pendingQueue.length>0){m("busy"),c.isResponding||this.flushBufferedPrompt(c);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,c.currentTurn=h,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,s,o?{sessionId:s,clientMessageId:o}:{sessionId:s}))}async sendReconnectSnapshot(e,n,s,r,i,o,a,l,u){try{let c=this.getDeletedSessionIds(),d;try{d=await zs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(g){b.warn({error:String(g)},"failed to build reconnect snapshot session list"),d={sessions:[],nextCursor:void 0}}d={...d,sessions:this.decorateSessionsWithArchived(d.sessions),inventoryVersion:this.inventoryVersion};let f;if(o&&!c.has(o)){let g=o;o=this.resolveSessionRef(o).resolvedSessionId;let m=a??d.sessions.find(C=>C.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let y=await this.resolveReconnectSession(o,m,p);if(y){let C=await Ln(o,y.agent,p?.cwd??y.cwd),A=this.annotateHistoryMessages(C,p?.acceptedClientMessageIds??y.acceptedClientMessageIds,p?.interruptedClientMessageIds??y.interruptedClientMessageIds),T=p?{}:await mo(o,y.agent,y.cwd),I=!p&&!!T.isResponding,D=I?await this.externalProcessPresenceCheck(o):!1,x=I&&!D?{}:T,X=p?.interruptReason??y.interruptReason,ut=p?.stallWarning??y.stallWarning,Gn=p?.pendingQueue??y.pendingQueue;f={sessionId:o,agent:y.agent,messages:A,...ar(p?.acceptedClientMessageIds??y.acceptedClientMessageIds),isResponding:p?.isResponding??x.isResponding??(I&&!D?void 0:y.isResponding),...D?{externallyResponding:!0}:{},partialReplyText:p?this.currentPartialReplyText(p):x.partialReplyText,approvalMode:p?.approvalMode??y.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{},...X?{interruptReason:X}:{},...ut?{stallWarning:ut}:{},...Gn.length>0?{pendingQueue:Ut(Gn)}:{}},g!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:g})}}let h=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:f?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:d.sessions,nextCursor:d.nextCursor,inventoryVersion:d.inventoryVersion,...f?{activeSession:f}:{},...h.length>0?{pendingApprovals:h}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,s,r,i){let o=this.resolveSessionRef(s);s=o.resolvedSessionId;let a=this.sessions.get(s),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(r);if(a&&u){a.pendingApproval=void 0,w.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(af(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}));return}let c=a?.syntheticApprovalRetries[r];if(a&&c&&Ms(r)){delete a.syntheticApprovalRetries[r],a.pendingApproval=void 0,w.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s})),i&&await this.retrySyntheticClaudeApproval(a,c);return}if(a&&!a.driver&&l)try{await this.reviveSessionForApproval(a)}catch(f){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(f)}`);return}if(!a?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(w.emit("approval.response",{sessionId:s,requestId:r,approved:i}),!a.driver.respondApproval(r,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}a.pendingApproval=void 0,this.touchSession(a.sessionId),a.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let s=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",r=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,r,e.claudeHookSecret);await r.start(e.cwd,e.sessionId,s),e.driver=r,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.currentTurn=bo(n.message),e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],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(j(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:s},"retrying Claude turn after synthetic approval"),r.sendPrompt(n.message,e.model)}catch(s){e.driver=null,e.active=!1,e.isResponding=!1,delete e.currentTurn,e.startupInProgress=!1;let r=e.pendingQueue.length>0;e.pendingQueue=[],e.startupToken+=1,r&&this.broadcastPendingQueue(e),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:e.sessionId,error:String(s)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(s)}`})}}async setApprovalMode(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){let l=this.store.find(s);l?(r===null?delete l.approvalMode:l.approvalMode=r,this.store.upsert(l),this.noteInventoryChanged("session_updated"),b.info({sessionId:s,agent:l.agent,newMode:r},"approval mode changed (inactive session)")):b.info({sessionId:s,newMode:r},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}));return}if(r===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=r,this.store.upsert(j(o)),this.noteInventoryChanged("session_updated"),b.info({sessionId:s,agent:o.agent,oldMode:a,newMode:r},"approval mode changed"),o.driver&&o.driver.setApprovalMode(r),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}))}interrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(w.emit("session.interrupt",{sessionId:s,agent:i.agent}),!i.driver){if(i.isResponding||i.pendingQueue.length>0){b.info({sessionId:s,agent:i.agent},"interrupting driverless session with stale responding state");let o=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),o&&this.broadcastPendingQueue(i),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})}this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}if(i.startupInProgress){let o=i.isResponding||i.pendingQueue.length>0;b.info({sessionId:s,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session");let a=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),a&&this.broadcastPendingQueue(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}clearInterrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s),o=this.store.find(s);if(!i&&!o?.interruptReason){this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}let a=!1;i?.interruptReason&&(i.interruptReason=void 0,a=!0),i?this.store.upsert(j(i)):o?.interruptReason&&(this.store.upsert({...o,interruptReason:void 0}),a=!0),a&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}stopSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:s,agent:i.agent},"stopping session"),w.emit("session.stop",{sessionId:s,agent:i.agent}),sf(i);let o=i.isResponding||i.pendingQueue.length>0||i.startupInProgress,a=i.pendingQueue.length>0;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",delete i.currentTurn,i.pendingApproval=void 0,i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),a&&this.broadcastPendingQueue(i),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}deleteSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);i&&(b.info({sessionId:s,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(s)),w.emit("session.delete",{sessionId:s}),this.store.remove(s),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}async sendHistory(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}o&&o.clients.add(e);let l=a?.cwd??o?.cwd??this.store.find(s)?.cwd??"",u=this.store.find(s),c=await Ln(s,r,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),f=a||o?{}:await mo(s,r,l),h=!a&&!!f.isResponding,g=h?await this.externalProcessPresenceCheck(s):!1,m=g?!0:void 0,p=h&&!g?{}:f,y=a?.isResponding??p.isResponding,C=a?this.currentPartialReplyText(a):p.partialReplyText;b.info({sessionId:s,historyCount:c.length,isResponding:y,externallyResponding:m,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let A=o&&o.pendingQueue.length>0?Ut(o.pendingQueue):u?.pendingQueue&&u.pendingQueue.length>0?u.pendingQueue:void 0,T={type:"session.history",sessionId:s,messages:d,...ar(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:m,partialReplyText:C,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval,stallWarning:o?.stallWarning??u?.stallWarning,...A?{pendingQueue:A}:{}};e.readyState===1&&e.send(JSON.stringify(T));let I=o?.interruptReason??u?.interruptReason;if(I&&e.readyState===1){let D={type:"session.interrupted_notice",sessionId:s,reason:I};e.send(JSON.stringify(D))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s}))}async listSessions(e,n,s,r,i,o=50,a,l,u,c){try{let d=await zs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:c}),f=this.decorateSessionsWithArchived(d.sessions);this.reply(e,n,!0,{...d,sessions:f,inventoryVersion:this.inventoryVersion})}catch(d){this.reply(e,n,!1,void 0,String(d))}}setSessionArchived(e,n,s,r){if(typeof s!="string"||s.length===0){this.reply(e,n,!1,void 0,"sessionId is required");return}this.store.setArchived(s,r===!0)&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,{archived:this.store.isArchived(s)})}archiveSync(e,n,s,r){let i,o=!1;switch(s){case"pushReplace":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.replaceArchivedSessionIds(l),o=u.size!==i.length||i.some(c=>!u.has(c));break}case"pushMerge":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.mergeArchivedSessionIds(l),o=i.some(c=>!u.has(c));break}case"pull":{i=this.store.getArchivedSessionIds();break}default:this.reply(e,n,!1,void 0,`unknown archive sync mode: ${String(s)}`);return}o&&this.noteInventoryChanged("session_updated");let a={archivedSessionIds:i};this.reply(e,n,!0,a)}decorateSessionsWithArchived(e){return e.length===0?e:e.map(n=>({...n,archived:this.store.isArchived(n.sessionId)}))}listArchiveableManagedSessions(e,n){let s=this.getDeletedSessionIds(),r=new Set;for(let o of this.sessions.values())o.managed&&(o.sessionId.startsWith("pending_")||s.has(o.sessionId)||r.add(o.sessionId));for(let o of this.store.getAll())o.managed&&(s.has(o.sessionId)||r.add(o.sessionId));let i={count:r.size,ids:[...r]};this.reply(e,n,!0,i)}createDriver(e){if(S.reviewMock)return new Ls;switch(e){case"claude":return new In;case"codex":return new An;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let s=this.sessions.get(e);if(!s){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let r=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:s.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(r),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){s.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=s.title||e,c=this.buildPushBody(s.currentReplyText);s.currentReplyText="",this.pushSender({title:u,body:c},{sessionId:e,agent:s.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(s.currentReplyText="")}reply(e,n,s,r,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:s,data:r,error:i};e.send(JSON.stringify(o))}};function Io(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,t.locale):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var df=require("child_process");function P_(t,e){return(0,df.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function M_(t){let e=t.split(`
113
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function ff(t,e=P_){let n;try{n=M_(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(s=>{try{let r=e("ps",["-p",String(s),"-o","command="]);return r?{pid:s,command:r}:{pid:s}}catch{return{pid:s}}})}var Gt=require("fs"),Ao=require("os"),hf=require("crypto"),gf=require("path");function mf(t){return(0,hf.randomBytes)(t).toString("base64url")}function L_(){return`d_${mf(12)}`}function N_(){return(0,Ao.hostname)()}function O_(){let t=(0,Ao.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function D_(t){return{daemonId:L_(),daemonSecret:mf(32),displayName:N_(),canonicalHost:O_(),port:t,createdAt:new Date().toISOString()}}function pf(t,e){(0,Gt.mkdirSync)((0,gf.dirname)(e),{recursive:!0}),(0,Gt.writeFileSync)(e,JSON.stringify(t,null,2)+`
114
- `,"utf8")}function yf(t,e=Yc){try{let s=(0,Gt.readFileSync)(e,"utf8"),r=JSON.parse(s);if(typeof r.daemonId=="string"&&typeof r.daemonSecret=="string"&&typeof r.displayName=="string"&&typeof r.canonicalHost=="string"&&typeof r.createdAt=="string"){let i={daemonId:r.daemonId,daemonSecret:r.daemonSecret,displayName:r.displayName,canonicalHost:r.canonicalHost,port:typeof r.port=="number"&&Number.isFinite(r.port)?r.port:t,createdAt:r.createdAt};return i.port!==t&&(i.port=t,pf(i,e)),i}}catch{}let n=D_(t);return pf(n,e),n}var jt=require("crypto"),$t=require("fs"),Sf=require("path");function To(t){return(0,jt.randomBytes)(t).toString("base64url")}function Co(t){return(0,jt.createHash)("sha256").update(t).digest("hex")}function vf(t,e){let n=Buffer.from(t),s=Buffer.from(e);return n.length!==s.length?!1:(0,jt.timingSafeEqual)(n,s)}function B_(t){try{let e=(0,$t.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(s=>s&&typeof s.deviceId=="string"&&typeof s.deviceName=="string"&&typeof s.tokenHash=="string"&&typeof s.createdAt=="string"&&typeof s.lastSeenAt=="string"&&(typeof s.revokedAt=="string"||s.revokedAt===null)):[]}catch{return[]}}function Hn(t,e){(0,$t.mkdirSync)((0,Sf.dirname)(t),{recursive:!0}),(0,$t.writeFileSync)(t,JSON.stringify(e,null,2)+`
115
- `,"utf8")}var cr=class{constructor(e=Jc){this.pairingsPath=e;this.records=B_(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 s=`pair_${To(8)}`,r=To(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:s,pairNonce:r,expiresAt:i,reusable:n};return this.windows.set(r,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 s=new Date().toISOString(),r=To(32),i={deviceId:e,deviceName:n,tokenHash:Co(r),createdAt:s,lastSeenAt:s,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Hn(this.pairingsPath,this.records),r}validatePairToken(e,n,s=!0){let r=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!r)return!1;let i=Co(n);return vf(r.tokenHash,i)?(s&&(r.lastSeenAt=new Date().toISOString(),Hn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let s=Co(e),r=this.records.find(i=>!i.revokedAt&&vf(i.tokenHash,s));return r?(n&&(r.lastSeenAt=new Date().toISOString(),Hn(this.pairingsPath,this.records)),r):null}revoke(e){let n=this.records.find(s=>s.deviceId===e&&!s.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Hn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Hn(this.pairingsPath,this.records)}};function ur(t){return Array.isArray(t)?t[0]:t}function _f(t){let e=ur(t.headers["x-forwarded-for"]),n=ur(t.headers["cf-connecting-ip"]),s=ur(t.headers["x-real-ip"]),r=e?.split(",")[0]?.trim()||n||s||t.socket.remoteAddress||void 0,i=ur(t.headers["user-agent"]);return{...r?{ip:r}:{},...i?{userAgent:i}:{}}}function F_(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}var H_=["x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","forwarded","via","cf-connecting-ip","cf-ray"];function U_(t){for(let e of H_)if(t[e]!==void 0)return!0;return!1}function lt(t){return F_(t.socket.remoteAddress)&&!U_(t.headers)}function W_(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function ko(t,e){return W_(t)??e}function dr(t,e){return!!(t&&e&&t===e)}function xo(t,e,n,s=!0){return t?dr(t,e)?!0:!!n(t,s):!1}var bf=require("fs");var q_=new Set(["ws.connect","ws.auth.success"]);function G_(t){try{let n=(0,bf.readFileSync)(t,"utf8").split(`
116
- `),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&q_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function wf(t,e=20,n=De){let s=G_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var Tf=require("child_process"),Cf=require("fs");function fr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Ro(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function j_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function $_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function z_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function pr(t){return!!t&&!j_(t)&&!$_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Eo(t){return fe(t.replace(/^https?:\/\//,""))??t}function V_(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>pr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function Q_(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function Y_(t){let e=Eo(t);return Ro(e)||e.endsWith(".ts.net")}function J_(t){let e=Eo(t);return z_(e)||e.endsWith(".local")}function K_(t){return Eo(t).endsWith(".trycloudflare.com")}function If(t,e){return Y_(t)?"tailscale":J_(t)?"local_network":e?"configured_host":"fallback"}function kf(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function X_(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function Z_(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=K_(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function eb(t,e,n){let s=fe(t)||"localhost",r=V_(e,s);return kf([{kind:"direct",host:s,port:n,source:If(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:If(i,!1),stability:"stable"}))])}function xf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function tb(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&Q_(s))for(let i of r)i.internal||i.family!=="IPv4"||pr(i.address)&&(Ro(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Af(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>Ro(o)&&pr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Rf(t=Tf.execFileSync,e=Cf.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Af(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Af(s)}catch{return{fallbackHosts:[]}}}function Ef(t){let e=eb(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?Z_(t.relayUrl):null,s=kf([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:X_(s),port:r.port,connections:s}}function Pf(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...tb(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>pr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Mf(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 z=M.child({module:"daemon"}),Un=M.child({module:"ws"});function nb(){try{let t=JSON.parse(require("fs").readFileSync(Xc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var W=yf(S.port),te=new lr((t,e)=>sr(t,{daemonId:W.daemonId,canonicalHost:Wn().canonicalHost,...e??{}})),ae=new cr,gr=new Set,We=new WeakMap,Lf=!1,Bf=Date.now(),zt=null,hr=null,sb=1e3;function rb(){let t=Rf();return Pf({canonicalHost:W.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:xf(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Df.networkInterfaces)()})}function Wn(){let t=Date.now();if(hr&&hr.expiresAt>t)return hr.value;let e=rb(),n=Ef({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:W.port,relayUrl:S.relayUrl});return hr={value:n,expiresAt:t+sb},n}function ib(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,n.secure===!0])),e}async function ob(t){let e=JSON.stringify(ib(t));await(0,le.mkdir)(Ie,{recursive:!0}),await Lo.default.toFile(Ri,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Lo.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});kt(`
110
+ ${n}`:n:t}function Ut(t){return t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},enqueuedAt:e.enqueuedAt}))}function Zd(t){return t?.length?t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},prompt:uf(e.content,e.images),enqueuedAt:e.enqueuedAt})):[]}function A_(t,e){let n=t?.length?t:void 0,s=e?.length?e:void 0;return!n||!s?n===s:n.length!==s.length?!1:n.every((r,i)=>r===s[i])}function wo(t,e,n){return{content:t,...e?.length?{images:e}:{},...n!==void 0?{model:n}:{}}}function ef(t,e){return t?t.content===e.content&&A_(t.images,e.images)&&t.model===e.model:!1}var tf=200;function nf(t){return t?.replace(/_/g,"-").toLowerCase()?.startsWith("zh")?"zh":"en"}var T_={zh:"Agent \u5361\u4F4F",en:"Agent stalled"},C_={zh:"Agent \u5D29\u6E83",en:"Agent crashed"};function qt(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),s=e%60;return s===0?`${n} \u5206\u949F`:`${n} \u5206 ${s} \u79D2`}function df(t){if(!t)return;let e=t.trim();if(e)return e.length>tf?`${e.slice(0,tf-1)}\u2026`:e}function k_(t,e,n,s){let r=qt(t),i=qt(n),o=qt(e),a=df(s),l=a?`
111
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${a}"\u3002`:"",u=n>e?`Agent \u957F\u65F6\u95F4\u6CA1\u6709\u8F93\u51FA\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\u540E\u88AB\u81EA\u52A8\u505C\u6B62\uFF08${o} \u65F6\u5DF2\u6807\u8BB0\u7591\u4F3C\u5361\u4F4F\uFF09\u3002`:`Agent \u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u9608\u503C\u540E\u88AB\u81EA\u52A8\u505C\u6B62\u3002`;return{kind:"stall_timeout",at:new Date().toISOString(),humanText:`${u}${l}`,...a?{lastPrompt:a}:{},idleMs:t,softThresholdMs:e,stopThresholdMs:n}}function x_(t,e,n){let s=qt(t),r=qt(e),i=n>0?qt(n):void 0;return{at:new Date().toISOString(),humanText:i?`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5982\u679C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\uFF0C\u5C06\u81EA\u52A8\u505C\u6B62\u3002`:`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5F53\u524D\u4E0D\u4F1A\u81EA\u52A8\u505C\u6B62\uFF0C\u4F60\u53EF\u4EE5\u7EE7\u7EED\u7B49\u5F85\u6216\u624B\u52A8\u505C\u6B62\u3002`,idleMs:t,softThresholdMs:e,...n>0?{hardTimeoutMs:n}:{}}}function R_(t,e){let n=df(e),s=n?`
112
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"driver_crash",at:new Date().toISOString(),humanText:`Agent \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${t}\uFF09\u3002${s}`,...n?{lastPrompt:n}:{},exitCode:t}}function E_(t,e){return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,...Number.isFinite(e.cacheCreationInputTokens)?{cacheCreationInputTokens:e.cacheCreationInputTokens}:Number.isFinite(t?.cacheCreationInputTokens)?{cacheCreationInputTokens:t?.cacheCreationInputTokens}:{},...Number.isFinite(e.cacheReadInputTokens)?{cacheReadInputTokens:e.cacheReadInputTokens}:Number.isFinite(t?.cacheReadInputTokens)?{cacheReadInputTokens:t?.cacheReadInputTokens}:{},...Number.isFinite(e.contextWindowTokens)?{contextWindowTokens:e.contextWindowTokens}:Number.isFinite(t?.contextWindowTokens)?{contextWindowTokens:t?.contextWindowTokens}:{}}:t}function sf(t){if(t)return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,...Number.isFinite(t.cacheCreationInputTokens)?{cacheCreationInputTokens:t.cacheCreationInputTokens}:{},...Number.isFinite(t.cacheReadInputTokens)?{cacheReadInputTokens:t.cacheReadInputTokens}:{},...Number.isFinite(t.contextWindowTokens)?{contextWindowTokens:t.contextWindowTokens}:{}}}function P_(t,e){return t?.inputTokens===e?.inputTokens&&t?.outputTokens===e?.outputTokens&&t?.cacheCreationInputTokens===e?.cacheCreationInputTokens&&t?.cacheReadInputTokens===e?.cacheReadInputTokens&&t?.contextWindowTokens===e?.contextWindowTokens}function Ce(...t){let e=[];for(let n of t)if(n?.length)for(let s of n)!s||e.includes(s)||(e.push(s),e.length>Wt&&e.splice(0,e.length-Wt));return e}function ar(t){return t?.length?{acceptedClientMessageIds:Ce(t)}:{}}function $(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,model:t.model,acceptedClientMessageIds:Ce(t.acceptedClientMessageIds),interruptedClientMessageIds:Ce(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,lastUsage:t.lastUsage,managed:t.managed,isResponding:t.isResponding||void 0,interruptReason:t.interruptReason,stallWarning:t.stallWarning,pendingQueue:t.pendingQueue.length>0?Ut(t.pendingQueue):void 0}}function rf(t){t.managed||(t.managed=!0)}function of(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Ms(e)}function af(t,e,n){return{sessionId:t,agent:e,...n}}function M_(t){return t.startsWith(Ni)}function lf(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 lr=class{constructor(e=sr,n=ed){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=fd(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.updateGauges(),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new er;idleSweepInterval=null;watchdogNowMs=Date.now();lastWatchdogWallClockMs=this.watchdogNowMs;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),w_),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=this.advanceWatchdogClock(Date.now(),"sweep"),n=S.idleTimeoutMs,s=S.turnStallTimeoutMs,r=S.turnStallHardTimeoutMs;if(n<=0&&s<=0)return;let i=3600*1e3;for(let[o,a]of this.sessions){if(!a.active&&!a.driver){if(a.clients.size===0){let u=e-a.lastActivityTs;u>=i&&(w.info({sessionId:a.sessionId,inactiveMs:u},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(a),this.sessions.delete(o))}continue}if(!a.active||!a.driver)continue;let l=e-a.lastActivityTs;if(a.isResponding){if(s<=0||a.pendingApproval||l<s)continue;let u=this.getRespondingLivenessHint(a),c=r>0&&l>=r,d=u==="dead";if(!d&&!c){if(!a.stallWarningAt){let m=x_(l,s,r);a.stallWarningAt=e,a.stallWarning=m,this.updateGauges(),w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"responding session exceeded soft stall threshold; waiting before forced stop"),_.increment("driver.stall_warning",{agent:a.agent}),b.emit("driver.stall_warning",{sessionId:a.sessionId,agent:a.agent,idleMs:l,hardTimeoutMs:r||void 0}),this.broadcast(a.sessionId,{type:"session.stall_warning",sessionId:a.sessionId,warning:m}),this.store.upsert($(a)),this.noteInventoryChanged("session_updated")}continue}let f=d||r<=0?s:r;w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:a.agent}),b.emit("driver.stall_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l});let h=k_(l,s,f,a.lastUserMessage);a.interruptReason=h,this.clearStallWarning(a),this.resolvePendingClaudeHookApprovals(a),a.driver.stop(),a.active=!1,a.driver=null,a.isResponding=!1,a.currentReplyText="",delete a.currentTurn,this.updateGauges(),this.broadcast(a.sessionId,{type:"session.interrupted_notice",sessionId:a.sessionId,reason:h});let g=this.buildPushBody(`${a.title||a.sessionId}: ${h.lastPrompt??""}`.trim());this.pushSender(m=>({title:T_[nf(m)],body:g}),{sessionId:a.sessionId,agent:a.agent,eventType:"agent_stalled"}),this.touchSession(a.sessionId),this.store.upsert($(a)),this.noteInventoryChanged("session_updated");continue}a.pendingApproval||n<=0||l<n||(w.info({sessionId:a.sessionId,agent:a.agent,idleMs:l,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:a.agent}),b.emit("driver.idle_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l}),a.driver.stop(),a.active=!1,a.driver=null,this.updateGauges(),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,s,r){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){w.info({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(w.debug({agent:n,context:s,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,r),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,delete e.currentTurn,o.type==="session.done"&&(n==="claude"?(e.lastUsage=sf(o.usage),this.reconcileClaudeSessionUsage(e,o.usage)):o.usage&&(e.lastUsage=E_(e.lastUsage,o.usage))),o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!of(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}w.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({title:b_,body: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"&&Ms(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:w.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry"));let a=this.clearStallWarning(e);this.touchSession(e.sessionId,o.type!=="text.delta"||a),(a||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"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.pendingQueue.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"driver exited"),b.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;_.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&of(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.clearStallWarning(e),l||(e.pendingApproval=void 0),a){let u=R_(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u});let c=this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim());this.pushSender(d=>({title:C_[nf(d)],body:c}),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert($(e)),this.noteInventoryChanged("session_updated")})}async reconcileClaudeSessionUsage(e,n){let s=await Nd(e.sessionId,e.cwd),r=sf(s??n);!r||P_(e.lastUsage,r)||(e.lastUsage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"))}remapSessionId(e,n,s){if(!n||n===e.sessionId)return;let r=this.sessions.get(n);if(r&&r!==e){w.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;w.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert($(e)),this.noteInventoryChanged("session_remapped"),s&&this.reply(s,`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 s=e.pendingQueue.shift();return s?(s.clientMessageId&&this.rememberAcceptedClientMessage(e,s.clientMessageId),s.model!==void 0&&(e.model=s.model||void 0),e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=s.content,e.currentTurn=wo(s.content,s.images,s.model),e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),this.store.upsert($(e)),this.broadcastPendingQueue(e),e.driver.sendPrompt(s.prompt,e.model),!0):!1}broadcastPendingQueue(e){this.broadcast(e.sessionId,{type:"session.queue",sessionId:e.sessionId,pending:Ut(e.pendingQueue)})}cancelQueuedTurn(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){this.reply(e,n,!1,void 0,"Session not found");return}if(!r){this.reply(e,n,!1,void 0,"clientMessageId required");return}let a=o.pendingQueue.length;o.pendingQueue=o.pendingQueue.filter(u=>u.clientMessageId!==r);let l=a-o.pendingQueue.length;l>0&&(b.emit("session.queue.cancel",{sessionId:s,agent:o.agent,clientMessageId:r,removed:l}),this.store.upsert($(o)),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.broadcastPendingQueue(o)),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s,removed:l}))}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&Od(e.sessionId,e.agent,e.cwd,n).then(s=>{for(let r of s)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:r})}).catch(s=>{w.warn({sessionId:e.sessionId,error:String(s)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let s=e.driver,r=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await s.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(r)!==e||e.startupToken!==i||e.driver!==s){w.info({pendingSessionId:r,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,w.info({pendingSessionId:r,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==r&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(r)!==e||e.startupToken!==i){w.info({pendingSessionId:r,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1;let u=e.pendingQueue.length>0;e.pendingQueue=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),u&&this.broadcastPendingQueue(e),w.error({sessionId:r,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,s,r){if(e==="codex"&&n instanceof An&&r&&n.setModel(r),e!=="claude"||!(n instanceof In))return;let i=s??(0,Io.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=bn){for(let s of e.pendingClaudeHookApprovals.values())s.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&M_(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 s=this.resolveClaudeHookSession(e);return s?(this.touchSession(s.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let s=this.resolveClaudeHookSession(e);if(!s||s.agent!=="claude"||!s.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),bn;if(s.approvalMode==="autoApprove")return lf(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return bn;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:"",u=`${Ni}${l.trim()||(0,Io.randomUUID)()}`,c=s.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return s.pendingClaudeHookApprovals.set(u,{requestId:u,promise:h,resolve:g=>{s.pendingClaudeHookApprovals.delete(u),f(g)}}),s.pendingApproval={requestId:u,toolName:i,input:a,description:d},b.emit("approval.request",{agent:"claude",sessionId:s.sessionId,toolName:i}),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"approval.request",sessionId:s.sessionId,requestId:u,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,s){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let r=new Date().toISOString(),i=s?.agent,o=s?.cwd??"",a=s?.approvalMode,l=s?.model,u=s?.pendingApproval,c=s?.title??"",d=s?.createdAt??r,f=s?.lastActivityAt??r,h=s?.lastUsage,g=Ce(s?.acceptedClientMessageIds),m=Ce(s?.interruptedClientMessageIds),p=s?.isResponding,y=s?.interruptReason,C=s?.stallWarning,A=s?[...s.pendingQueue]:[],T=s?"memory":"client",I=this.store.find(e);if(I)i=I.agent,o=I.cwd||o,a=I.approvalMode??a,l=I.model??l,u=I.pendingApproval??u,c=I.title||c,d=I.createdAt||d,f=I.lastActivityAt||f,h=I.lastUsage??h,g=Ce(I.acceptedClientMessageIds,g),m=Ce(I.interruptedClientMessageIds,m),y=y??I.interruptReason,C=C??I.stallWarning,s||(A=Zd(I.pendingQueue)),T="record";else if(!s){let R=(await Mn(n??i)).find(X=>X.sessionId===e);R&&(i=R.agent,o=R.cwd||o,c=R.title??c,d=R.createdAt,f=R.lastActivityAt,h=R.lastUsage??h,p=R.runtime.isResponding??p,T="scanner")}if(!i&&n&&(i=n,T=s?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,model:l,pendingApproval:u,title:c,createdAt:d,lastActivityAt:f,lastUsage:h,acceptedClientMessageIds:g,interruptedClientMessageIds:m,source:T,managed:s?.managed??I?.managed,isResponding:p||void 0,...y?{interruptReason:y}:{},...C?{stallWarning:C}:{},pendingQueue:A}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let s of this.sessions.values()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(af(s.sessionId,s.agent,s.pendingApproval)))}for(let s of this.store.getAll()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(af(s.sessionId,s.agent,s.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),s=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="",delete e.currentTurn,e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=s??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert($(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<=Kd?n:`${n.slice(0,Math.max(1,Kd-3)).trimEnd()}...`:__}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}currentWatchdogTime(){return this.advanceWatchdogClock(Date.now(),"activity")}getRespondingLivenessHint(e){return e.driver?.getRespondingLivenessHint?.()??"unknown"}clearStallWarning(e){return!e.stallWarning&&!e.stallWarningAt?!1:(e.stallWarning=void 0,e.stallWarningAt=void 0,this.updateGauges(),!0)}advanceWatchdogClock(e,n){let s=Math.max(0,e-this.lastWatchdogWallClockMs);return this.lastWatchdogWallClockMs=e,s<=0?this.watchdogNowMs:s>Xd?(n==="sweep"&&w.warn({elapsedWallMs:s,toleratedGapMs:Xd},"watchdog gap detected; discounting paused wall-clock time"),this.watchdogNowMs):(this.watchdogNowMs+=s,this.watchdogNowMs)}touchSession(e,n=!0){let s=Date.now(),r=new Date(s).toISOString(),i=this.advanceWatchdogClock(s,"activity"),o=this.sessions.get(e);if(o){o.lastActivityAt=r,o.lastActivityTs=i,n&&this.store.upsert($(o));return}let a=this.store.find(e);a&&this.store.upsert({...a,lastActivityAt:r})}updateGauges(){let e=0,n=0;for(let s of this.sessions.values())s.active&&e++,s.stallWarning&&n++;_.gauge("session.active",e),_.gauge("session.stall_warning_active",n)}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,model:n.model,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,lastUsage:n.lastUsage,...n.pendingApproval||n.stallWarning?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{},...n.stallWarning?{stallWarning:n.stallWarning}:{}});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}resolveSessionRef(e){let n=this.store.resolveSessionId(e);return{requestedSessionId:e,resolvedSessionId:n,remapped:n!==e}}buildResolvedSessionResponseData(e,n){let s=n?{...n}:{};return e.remapped&&(s.sessionId=e.resolvedSessionId,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s:void 0}buildSessionResponseData(e,n,s){let r=s?{...s}:{};return n&&n!==e.requestedSessionId&&(r.sessionId=n,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}canResumeDriverSession(e,n){return!(e==="codex"&&n.startsWith("pending_"))}rememberSessionAlias(e,n){!e||!n||e===n||(this.store.forget(e),this.store.addAlias(e,n),this.noteInventoryChanged("session_remapped"))}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return Mn(e,n)}async handle(e,n){switch(w.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.queue.cancel":this.cancelQueuedTurn(e,n.id,n.sessionId,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.clearInterrupt":this.clearInterrupt(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,n.customTitles,n.sinceMs);break;case"sessions.list":{let s=typeof n.skipGitMetadata=="boolean"?n.skipGitMetadata:void 0;await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles,n.sinceMs,s);break}case"sessions.archiveableManaged":this.listArchiveableManagedSessions(e,n.id);break;case"session.setArchived":this.setSessionArchived(e,n.id,n.sessionId,n.archived);break;case"sessions.archiveSync":this.archiveSync(e,n.id,n.mode,n.archivedSessionIds);break;case"usage.limits.fetch":await this.handleUsageLimitsFetch(e,n.id,n.agent,n.force);break}}async handleUsageLimitsFetch(e,n,s,r){let i=await Jd(s,{force:!!r});this.reply(e,n,!0,i)}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){w.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(){zs({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).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},s=JSON.stringify(n);for(let r of this.globalClients)r.readyState===1&&r.send(s)}async createSession(e,n,s,r,i,o,a){r=Wd(r),w.info({agent:s,cwd:r,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,cf.stat)(r)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${r}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${r}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(s,r)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return w.info({sessionId:u.sessionId,cwd:r},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,s,r,i);w.info("continue mode: no previous sessions found, creating new")}catch(l){w.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(s),u=this.configureDriverBeforeStart(s,l,void 0,a);if(s==="codex"){let g=`pending_${Date.now()}`;w.info({sessionId:g,agent:s,cwd:r},"session created (pending codex startup)"),_.increment("session.create",{agent:s}),b.emit("session.create",{sessionId:g,agent:s,cwd:r,approvalMode:i});let m={sessionId:g,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,pendingQueue:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(g,m),this.registerClaudeHookSession(m),this.store.upsert($(m)),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(m,s,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(m,e);return}let c=_.startTimer("driver.spawn"),d=await l.start(r,void 0,i),f=c();w.info({sessionId:d,agent:s,spawnMs:f},"session created"),_.increment("session.create",{agent:s}),b.emit("session.create",{sessionId:d,agent:s,cwd:r,approvalMode:i});let h={sessionId:d,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert($(h)),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,s,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){w.error({agent:s,cwd:r,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,s,r,i,o){let a=this.resolveSessionRef(s);if(s=a.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(s);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let h=await Ln(s,r,l.cwd),g=this.annotateHistoryMessages(h,l.acceptedClientMessageIds,l.interruptedClientMessageIds),m=this.currentPartialReplyText(l),p=l.pendingQueue.length>0?Ut(l.pendingQueue):void 0;if(h.length>0||m||l.approvalMode||l.pendingApproval||l.stallWarning||p){let y={type:"session.history",sessionId:s,messages:g,...ar(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:m,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval,stallWarning:l.stallWarning,...p?{pendingQueue:p}:{}};e.readyState===1&&e.send(JSON.stringify(y))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:s}));return}let u=this.store.find(s),c=i||u?.cwd||"",d=o??u?.approvalMode,f=u?.title??"Resumed session";try{let h=_.startTimer("driver.spawn"),g=this.createDriver(r),m=this.configureDriverBeforeStart(r,g),p=this.canResumeDriverSession(r,s),y=await g.start(c,p?s:void 0,d),C=h();w.info({sessionId:y,agent:r,spawnMs:C},"session resumed"),_.increment("session.resume",{agent:r}),b.emit("session.resume",{sessionId:y,agent:r,cwd:c});let A={sessionId:y,agent:r,cwd:c,approvalMode:d,model:u?.model,driver:g,clients:new Set([e]),title:f,createdAt:u?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),lastUsage:u?.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:u?.acceptedClientMessageIds??[],interruptedClientMessageIds:u?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:Zd(u?.pendingQueue),startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,stallWarning:u?.stallWarning,claudeHookSecret:m,pendingClaudeHookApprovals:new Map};this.sessions.set(y,A),this.rememberSessionAlias(s,y),this.registerClaudeHookSession(A),this.store.upsert($(A)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(A,r," (resumed)",e),this.restoreDriverPendingApproval(g,A.pendingApproval);let I=await Ln(p?s:y,r,c),D=this.annotateHistoryMessages(I,A.acceptedClientMessageIds,A.interruptedClientMessageIds),R=A.pendingQueue.length>0?Ut(A.pendingQueue):void 0;if(I.length>0||A.pendingApproval||A.stallWarning||R){w.info({sessionId:s,historyCount:I.length},"sending history messages");let X={type:"session.history",sessionId:y,messages:D,...ar(A.acceptedClientMessageIds),approvalMode:d,pendingApproval:A.pendingApproval,stallWarning:A.stallWarning,...R?{pendingQueue:R}:{}};e.readyState===1&&e.send(JSON.stringify(X))}this.reply(e,n,!0,this.buildSessionResponseData(a,y,{sessionId:y}))}catch(h){this.reply(e,n,!1,void 0,String(h))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Wt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Wt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Wt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Wt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,s){if(!e.length||!n?.length||!s?.length)return e;let r=new Set(s),i=[];for(let c=0;c<e.length;c+=1)e[c]?.role==="user"&&i.push(c);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,u=i.length-o;for(let c=0;c<o;c+=1){let d=n[l+c];r.has(d)&&a.set(i[u+c],"interrupted")}return a.size===0?e:e.map((c,d)=>c.role==="user"&&a.has(d)?{...c,delivery:"interrupted"}:c)}hasDuplicateInFlightTurn(e,n){return(e.isResponding||e.pendingApproval)&&ef(e.currentTurn,n)?!0:e.pendingQueue.some(s=>ef(s,n))}async sendMessage(e,n,s,r,i,o,a,l){let u=this.resolveSessionRef(s);if(s=u.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(s);if(!c||!c.driver){let p=await this.resolveReconnectSession(s,i,c);if(!p){w.warn({sessionId:s},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:p.agent,source:p.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:p.agent,source:p.source}),b.emit("session.reconnect",{sessionId:s,agent:p.agent,source:p.source});try{let y=this.createDriver(p.agent),C=this.configureDriverBeforeStart(p.agent,y,c?.claudeHookSecret),A=this.canResumeDriverSession(p.agent,s),T=await y.start(p.cwd,A?s:void 0,p.approvalMode);this.restoreDriverPendingApproval(y,p.pendingApproval),c?(c.approvalMode=p.approvalMode,c.model=p.model,c.pendingApproval=p.pendingApproval,c.driver=y,c.active=!0,c.clients.add(e),c.lastActivityAt=p.lastActivityAt,c.lastUsage=p.lastUsage,c.lastActivityTs=this.currentWatchdogTime(),c.isResponding=!1,c.currentReplyText="",delete c.currentTurn,c.acceptedClientMessageIds=Ce(c.acceptedClientMessageIds,p.acceptedClientMessageIds),c.interruptedClientMessageIds=Ce(c.interruptedClientMessageIds,p.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,(!c.pendingQueue||c.pendingQueue.length===0)&&(c.pendingQueue=p.pendingQueue),c.startupToken=c.startupToken??0,c.claudeHookSecret=C??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,T&&T!==c.sessionId&&this.remapSessionId(c,T)):(c={sessionId:T,agent:p.agent,cwd:p.cwd,approvalMode:p.approvalMode,model:p.model,driver:y,clients:new Set([e]),title:p.title,createdAt:p.createdAt,lastActivityAt:p.lastActivityAt,lastUsage:p.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:p.acceptedClientMessageIds,interruptedClientMessageIds:p.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:p.pendingQueue,startupToken:0,managed:p.managed,pendingApproval:p.pendingApproval,claudeHookSecret:C,pendingClaudeHookApprovals:new Map,interruptReason:p.interruptReason},this.sessions.set(T,c),this.rememberSessionAlias(s,T)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,p.agent," (reconnected)"),this.store.upsert($(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),s=c.sessionId,c.pendingQueue.length>0&&this.flushBufferedPrompt(c)}catch(y){this.reply(e,n,!1,void 0,`Failed to reconnect: ${y}`);return}}if(c.clients.add(e),o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,clientMessageId:o,duplicate:!0}));return}let d=uf(r,a),f=l!==void 0&&l||void 0,h=wo(r,a,f);if(this.hasDuplicateInFlightTurn(c,h)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,...o?{clientMessageId:o}:{},duplicate:!0})),w.debug({sessionId:s,hasClientMessageId:!!o,imageCount:a?.length??0},"duplicate in-flight session.send suppressed");return}w.info({sessionId:s,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),b.emit("session.send",{sessionId:s,agent:c.agent,messagePreview:r.slice(0,100),imageCount:a?.length??0}),rf(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert($(c)),this.noteInventoryChanged("session_updated"));let g=this.clearStallWarning(c);if(Mt(c.title)){let p=Gi(r,50);p&&p!==c.title&&(c.title=p),this.store.upsert($(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId),g&&this.noteInventoryChanged("session_updated");let m=p=>{let y={...o?{clientMessageId:o}:{},content:h.content,...h.images?.length?{images:h.images}:{},...f!==void 0?{model:f}:{},prompt:d,enqueuedAt:new Date().toISOString()};c.pendingQueue.push(y),this.store.upsert($(c)),this.broadcastPendingQueue(c);let C=o?{sessionId:s,clientMessageId:o,queued:!0}:{sessionId:s,queued:!0};this.reply(e,n,!0,this.buildSessionResponseData(u,s,C)),w.debug({sessionId:s,reason:p,queueLength:c.pendingQueue.length},"message enqueued on daemon")};if(l!==void 0&&(c.model=l||void 0),c.pendingApproval){m("pending_approval");return}if(c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,this.noteInventoryChanged("session_updated"),m("startup");return}if(c.isResponding||c.pendingQueue.length>0){m("busy"),c.isResponding||this.flushBufferedPrompt(c);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,c.currentTurn=h,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,s,o?{sessionId:s,clientMessageId:o}:{sessionId:s}))}async sendReconnectSnapshot(e,n,s,r,i,o,a,l,u){try{let c=this.getDeletedSessionIds(),d;try{d=await zs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(g){w.warn({error:String(g)},"failed to build reconnect snapshot session list"),d={sessions:[],nextCursor:void 0}}d={...d,sessions:this.decorateSessionsWithArchived(d.sessions),inventoryVersion:this.inventoryVersion};let f;if(o&&!c.has(o)){let g=o;o=this.resolveSessionRef(o).resolvedSessionId;let m=a??d.sessions.find(C=>C.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let y=await this.resolveReconnectSession(o,m,p);if(y){let C=await Ln(o,y.agent,p?.cwd??y.cwd),A=this.annotateHistoryMessages(C,p?.acceptedClientMessageIds??y.acceptedClientMessageIds,p?.interruptedClientMessageIds??y.interruptedClientMessageIds),T=p?{}:await mo(o,y.agent,y.cwd),I=!p&&!!T.isResponding,D=I?await this.externalProcessPresenceCheck(o):!1,R=I&&!D?{}:T,X=p?.interruptReason??y.interruptReason,ut=p?.stallWarning??y.stallWarning,Gn=p?.pendingQueue??y.pendingQueue;f={sessionId:o,agent:y.agent,messages:A,...ar(p?.acceptedClientMessageIds??y.acceptedClientMessageIds),isResponding:p?.isResponding??R.isResponding??(I&&!D?void 0:y.isResponding),...D?{externallyResponding:!0}:{},partialReplyText:p?this.currentPartialReplyText(p):R.partialReplyText,approvalMode:p?.approvalMode??y.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{},...X?{interruptReason:X}:{},...ut?{stallWarning:ut}:{},...Gn.length>0?{pendingQueue:Ut(Gn)}:{}},g!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:g})}}let h=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:f?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:d.sessions,nextCursor:d.nextCursor,inventoryVersion:d.inventoryVersion,...f?{activeSession:f}:{},...h.length>0?{pendingApprovals:h}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,s,r,i){let o=this.resolveSessionRef(s);s=o.resolvedSessionId;let a=this.sessions.get(s),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(r);if(a&&u){a.pendingApproval=void 0,b.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(lf(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}));return}let c=a?.syntheticApprovalRetries[r];if(a&&c&&Ms(r)){delete a.syntheticApprovalRetries[r],a.pendingApproval=void 0,b.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s})),i&&await this.retrySyntheticClaudeApproval(a,c);return}if(a&&!a.driver&&l)try{await this.reviveSessionForApproval(a)}catch(f){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(f)}`);return}if(!a?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(b.emit("approval.response",{sessionId:s,requestId:r,approved:i}),!a.driver.respondApproval(r,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}a.pendingApproval=void 0,this.touchSession(a.sessionId),a.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let s=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",r=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,r,e.claudeHookSecret);await r.start(e.cwd,e.sessionId,s),e.driver=r,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.currentTurn=wo(n.message),e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],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($(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:s},"retrying Claude turn after synthetic approval"),r.sendPrompt(n.message,e.model)}catch(s){e.driver=null,e.active=!1,e.isResponding=!1,delete e.currentTurn,e.startupInProgress=!1;let r=e.pendingQueue.length>0;e.pendingQueue=[],e.startupToken+=1,r&&this.broadcastPendingQueue(e),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:e.sessionId,error:String(s)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(s)}`})}}async setApprovalMode(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){let l=this.store.find(s);l?(r===null?delete l.approvalMode:l.approvalMode=r,this.store.upsert(l),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:l.agent,newMode:r},"approval mode changed (inactive session)")):w.info({sessionId:s,newMode:r},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}));return}if(r===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=r,this.store.upsert($(o)),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:o.agent,oldMode:a,newMode:r},"approval mode changed"),o.driver&&o.driver.setApprovalMode(r),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}))}interrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(b.emit("session.interrupt",{sessionId:s,agent:i.agent}),!i.driver){if(i.isResponding||i.pendingQueue.length>0){w.info({sessionId:s,agent:i.agent},"interrupting driverless session with stale responding state");let o=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),o&&this.broadcastPendingQueue(i),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})}this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}if(i.startupInProgress){let o=i.isResponding||i.pendingQueue.length>0;w.info({sessionId:s,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session");let a=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),a&&this.broadcastPendingQueue(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}clearInterrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s),o=this.store.find(s);if(!i&&!o?.interruptReason){this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}let a=!1;i?.interruptReason&&(i.interruptReason=void 0,a=!0),i?this.store.upsert($(i)):o?.interruptReason&&(this.store.upsert({...o,interruptReason:void 0}),a=!0),a&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}stopSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:i.agent},"stopping session"),b.emit("session.stop",{sessionId:s,agent:i.agent}),rf(i);let o=i.isResponding||i.pendingQueue.length>0||i.startupInProgress,a=i.pendingQueue.length>0;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",delete i.currentTurn,i.pendingApproval=void 0,i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),a&&this.broadcastPendingQueue(i),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}deleteSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);i&&(w.info({sessionId:s,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(s)),b.emit("session.delete",{sessionId:s}),this.store.remove(s),this.updateGauges(),Ks(),Hs(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}async sendHistory(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}o&&o.clients.add(e);let l=a?.cwd??o?.cwd??this.store.find(s)?.cwd??"",u=this.store.find(s),c=await Ln(s,r,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),f=a||o?{}:await mo(s,r,l),h=!a&&!!f.isResponding,g=h?await this.externalProcessPresenceCheck(s):!1,m=g?!0:void 0,p=h&&!g?{}:f,y=a?.isResponding??p.isResponding,C=a?this.currentPartialReplyText(a):p.partialReplyText;w.info({sessionId:s,historyCount:c.length,isResponding:y,externallyResponding:m,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let A=o&&o.pendingQueue.length>0?Ut(o.pendingQueue):u?.pendingQueue&&u.pendingQueue.length>0?u.pendingQueue:void 0,T={type:"session.history",sessionId:s,messages:d,...ar(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:m,partialReplyText:C,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval,stallWarning:o?.stallWarning??u?.stallWarning,...A?{pendingQueue:A}:{}};e.readyState===1&&e.send(JSON.stringify(T));let I=o?.interruptReason??u?.interruptReason;if(I&&e.readyState===1){let D={type:"session.interrupted_notice",sessionId:s,reason:I};e.send(JSON.stringify(D))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s}))}async listSessions(e,n,s,r,i,o=50,a,l,u,c){try{let d=await zs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:c}),f=this.decorateSessionsWithArchived(d.sessions);this.reply(e,n,!0,{...d,sessions:f,inventoryVersion:this.inventoryVersion})}catch(d){this.reply(e,n,!1,void 0,String(d))}}setSessionArchived(e,n,s,r){if(typeof s!="string"||s.length===0){this.reply(e,n,!1,void 0,"sessionId is required");return}this.store.setArchived(s,r===!0)&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,{archived:this.store.isArchived(s)})}archiveSync(e,n,s,r){let i,o=!1;switch(s){case"pushReplace":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.replaceArchivedSessionIds(l),o=u.size!==i.length||i.some(c=>!u.has(c));break}case"pushMerge":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.mergeArchivedSessionIds(l),o=i.some(c=>!u.has(c));break}case"pull":{i=this.store.getArchivedSessionIds();break}default:this.reply(e,n,!1,void 0,`unknown archive sync mode: ${String(s)}`);return}o&&this.noteInventoryChanged("session_updated");let a={archivedSessionIds:i};this.reply(e,n,!0,a)}decorateSessionsWithArchived(e){return e.length===0?e:e.map(n=>({...n,archived:this.store.isArchived(n.sessionId)}))}listArchiveableManagedSessions(e,n){let s=this.getDeletedSessionIds(),r=new Set;for(let o of this.sessions.values())o.managed&&(o.sessionId.startsWith("pending_")||s.has(o.sessionId)||r.add(o.sessionId));for(let o of this.store.getAll())o.managed&&(s.has(o.sessionId)||r.add(o.sessionId));let i={count:r.size,ids:[...r]};this.reply(e,n,!0,i)}createDriver(e){if(S.reviewMock)return new Ls;switch(e){case"claude":return new In;case"codex":return new An;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let s=this.sessions.get(e);if(!s){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let r=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:s.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(r),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){s.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=s.title||e,c=this.buildPushBody(s.currentReplyText);s.currentReplyText="",this.pushSender({title:u,body:c},{sessionId:e,agent:s.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(s.currentReplyText="")}reply(e,n,s,r,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:s,data:r,error:i};e.send(JSON.stringify(o))}};function Ao(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,t.locale):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var ff=require("child_process");function L_(t,e){return(0,ff.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function N_(t){let e=t.split(`
113
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function pf(t,e=L_){let n;try{n=N_(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(s=>{try{let r=e("ps",["-p",String(s),"-o","command="]);return r?{pid:s,command:r}:{pid:s}}catch{return{pid:s}}})}var Gt=require("fs"),To=require("os"),gf=require("crypto"),mf=require("path");function yf(t){return(0,gf.randomBytes)(t).toString("base64url")}function O_(){return`d_${yf(12)}`}function D_(){return(0,To.hostname)()}function B_(){let t=(0,To.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function F_(t){return{daemonId:O_(),daemonSecret:yf(32),displayName:D_(),canonicalHost:B_(),port:t,createdAt:new Date().toISOString()}}function hf(t,e){(0,Gt.mkdirSync)((0,mf.dirname)(e),{recursive:!0}),(0,Gt.writeFileSync)(e,JSON.stringify(t,null,2)+`
114
+ `,"utf8")}function vf(t,e=Jc){try{let s=(0,Gt.readFileSync)(e,"utf8"),r=JSON.parse(s);if(typeof r.daemonId=="string"&&typeof r.daemonSecret=="string"&&typeof r.displayName=="string"&&typeof r.canonicalHost=="string"&&typeof r.createdAt=="string"){let i={daemonId:r.daemonId,daemonSecret:r.daemonSecret,displayName:r.displayName,canonicalHost:r.canonicalHost,port:typeof r.port=="number"&&Number.isFinite(r.port)?r.port:t,createdAt:r.createdAt};return i.port!==t&&(i.port=t,hf(i,e)),i}}catch{}let n=F_(t);return hf(n,e),n}var jt=require("crypto"),$t=require("fs"),_f=require("path");function Co(t){return(0,jt.randomBytes)(t).toString("base64url")}function ko(t){return(0,jt.createHash)("sha256").update(t).digest("hex")}function Sf(t,e){let n=Buffer.from(t),s=Buffer.from(e);return n.length!==s.length?!1:(0,jt.timingSafeEqual)(n,s)}function H_(t){try{let e=(0,$t.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(s=>s&&typeof s.deviceId=="string"&&typeof s.deviceName=="string"&&typeof s.tokenHash=="string"&&typeof s.createdAt=="string"&&typeof s.lastSeenAt=="string"&&(typeof s.revokedAt=="string"||s.revokedAt===null)):[]}catch{return[]}}function Hn(t,e){(0,$t.mkdirSync)((0,_f.dirname)(t),{recursive:!0}),(0,$t.writeFileSync)(t,JSON.stringify(e,null,2)+`
115
+ `,"utf8")}var cr=class{constructor(e=Kc){this.pairingsPath=e;this.records=H_(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 s=`pair_${Co(8)}`,r=Co(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:s,pairNonce:r,expiresAt:i,reusable:n};return this.windows.set(r,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 s=new Date().toISOString(),r=Co(32),i={deviceId:e,deviceName:n,tokenHash:ko(r),createdAt:s,lastSeenAt:s,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Hn(this.pairingsPath,this.records),r}validatePairToken(e,n,s=!0){let r=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!r)return!1;let i=ko(n);return Sf(r.tokenHash,i)?(s&&(r.lastSeenAt=new Date().toISOString(),Hn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let s=ko(e),r=this.records.find(i=>!i.revokedAt&&Sf(i.tokenHash,s));return r?(n&&(r.lastSeenAt=new Date().toISOString(),Hn(this.pairingsPath,this.records)),r):null}revoke(e){let n=this.records.find(s=>s.deviceId===e&&!s.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Hn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Hn(this.pairingsPath,this.records)}};function ur(t){return Array.isArray(t)?t[0]:t}function bf(t){let e=ur(t.headers["x-forwarded-for"]),n=ur(t.headers["cf-connecting-ip"]),s=ur(t.headers["x-real-ip"]),r=e?.split(",")[0]?.trim()||n||s||t.socket.remoteAddress||void 0,i=ur(t.headers["user-agent"]);return{...r?{ip:r}:{},...i?{userAgent:i}:{}}}function U_(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}var W_=["x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","forwarded","via","cf-connecting-ip","cf-ray"];function q_(t){for(let e of W_)if(t[e]!==void 0)return!0;return!1}function lt(t){return U_(t.socket.remoteAddress)&&!q_(t.headers)}function G_(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function xo(t,e){return G_(t)??e}function dr(t,e){return!!(t&&e&&t===e)}function Ro(t,e,n,s=!0){return t?dr(t,e)?!0:!!n(t,s):!1}var wf=require("fs");var j_=new Set(["ws.connect","ws.auth.success"]);function $_(t){try{let n=(0,wf.readFileSync)(t,"utf8").split(`
116
+ `),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&j_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function If(t,e=20,n=De){let s=$_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var Cf=require("child_process"),kf=require("fs");function fr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Eo(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function z_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function V_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Q_(t){if(!fr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function pr(t){return!!t&&!z_(t)&&!V_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Po(t){return fe(t.replace(/^https?:\/\//,""))??t}function Y_(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>pr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function J_(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function K_(t){let e=Po(t);return Eo(e)||e.endsWith(".ts.net")}function X_(t){let e=Po(t);return Q_(e)||e.endsWith(".local")}function Z_(t){return Po(t).endsWith(".trycloudflare.com")}function Af(t,e){return K_(t)?"tailscale":X_(t)?"local_network":e?"configured_host":"fallback"}function xf(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function eb(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function tb(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=Z_(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function nb(t,e,n){let s=fe(t)||"localhost",r=Y_(e,s);return xf([{kind:"direct",host:s,port:n,source:Af(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:Af(i,!1),stability:"stable"}))])}function Rf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function sb(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&J_(s))for(let i of r)i.internal||i.family!=="IPv4"||pr(i.address)&&(Eo(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Tf(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>Eo(o)&&pr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Ef(t=Cf.execFileSync,e=kf.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Tf(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Tf(s)}catch{return{fallbackHosts:[]}}}function Pf(t){let e=nb(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?tb(t.relayUrl):null,s=xf([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:eb(s),port:r.port,connections:s}}function Mf(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...sb(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>pr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Lf(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 z=L.child({module:"daemon"}),Un=L.child({module:"ws"});function rb(){try{let t=JSON.parse(require("fs").readFileSync(Zc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var q=vf(S.port),te=new lr((t,e)=>sr(t,{daemonId:q.daemonId,canonicalHost:Wn().canonicalHost,...e??{}})),ae=new cr,gr=new Set,We=new WeakMap,Nf=!1,Ff=Date.now(),zt=null,hr=null,ib=1e3;function ob(){let t=Ef();return Mf({canonicalHost:q.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Rf(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Bf.networkInterfaces)()})}function Wn(){let t=Date.now();if(hr&&hr.expiresAt>t)return hr.value;let e=ob(),n=Pf({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:q.port,relayUrl:S.relayUrl});return hr={value:n,expiresAt:t+ib},n}function ab(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,n.secure===!0])),e}async function lb(t){let e=JSON.stringify(ab(t));await(0,le.mkdir)(Ie,{recursive:!0}),await No.default.toFile(Ri,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await No.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});kt(`
117
117
  Scan this QR code with Vibelet app:
118
118
 
119
119
  ${n}
120
120
  `),kt(`If Vibelet app can't scan the terminal QR, open this PNG instead:
121
121
  ${Ri}
122
- `)}async function Po(t){let e=[];for await(let s of t)e.push(Buffer.isBuffer(s)?s:Buffer.from(s));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function H(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function ab(t){let e=(0,Vt.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 Ff(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function lb(t,e){if(lt(t))return!0;let n=ko(t.headers.authorization,e.searchParams.get("token"));return xo(n,S.legacyToken,(s,r)=>ae.validateAnyPairToken(s,r),!1)}function cb(){let t=ae.openWindow(Ff(),S.pairReusable),e=Wn();return{type:"vibelet-pair",daemonId:W.daemonId,displayName:W.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 ub(t,e){let n=yo(t,e),s=await(0,le.readdir)(n),r=[];for(let i of s){if(i.startsWith("."))continue;let o=await(0,le.stat)((0,Vt.join)(n,i)).catch(()=>null);o&&r.push({name:i,isDirectory:o.isDirectory()})}return r.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:r}}var qn=(0,Nf.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let r=Wn(),i=nb(),o={status:"ok",version:Pt,...i?{latestVersion:i}:{}};if(!lb(t,n)){H(e,200,o);return}let a={...o,status:"ok",daemonId:W.daemonId,displayName:W.displayName,canonicalHost:r.canonicalHost,uptimeSeconds:Math.round((Date.now()-Bf)/1e3),activeSessions:te.getActiveSessionCount(),pairedDevices:ae.pairedCount(),wsClients:pe.clients.size,drivers:te.getDriverCounts(),sessionInventory:fd(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),H(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!lt(t)){H(e,403,{error:"forbidden"});return}H(e,200,cb());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!lt(t)){H(e,403,{error:"forbidden"});return}ae.reset(),H(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!lt(t)){H(e,403,{error:"forbidden"});return}H(e,200,{status:"stopping"}),setTimeout(()=>ct("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!lt(t)){H(e,403,{error:"forbidden"});return}try{let r=await Po(t),i=t.headers[_n],o=Array.isArray(i)?i[0]:i;te.handleClaudeSessionStartHook(o,r),H(e,200,{ok:!0})}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!lt(t)){H(e,403,{error:"forbidden"});return}try{let r=await Po(t),i=t.headers[_n],o=Array.isArray(i)?i[0]:i,a=await te.handleClaudePermissionHook(o,r);H(e,200,a)}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let r=await Po(t);if(r.daemonId!==W.daemonId||typeof r.pairNonce!="string"||typeof r.deviceId!="string"||typeof r.deviceName!="string"){H(e,400,{error:"invalid_pair_request"});return}if(!ae.consumeWindow(r.pairNonce)){H(e,401,{error:"pair_window_expired"});return}let o=ae.issuePairToken(r.deviceId,r.deviceName),a=Wn();H(e,200,{daemonId:W.daemonId,displayName:W.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:r.deviceId,pairToken:o})}catch(r){H(e,400,{error:String(r)})}return}let s=ko(t.headers.authorization,n.searchParams.get("token"));if(!xo(s,S.legacyToken,(r,i)=>ae.validateAnyPairToken(r,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let r={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","application/json":".json","application/zip":".zip"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=n.searchParams.get("name")??"",l=(0,Vt.extname)(o).toLowerCase()||r[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let f of t){let h=Buffer.isBuffer(f)?f:Buffer.from(f);if(d+=h.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(h)}try{await(0,le.mkdir)(xi,{recursive:!0});let f=`${Date.now()}_${(0,Of.randomBytes)(8).toString("hex")}${l}`,h=(0,Vt.join)(xi,f);await(0,le.writeFile)(h,Buffer.concat(c)),z.info({filePath:h,size:d,contentType:i,providedName:o||void 0},"file uploaded"),H(e,200,{path:h})}catch(f){z.error({error:String(f)},"upload failed"),H(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let r=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!r){e.writeHead(400),e.end("Missing path parameter");return}try{let o=yo(r,i);if(!(await(0,le.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=ab(o),u=await(0,le.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${Pt}`)}),pe=new Br.default({server:qn});qn.on("connection",t=>{gr.add(t),t.on("close",()=>{gr.delete(t)})});pe.on("connection",(t,e)=>{let s=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token"),r=_f(e);if(s&&dr(s,S.legacyToken))We.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),w.emit("ws.auth.success",{authMode:"query_token",...r}),te.addGlobalClient(t),te.prewarmCaches();else if(s){let i=ae.validateAnyPairToken(s);if(i)We.set(t,{authMode:"query_token",deviceId:i.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),w.emit("ws.auth.success",{authMode:"query_token",deviceId:i.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),w.emit("ws.auth.failure",{authMode:"query_token",...r}),t.close(4001,"Unauthorized");return}}Un.info({clients:pe.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",pe.clients.size),w.emit("ws.connect",{clients:pe.clients.size,authMode:We.get(t)?.authMode??"pending",deviceId:We.get(t)?.deviceId,...r}),t.on("message",async i=>{try{let o=JSON.parse(Mf(i));if(!o||typeof o.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(o.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let a=o;if(!We.has(t)){if(a.action==="auth.hello"){let l=(()=>{if(dr(a.pairToken,S.legacyToken))return{deviceId:a.deviceId};if(a.deviceId&&a.daemonId===W.daemonId&&ae.validatePairToken(a.deviceId,a.pairToken))return{deviceId:a.deviceId};if(!a.daemonId||a.daemonId===W.daemonId){let u=ae.validateAnyPairToken(a.pairToken);if(u)return{deviceId:u.deviceId}}return null})();if(l){We.set(t,{authMode:"auth_hello",deviceId:l.deviceId,...a.locale?{locale:a.locale}:{}}),_.increment("ws.auth.success",{mode:"auth_hello"}),w.emit("ws.auth.success",{authMode:"auth_hello",deviceId:l.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches(),t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{daemonId:W.daemonId,...l.deviceId?{deviceId:l.deviceId}:{},displayName:W.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),w.emit("ws.auth.failure",{authMode:"auth_hello",...r}),t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(a.action==="log.report"){for(let l of a.entries)w.emitApp(l.event,l.level,l.data??{},l.ts),(l.level==="error"?z.error:l.level==="warn"?z.warn:z.info).call(z,{event:l.event,...l.data},`[app] ${l.event}`);t.send(JSON.stringify({type:"response",id:a.id,ok:!0}));return}if(a.action==="dirs.list"){try{let l=await ub(a.path,a.cwd);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:l}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}if(o.action==="push.register"){let l=We.get(t),u=o.locale?o:{...o,locale:l?.locale};Io(u,{deviceId:l?.deviceId,registerToken:vo,unregisterToken:So,respond:c=>t.send(JSON.stringify(c))});return}if(o.action==="push.unregister"){let l=We.get(t);Io(o,{deviceId:l?.deviceId,registerToken:vo,unregisterToken:So,respond:u=>t.send(JSON.stringify(u))});return}if(a.action==="audit.list_devices"){try{let l=wf(ae,a.maxConnectionsPerDevice);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{devices:l}}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}await te.handle(t,a)}catch(o){Un.error({error:String(o)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(o)}))}}),t.on("close",i=>{Un.info({clients:pe.clients.size,code:i},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(i)}),_.gauge("ws.clients",pe.clients.size),w.emit("ws.disconnect",{clients:pe.clients.size,code:i}),te.removeClient(t)}),t.on("error",i=>{Un.error({error:i.message},"websocket error")})});function Mo(){for(let t of gr)try{t.destroy()}catch{}gr.clear()}function Hf(){let t=cu({auditPath:De,stdoutLogPath:_s,stderrLogPath:bs,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&z.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 db(){zt||(zt=setInterval(Hf,S.storageHousekeepingIntervalMs),zt.unref())}function fb(){zt&&(clearInterval(zt),zt=null)}function ct(t,e=0){if(!Lf){Lf=!0,z.info({reason:t,exitCode:e},"shutting down"),w.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Bf)/1e3)}),_.stopPeriodicLog(),fb(),Nt.stop().catch(()=>{}),te.shutdown();for(let n of pe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}pe.close(n=>{n&&z.error({error:String(n)},"websocket close error")}),qn.close(n=>{if(n){z.error({error:String(n)},"http close error"),Mo(),process.exit(1);return}Mo(),process.exit(e)}),setTimeout(()=>{z.error("force exiting after shutdown timeout"),Mo(),process.exit(e||1)},3e3).unref()}}pe.on("error",t=>{Un.error({error:t.message},"wss error")});qn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=ff(S.port).filter(n=>n.pid!==process.pid);z.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or start Vibelet with --port <port> (or VIBE_PORT=<port>)")}else z.error({error:String(t)},"server error");ct(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ct("SIGINT"));process.once("SIGTERM",()=>ct("SIGTERM"));process.once("SIGHUP",()=>ct("SIGHUP"));process.once("SIGTTIN",()=>ct("SIGTTIN"));process.once("SIGTSTP",()=>ct("SIGTSTP"));process.on("uncaughtException",t=>{z.error({error:String(t),stack:t.stack},"uncaughtException"),w.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{z.error({reason:String(t)},"unhandledRejection"),w.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});qn.listen(S.port,async()=>{Hf(),w.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),db(),pd(),Nt.start().catch(s=>{z.warn({error:String(s)},"session activity watcher failed to start")});let t=Wn();z.info({port:S.port,pairingPort:t.port,daemonId:W.daemonId,displayName:W.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,turnStallHardTimeoutMs:S.turnStallHardTimeoutMs},"daemon started");let e=ae.openWindow(Ff(),S.pairReusable),n={type:"vibelet-pair",daemonId:W.daemonId,displayName:W.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};kt(`
122
+ `)}async function Mo(t){let e=[];for await(let s of t)e.push(Buffer.isBuffer(s)?s:Buffer.from(s));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function U(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function cb(t){let e=(0,Vt.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 Hf(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function ub(t,e){if(lt(t))return!0;let n=xo(t.headers.authorization,e.searchParams.get("token"));return Ro(n,S.legacyToken,(s,r)=>ae.validateAnyPairToken(s,r),!1)}function db(){let t=ae.openWindow(Hf(),S.pairReusable),e=Wn();return{type:"vibelet-pair",daemonId:q.daemonId,displayName:q.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 fb(t,e){let n=vo(t,e),s=await(0,le.readdir)(n),r=[];for(let i of s){if(i.startsWith("."))continue;let o=await(0,le.stat)((0,Vt.join)(n,i)).catch(()=>null);o&&r.push({name:i,isDirectory:o.isDirectory()})}return r.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:r}}var qn=(0,Of.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let r=Wn(),i=rb(),o={status:"ok",version:Pt,...i?{latestVersion:i}:{}};if(!ub(t,n)){U(e,200,o);return}let a={...o,status:"ok",daemonId:q.daemonId,displayName:q.displayName,canonicalHost:r.canonicalHost,uptimeSeconds:Math.round((Date.now()-Ff)/1e3),activeSessions:te.getActiveSessionCount(),pairedDevices:ae.pairedCount(),wsClients:pe.clients.size,drivers:te.getDriverCounts(),sessionInventory:pd(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),U(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!lt(t)){U(e,403,{error:"forbidden"});return}U(e,200,db());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!lt(t)){U(e,403,{error:"forbidden"});return}ae.reset(),U(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!lt(t)){U(e,403,{error:"forbidden"});return}U(e,200,{status:"stopping"}),setTimeout(()=>ct("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!lt(t)){U(e,403,{error:"forbidden"});return}try{let r=await Mo(t),i=t.headers[_n],o=Array.isArray(i)?i[0]:i;te.handleClaudeSessionStartHook(o,r),U(e,200,{ok:!0})}catch(r){U(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!lt(t)){U(e,403,{error:"forbidden"});return}try{let r=await Mo(t),i=t.headers[_n],o=Array.isArray(i)?i[0]:i,a=await te.handleClaudePermissionHook(o,r);U(e,200,a)}catch(r){U(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let r=await Mo(t);if(r.daemonId!==q.daemonId||typeof r.pairNonce!="string"||typeof r.deviceId!="string"||typeof r.deviceName!="string"){U(e,400,{error:"invalid_pair_request"});return}if(!ae.consumeWindow(r.pairNonce)){U(e,401,{error:"pair_window_expired"});return}let o=ae.issuePairToken(r.deviceId,r.deviceName),a=Wn();U(e,200,{daemonId:q.daemonId,displayName:q.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:r.deviceId,pairToken:o})}catch(r){U(e,400,{error:String(r)})}return}let s=xo(t.headers.authorization,n.searchParams.get("token"));if(!Ro(s,S.legacyToken,(r,i)=>ae.validateAnyPairToken(r,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let r={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","application/json":".json","application/zip":".zip"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=n.searchParams.get("name")??"",l=(0,Vt.extname)(o).toLowerCase()||r[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let f of t){let h=Buffer.isBuffer(f)?f:Buffer.from(f);if(d+=h.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(h)}try{await(0,le.mkdir)(xi,{recursive:!0});let f=`${Date.now()}_${(0,Df.randomBytes)(8).toString("hex")}${l}`,h=(0,Vt.join)(xi,f);await(0,le.writeFile)(h,Buffer.concat(c)),z.info({filePath:h,size:d,contentType:i,providedName:o||void 0},"file uploaded"),U(e,200,{path:h})}catch(f){z.error({error:String(f)},"upload failed"),U(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let r=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!r){e.writeHead(400),e.end("Missing path parameter");return}try{let o=vo(r,i);if(!(await(0,le.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=cb(o),u=await(0,le.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${Pt}`)}),pe=new Br.default({server:qn});qn.on("connection",t=>{gr.add(t),t.on("close",()=>{gr.delete(t)})});pe.on("connection",(t,e)=>{let s=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token"),r=bf(e);if(s&&dr(s,S.legacyToken))We.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),b.emit("ws.auth.success",{authMode:"query_token",...r}),te.addGlobalClient(t),te.prewarmCaches();else if(s){let i=ae.validateAnyPairToken(s);if(i)We.set(t,{authMode:"query_token",deviceId:i.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),b.emit("ws.auth.success",{authMode:"query_token",deviceId:i.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),b.emit("ws.auth.failure",{authMode:"query_token",...r}),t.close(4001,"Unauthorized");return}}Un.info({clients:pe.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",pe.clients.size),b.emit("ws.connect",{clients:pe.clients.size,authMode:We.get(t)?.authMode??"pending",deviceId:We.get(t)?.deviceId,...r}),t.on("message",async i=>{try{let o=JSON.parse(Lf(i));if(!o||typeof o.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(o.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let a=o;if(!We.has(t)){if(a.action==="auth.hello"){let l=(()=>{if(dr(a.pairToken,S.legacyToken))return{deviceId:a.deviceId};if(a.deviceId&&a.daemonId===q.daemonId&&ae.validatePairToken(a.deviceId,a.pairToken))return{deviceId:a.deviceId};if(!a.daemonId||a.daemonId===q.daemonId){let u=ae.validateAnyPairToken(a.pairToken);if(u)return{deviceId:u.deviceId}}return null})();if(l){We.set(t,{authMode:"auth_hello",deviceId:l.deviceId,...a.locale?{locale:a.locale}:{}}),_.increment("ws.auth.success",{mode:"auth_hello"}),b.emit("ws.auth.success",{authMode:"auth_hello",deviceId:l.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches(),t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{daemonId:q.daemonId,...l.deviceId?{deviceId:l.deviceId}:{},displayName:q.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),b.emit("ws.auth.failure",{authMode:"auth_hello",...r}),t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(a.action==="log.report"){for(let l of a.entries)b.emitApp(l.event,l.level,l.data??{},l.ts),(l.level==="error"?z.error:l.level==="warn"?z.warn:z.info).call(z,{event:l.event,...l.data},`[app] ${l.event}`);t.send(JSON.stringify({type:"response",id:a.id,ok:!0}));return}if(a.action==="dirs.list"){try{let l=await fb(a.path,a.cwd);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:l}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}if(o.action==="push.register"){let l=We.get(t),u=o.locale?o:{...o,locale:l?.locale};Ao(u,{deviceId:l?.deviceId,registerToken:So,unregisterToken:_o,respond:c=>t.send(JSON.stringify(c))});return}if(o.action==="push.unregister"){let l=We.get(t);Ao(o,{deviceId:l?.deviceId,registerToken:So,unregisterToken:_o,respond:u=>t.send(JSON.stringify(u))});return}if(a.action==="audit.list_devices"){try{let l=If(ae,a.maxConnectionsPerDevice);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{devices:l}}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}await te.handle(t,a)}catch(o){Un.error({error:String(o)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(o)}))}}),t.on("close",i=>{Un.info({clients:pe.clients.size,code:i},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(i)}),_.gauge("ws.clients",pe.clients.size),b.emit("ws.disconnect",{clients:pe.clients.size,code:i}),te.removeClient(t)}),t.on("error",i=>{Un.error({error:i.message},"websocket error")})});function Lo(){for(let t of gr)try{t.destroy()}catch{}gr.clear()}function Uf(){let t=uu({auditPath:De,stdoutLogPath:_s,stderrLogPath:bs,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&z.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 pb(){zt||(zt=setInterval(Uf,S.storageHousekeepingIntervalMs),zt.unref())}function hb(){zt&&(clearInterval(zt),zt=null)}function ct(t,e=0){if(!Nf){Nf=!0,z.info({reason:t,exitCode:e},"shutting down"),b.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Ff)/1e3)}),_.stopPeriodicLog(),hb(),Nt.stop().catch(()=>{}),te.shutdown();for(let n of pe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}pe.close(n=>{n&&z.error({error:String(n)},"websocket close error")}),qn.close(n=>{if(n){z.error({error:String(n)},"http close error"),Lo(),process.exit(1);return}Lo(),process.exit(e)}),setTimeout(()=>{z.error("force exiting after shutdown timeout"),Lo(),process.exit(e||1)},3e3).unref()}}pe.on("error",t=>{Un.error({error:t.message},"wss error")});qn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=pf(S.port).filter(n=>n.pid!==process.pid);z.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or start Vibelet with --port <port> (or VIBE_PORT=<port>)")}else z.error({error:String(t)},"server error");ct(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ct("SIGINT"));process.once("SIGTERM",()=>ct("SIGTERM"));process.once("SIGHUP",()=>ct("SIGHUP"));process.once("SIGTTIN",()=>ct("SIGTTIN"));process.once("SIGTSTP",()=>ct("SIGTSTP"));process.on("uncaughtException",t=>{z.error({error:String(t),stack:t.stack},"uncaughtException"),b.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{z.error({reason:String(t)},"unhandledRejection"),b.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});qn.listen(S.port,async()=>{Uf(),b.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),pb(),hd(),Nt.start().catch(s=>{z.warn({error:String(s)},"session activity watcher failed to start")});let t=Wn();z.info({port:S.port,pairingPort:t.port,daemonId:q.daemonId,displayName:q.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,turnStallHardTimeoutMs:S.turnStallHardTimeoutMs},"daemon started");let e=ae.openWindow(Hf(),S.pairReusable),n={type:"vibelet-pair",daemonId:q.daemonId,displayName:q.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};kt(`
123
123
  \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
124
124
  \u2551 Vibelet Daemon v${Pt} \u2551
125
125
  \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
126
126
  \u2551 Port: ${String(n.port).padEnd(28)}\u2551
127
- \u2551 ID: ${W.daemonId.slice(0,28).padEnd(28)}\u2551
127
+ \u2551 ID: ${q.daemonId.slice(0,28).padEnd(28)}\u2551
128
128
  \u2551 Host: ${n.canonicalHost.slice(0,28).padEnd(28)}\u2551
129
129
  \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
130
130
 
@@ -134,4 +134,4 @@ Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
134
134
 
135
135
  Claude: ${S.claudePath}
136
136
  Codex: ${S.codexPath}
137
- `);try{await ob(n)}catch{}});
137
+ `);try{await lb(n)}catch{}});