@vibelet/cli 1.0.9 → 1.0.10

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 Ld=Object.create;var no=Object.defineProperty;var Nd=Object.getOwnPropertyDescriptor;var Od=Object.getOwnPropertyNames;var Bd=Object.getPrototypeOf,Dd=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Hd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Od(e))!Dd.call(t,s)&&s!==n&&no(t,s,{get:()=>e[s],enumerable:!(r=Nd(e,s))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Ld(Bd(t)):{},Hd(e||!t||!t.__esModule?no(n,"default",{value:t,enumerable:!0}):n,t));var ye=y((Jv,io)=>{"use strict";var ro=["nodebuffer","arraybuffer","fragments"],so=typeof Blob<"u";so&&ro.push("blob");io.exports={BINARY_TYPES:ro,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:so,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ht=y((Kv,Pn)=>{"use strict";var{EMPTY_BUFFER:Fd}=ye(),$r=Buffer[Symbol.species];function Ud(t,e){if(t.length===0)return Fd;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new $r(n.buffer,n.byteOffset,r):n}function oo(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function ao(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function qd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Vr(t){if(Vr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new $r(t):ArrayBuffer.isView(t)?e=new $r(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Vr.readOnly=!1),e}Pn.exports={concat:Ud,mask:oo,toArrayBuffer:qd,toBuffer:Vr,unmask:ao};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Pn.exports.mask=function(e,n,r,s,i){i<48?oo(e,n,r,s,i):t.mask(e,n,r,s,i)},Pn.exports.unmask=function(e,n){e.length<32?ao(e,n):t.unmask(e,n)}}catch{}});var uo=y((Qv,co)=>{"use strict";var lo=Symbol("kDone"),zr=Symbol("kRun"),Yr=class{constructor(e){this[lo]=()=>{this.pending--,this[zr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[zr]()}[zr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[lo])}}};co.exports=Yr});var Ut=y((Xv,go)=>{"use strict";var Ft=require("zlib"),fo=Ht(),Wd=uo(),{kStatusCode:po}=ye(),Gd=Buffer[Symbol.species],jd=Buffer.from([0,0,255,255]),Mn=Symbol("permessage-deflate"),ve=Symbol("total-length"),at=Symbol("callback"),Ae=Symbol("buffers"),lt=Symbol("error"),Rn,Jr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Rn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Rn=new Wd(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[at];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Rn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Rn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ft.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Mn]=this,this._inflate[ve]=0,this._inflate[Ae]=[],this._inflate.on("error",Vd),this._inflate.on("data",ho)}this._inflate[at]=r,this._inflate.write(e),n&&this._inflate.write(jd),this._inflate.flush(()=>{let i=this._inflate[lt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=fo.concat(this._inflate[Ae],this._inflate[ve]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ve]=0,this._inflate[Ae]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ft.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ve]=0,this._deflate[Ae]=[],this._deflate.on("data",$d)}this._deflate[at]=r,this._deflate.write(e),this._deflate.flush(Ft.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=fo.concat(this._deflate[Ae],this._deflate[ve]);n&&(i=new Gd(i.buffer,i.byteOffset,i.length-4)),this._deflate[at]=null,this._deflate[ve]=0,this._deflate[Ae]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};go.exports=Jr;function $d(t){this[Ae].push(t),this[ve]+=t.length}function ho(t){if(this[ve]+=t.length,this[Mn]._maxPayload<1||this[ve]<=this[Mn]._maxPayload){this[Ae].push(t);return}this[lt]=new RangeError("Max payload size exceeded"),this[lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lt][po]=1009,this.removeListener("data",ho),this.reset()}function Vd(t){if(this[Mn]._inflate=null,this[lt]){this[at](this[lt]);return}t[po]=1007,this[at](t)}});var ct=y((Zv,Ln)=>{"use strict";var{isUtf8:mo}=require("buffer"),{hasBlob:zd}=ye(),Yd=[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 Jd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Kr(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 Kd(t){return zd&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ln.exports={isBlob:Kd,isValidStatusCode:Jd,isValidUTF8:Kr,tokenChars:Yd};if(mo)Ln.exports.isValidUTF8=function(t){return t.length<24?Kr(t):mo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ln.exports.isValidUTF8=function(e){return e.length<32?Kr(e):t(e)}}catch{}});var ts=y((eS,Io)=>{"use strict";var{Writable:Qd}=require("stream"),yo=Ut(),{BINARY_TYPES:Xd,EMPTY_BUFFER:vo,kStatusCode:Zd,kWebSocket:ef}=ye(),{concat:Qr,toArrayBuffer:tf,unmask:nf}=Ht(),{isValidStatusCode:rf,isValidUTF8:So}=ct(),Nn=Buffer[Symbol.species],X=0,_o=1,bo=2,wo=3,Xr=4,Zr=5,On=6,es=class extends Qd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Xd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ef]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Nn(r.buffer,r.byteOffset+e,r.length-e),new Nn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Nn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case _o:this.getPayloadLength16(e);break;case bo:this.getPayloadLength64(e);break;case wo:this.getMask();break;case Xr:this.getData(e);break;case Zr:case On:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[yo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=_o:this._payloadLength===127?this._state=bo:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=wo:this._state=Xr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xr}getData(e){let n=vo;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&&nf(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Zr,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,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Qr(r,n):this._binaryType==="arraybuffer"?s=tf(Qr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=On,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Qr(r,n);if(!this._skipUTF8Validation&&!So(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Zr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=On,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,vo),this.end();else{let r=e.readUInt16BE(0);if(!rf(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Nn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!So(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=On,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Zd]=s,o}};Io.exports=es});var ss=y((nS,xo)=>{"use strict";var{Duplex:tS}=require("stream"),{randomFillSync:sf}=require("crypto"),Ao=Ut(),{EMPTY_BUFFER:of,kWebSocket:af,NOOP:lf}=ye(),{isBlob:ut,isValidStatusCode:cf}=ct(),{mask:To,toBuffer:He}=Ht(),Z=Symbol("kByteLength"),uf=Buffer.alloc(4),Bn=8*1024,Fe,dt=Bn,se=0,df=1,ff=2,ns=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=se,this.onerror=lf,this[af]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||uf,n.generateMask?n.generateMask(r):(dt===Bn&&(Fe===void 0&&(Fe=Buffer.alloc(Bn)),sf(Fe,0,Bn),dt=0),r[0]=Fe[dt++],r[1]=Fe[dt++],r[2]=Fe[dt++],r[3]=Fe[dt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(To(e,r,c,i,a),[c]):(To(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=of;else{if(typeof e!="number"||!cf(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==se?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ut(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ut(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Ao.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ut(e)?(a=e.size,l=!1):(e=He(e),a=e.length,l=He.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==se?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=ff,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(rs,this,a,s);return}this._bufferedBytes-=r[Z];let o=He(i);n?this.dispatch(o,n,r,s):(this._state=se,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(pf,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Ao.extensionName];this._bufferedBytes+=r[Z],this._state=df,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");rs(this,l,s);return}this._bufferedBytes-=r[Z],this._state=se,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===se&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};xo.exports=ns;function rs(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function pf(t,e,n){rs(t,e,n),t.onerror(e)}});var Oo=y((rS,No)=>{"use strict";var{kForOnEventAttribute:qt,kListener:is}=ye(),Co=Symbol("kCode"),ko=Symbol("kData"),Eo=Symbol("kError"),Po=Symbol("kMessage"),Ro=Symbol("kReason"),ft=Symbol("kTarget"),Mo=Symbol("kType"),Lo=Symbol("kWasClean"),Se=class{constructor(e){this[ft]=null,this[Mo]=e}get target(){return this[ft]}get type(){return this[Mo]}};Object.defineProperty(Se.prototype,"target",{enumerable:!0});Object.defineProperty(Se.prototype,"type",{enumerable:!0});var Ue=class extends Se{constructor(e,n={}){super(e),this[Co]=n.code===void 0?0:n.code,this[Ro]=n.reason===void 0?"":n.reason,this[Lo]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Co]}get reason(){return this[Ro]}get wasClean(){return this[Lo]}};Object.defineProperty(Ue.prototype,"code",{enumerable:!0});Object.defineProperty(Ue.prototype,"reason",{enumerable:!0});Object.defineProperty(Ue.prototype,"wasClean",{enumerable:!0});var pt=class extends Se{constructor(e,n={}){super(e),this[Eo]=n.error===void 0?null:n.error,this[Po]=n.message===void 0?"":n.message}get error(){return this[Eo]}get message(){return this[Po]}};Object.defineProperty(pt.prototype,"error",{enumerable:!0});Object.defineProperty(pt.prototype,"message",{enumerable:!0});var Wt=class extends Se{constructor(e,n={}){super(e),this[ko]=n.data===void 0?null:n.data}get data(){return this[ko]}};Object.defineProperty(Wt.prototype,"data",{enumerable:!0});var hf={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[qt]&&s[is]===e&&!s[qt])return;let r;if(t==="message")r=function(i,o){let a=new Wt("message",{data:o?i:i.toString()});a[ft]=this,Dn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ue("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ft]=this,Dn(e,this,a)};else if(t==="error")r=function(i){let o=new pt("error",{error:i,message:i.message});o[ft]=this,Dn(e,this,o)};else if(t==="open")r=function(){let i=new Se("open");i[ft]=this,Dn(e,this,i)};else return;r[qt]=!!n[qt],r[is]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[is]===e&&!n[qt]){this.removeListener(t,n);break}}};No.exports={CloseEvent:Ue,ErrorEvent:pt,Event:Se,EventTarget:hf,MessageEvent:Wt};function Dn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var os=y((sS,Bo)=>{"use strict";var{tokenChars:Gt}=ct();function fe(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function gf(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Gt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(fe(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Gt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),fe(n,t.slice(l,u),!0),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Gt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Gt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Gt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),fe(n,a,h),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?fe(e,f,n):(a===void 0?fe(n,f,!0):r?fe(n,a,f.replace(/\\/g,"")):fe(n,a,f),fe(e,o,n)),e}function mf(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Bo.exports={format:mf,parse:gf}});var qn=y((aS,Yo)=>{"use strict";var yf=require("events"),vf=require("https"),Sf=require("http"),Fo=require("net"),_f=require("tls"),{randomBytes:bf,createHash:wf}=require("crypto"),{Duplex:iS,Readable:oS}=require("stream"),{URL:as}=require("url"),Te=Ut(),If=ts(),Af=ss(),{isBlob:Tf}=ct(),{BINARY_TYPES:Do,CLOSE_TIMEOUT:xf,EMPTY_BUFFER:Hn,GUID:Cf,kForOnEventAttribute:ls,kListener:kf,kStatusCode:Ef,kWebSocket:F,NOOP:Uo}=ye(),{EventTarget:{addEventListener:Pf,removeEventListener:Rf}}=Oo(),{format:Mf,parse:Lf}=os(),{toBuffer:Nf}=Ht(),qo=Symbol("kAborted"),cs=[8,13],_e=["CONNECTING","OPEN","CLOSING","CLOSED"],Of=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,E=class t extends yf{constructor(e,n,r){super(),this._binaryType=Do[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Hn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Wo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Do.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new If({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Af(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[F]=this,i[F]=this,e[F]=this,s.on("conclude",Hf),s.on("drain",Ff),s.on("error",Uf),s.on("message",qf),s.on("ping",Wf),s.on("pong",Gf),i.onerror=jf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",$o),e.on("data",Un),e.on("end",Vo),e.on("error",zo),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[Te.extensionName]&&this._extensions[Te.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),jo(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){us(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Hn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){us(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Hn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){us(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Te.extensionName]||(s.compress=!1),this._sender.send(e||Hn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(E.prototype,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(E,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(E.prototype,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(E,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(E.prototype,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(E,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});Object.defineProperty(E.prototype,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(E.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(E.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ls])return e[kf];return null},set(e){for(let n of this.listeners(t))if(n[ls]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ls]:!0})}})});E.prototype.addEventListener=Pf;E.prototype.removeEventListener=Rf;Yo.exports=E;function Wo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xf,protocolVersion:cs[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!cs.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${cs.join(", ")})`);let i;if(e instanceof as)i=e;else try{i=new as(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 p=new SyntaxError(l);if(t._redirects===0)throw p;Fn(t,p);return}let c=o?443:80,u=bf(16).toString("base64"),d=o?vf.request:Sf.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?Df:Bf),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new Te(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Mf({[Te.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!Of.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,v]of Object.entries(p))r.headers[m.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[qo]||(g=t._req=null,Fn(t,p))}),g.on("response",p=>{let m=p.headers.location,v=p.statusCode;if(m&&s.followRedirects&&v>=300&&v<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let w;try{w=new as(m,e)}catch{let k=new SyntaxError(`Invalid URL: ${m}`);Fn(t,k);return}Wo(t,w,n,r)}else t.emit("unexpected-response",g,p)||Y(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,m,v)=>{if(t.emit("upgrade",p),t.readyState!==E.CONNECTING)return;g=t._req=null;let w=p.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Y(t,m,"Invalid Upgrade header");return}let K=wf("sha1").update(u+Cf).digest("base64");if(p.headers["sec-websocket-accept"]!==K){Y(t,m,"Invalid Sec-WebSocket-Accept header");return}let k=p.headers["sec-websocket-protocol"],H;if(k!==void 0?f.size?f.has(k)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":f.size&&(H="Server sent no subprotocol"),H){Y(t,m,H);return}k&&(t._protocol=k);let Q=p.headers["sec-websocket-extensions"];if(Q!==void 0){if(!h){Y(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let de;try{de=Lf(Q)}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}let it=Object.keys(de);if(it.length!==1||it[0]!==Te.extensionName){Y(t,m,"Server indicated an extension that was not requested");return}try{h.accept(de[Te.extensionName])}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Te.extensionName]=h}t.setSocket(m,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Fn(t,e){t._readyState=E.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Bf(t){return t.path=t.socketPath,Fo.connect(t)}function Df(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Fo.isIP(t.host)?"":t.host),_f.connect(t)}function Y(t,e,n){t._readyState=E.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[qo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function us(t,e,n){if(e){let r=Tf(e)?e.size:Nf(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_e[t.readyState]})`);process.nextTick(n,r)}}function Hf(t,e){let n=this[F];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[F]!==void 0&&(n._socket.removeListener("data",Un),process.nextTick(Go,n._socket),t===1005?n.close():n.close(t,e))}function Ff(){let t=this[F];t.isPaused||t._socket.resume()}function Uf(t){let e=this[F];e._socket[F]!==void 0&&(e._socket.removeListener("data",Un),process.nextTick(Go,e._socket),e.close(t[Ef])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ho(){this[F].emitClose()}function qf(t,e){this[F].emit("message",t,e)}function Wf(t){let e=this[F];e._autoPong&&e.pong(t,!this._isServer,Uo),e.emit("ping",t)}function Gf(t){this[F].emit("pong",t)}function Go(t){t.resume()}function jf(t){let e=this[F];e.readyState!==E.CLOSED&&(e.readyState===E.OPEN&&(e._readyState=E.CLOSING,jo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function jo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function $o(){let t=this[F];if(this.removeListener("close",$o),this.removeListener("data",Un),this.removeListener("end",Vo),t._readyState=E.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[F]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ho),t._receiver.on("finish",Ho))}function Un(t){this[F]._receiver.write(t)||this.pause()}function Vo(){let t=this[F];t._readyState=E.CLOSING,t._receiver.end(),this.end()}function zo(){let t=this[F];this.removeListener("error",zo),this.on("error",Uo),t&&(t._readyState=E.CLOSING,this.destroy())}});var Xo=y((cS,Qo)=>{"use strict";var lS=qn(),{Duplex:$f}=require("stream");function Jo(t){t.emit("close")}function Vf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ko(t){this.removeListener("error",Ko),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function zf(t,e){let n=!0,r=new $f({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Jo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Jo,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Vf),r.on("error",Ko),r}Qo.exports=zf});var ea=y((uS,Zo)=>{"use strict";var{tokenChars:Yf}=ct();function Jf(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Yf[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Zo.exports={parse:Jf}});var aa=y((fS,oa)=>{"use strict";var Kf=require("events"),Wn=require("http"),{Duplex:dS}=require("stream"),{createHash:Qf}=require("crypto"),ta=os(),qe=Ut(),Xf=ea(),Zf=qn(),{CLOSE_TIMEOUT:ep,GUID:tp,kWebSocket:np}=ye(),rp=/^[+/0-9A-Za-z]{22}==$/,na=0,ra=1,ia=2,ds=class extends Kf{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ep,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Zf,...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=Wn.createServer((r,s)=>{let i=Wn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=sp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=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===ia){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(jt,this);return}if(e&&this.once("close",e),this._state!==ra)if(this._state=ra,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(jt,this):process.nextTick(jt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{jt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",sa);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){We(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){We(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!rp.test(i)){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){$t(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Xf.parse(l)}catch{We(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new qe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=ta.parse(u);h[qe.extensionName]&&(f.accept(h[qe.extensionName]),d[qe.extensionName]=f)}catch{We(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,p,m)=>{if(!h)return $t(n,g||401,p,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return $t(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[np])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>na)return $t(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Qf("sha1").update(n+tp).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[qe.extensionName]){let d=e[qe.extensionName].params,f=ta.format({[qe.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
1
+ "use strict";var Nd=Object.create;var ro=Object.defineProperty;var Od=Object.getOwnPropertyDescriptor;var Bd=Object.getOwnPropertyNames;var Dd=Object.getPrototypeOf,Hd=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Fd=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Bd(e))!Hd.call(t,s)&&s!==n&&ro(t,s,{get:()=>e[s],enumerable:!(r=Od(e,s))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?Nd(Dd(t)):{},Fd(e||!t||!t.__esModule?ro(n,"default",{value:t,enumerable:!0}):n,t));var ye=y((Qv,oo)=>{"use strict";var so=["nodebuffer","arraybuffer","fragments"],io=typeof Blob<"u";io&&so.push("blob");oo.exports={BINARY_TYPES:so,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:io,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Dt=y((Xv,Pn)=>{"use strict";var{EMPTY_BUFFER:Ud}=ye(),Vr=Buffer[Symbol.species];function qd(t,e){if(t.length===0)return Ud;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Vr(n.buffer,n.byteOffset,r):n}function ao(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function lo(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Wd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function zr(t){if(zr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Vr(t):ArrayBuffer.isView(t)?e=new Vr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),zr.readOnly=!1),e}Pn.exports={concat:qd,mask:ao,toArrayBuffer:Wd,toBuffer:zr,unmask:lo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Pn.exports.mask=function(e,n,r,s,i){i<48?ao(e,n,r,s,i):t.mask(e,n,r,s,i)},Pn.exports.unmask=function(e,n){e.length<32?lo(e,n):t.unmask(e,n)}}catch{}});var fo=y((Zv,uo)=>{"use strict";var co=Symbol("kDone"),Yr=Symbol("kRun"),Jr=class{constructor(e){this[co]=()=>{this.pending--,this[Yr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Yr]()}[Yr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[co])}}};uo.exports=Jr});var Ft=y((eS,mo)=>{"use strict";var Ht=require("zlib"),po=Dt(),Gd=fo(),{kStatusCode:ho}=ye(),jd=Buffer[Symbol.species],$d=Buffer.from([0,0,255,255]),Mn=Symbol("permessage-deflate"),ve=Symbol("total-length"),at=Symbol("callback"),Ae=Symbol("buffers"),lt=Symbol("error"),Rn,Kr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Rn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Rn=new Gd(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[at];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Rn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Rn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ht.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Mn]=this,this._inflate[ve]=0,this._inflate[Ae]=[],this._inflate.on("error",zd),this._inflate.on("data",go)}this._inflate[at]=r,this._inflate.write(e),n&&this._inflate.write($d),this._inflate.flush(()=>{let i=this._inflate[lt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=po.concat(this._inflate[Ae],this._inflate[ve]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ve]=0,this._inflate[Ae]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ht.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ht.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ve]=0,this._deflate[Ae]=[],this._deflate.on("data",Vd)}this._deflate[at]=r,this._deflate.write(e),this._deflate.flush(Ht.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=po.concat(this._deflate[Ae],this._deflate[ve]);n&&(i=new jd(i.buffer,i.byteOffset,i.length-4)),this._deflate[at]=null,this._deflate[ve]=0,this._deflate[Ae]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};mo.exports=Kr;function Vd(t){this[Ae].push(t),this[ve]+=t.length}function go(t){if(this[ve]+=t.length,this[Mn]._maxPayload<1||this[ve]<=this[Mn]._maxPayload){this[Ae].push(t);return}this[lt]=new RangeError("Max payload size exceeded"),this[lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lt][ho]=1009,this.removeListener("data",go),this.reset()}function zd(t){if(this[Mn]._inflate=null,this[lt]){this[at](this[lt]);return}t[ho]=1007,this[at](t)}});var ct=y((tS,Ln)=>{"use strict";var{isUtf8:yo}=require("buffer"),{hasBlob:Yd}=ye(),Jd=[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 Kd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Qr(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Qd(t){return Yd&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ln.exports={isBlob:Qd,isValidStatusCode:Kd,isValidUTF8:Qr,tokenChars:Jd};if(yo)Ln.exports.isValidUTF8=function(t){return t.length<24?Qr(t):yo(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ln.exports.isValidUTF8=function(e){return e.length<32?Qr(e):t(e)}}catch{}});var ns=y((nS,Ao)=>{"use strict";var{Writable:Xd}=require("stream"),vo=Ft(),{BINARY_TYPES:Zd,EMPTY_BUFFER:So,kStatusCode:ef,kWebSocket:tf}=ye(),{concat:Xr,toArrayBuffer:nf,unmask:rf}=Dt(),{isValidStatusCode:sf,isValidUTF8:_o}=ct(),Nn=Buffer[Symbol.species],X=0,bo=1,wo=2,Io=3,Zr=4,es=5,On=6,ts=class extends Xd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Zd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[tf]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Nn(r.buffer,r.byteOffset+e,r.length-e),new Nn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Nn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case bo:this.getPayloadLength16(e);break;case wo:this.getPayloadLength64(e);break;case Io:this.getMask();break;case Zr:this.getData(e);break;case es:case On:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[vo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=bo:this._payloadLength===127?this._state=wo:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Io:this._state=Zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Zr}getData(e){let n=So;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&&rf(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=es,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[vo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Xr(r,n):this._binaryType==="arraybuffer"?s=nf(Xr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=On,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Xr(r,n);if(!this._skipUTF8Validation&&!_o(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===es||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=On,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,So),this.end();else{let r=e.readUInt16BE(0);if(!sf(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Nn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_o(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=On,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[ef]=s,o}};Ao.exports=ts});var is=y((sS,Co)=>{"use strict";var{Duplex:rS}=require("stream"),{randomFillSync:of}=require("crypto"),xo=Ft(),{EMPTY_BUFFER:af,kWebSocket:lf,NOOP:cf}=ye(),{isBlob:ut,isValidStatusCode:uf}=ct(),{mask:To,toBuffer:He}=Dt(),Z=Symbol("kByteLength"),df=Buffer.alloc(4),Bn=8*1024,Fe,dt=Bn,se=0,ff=1,pf=2,rs=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=se,this.onerror=cf,this[lf]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||df,n.generateMask?n.generateMask(r):(dt===Bn&&(Fe===void 0&&(Fe=Buffer.alloc(Bn)),of(Fe,0,Bn),dt=0),r[0]=Fe[dt++],r[1]=Fe[dt++],r[2]=Fe[dt++],r[3]=Fe[dt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(To(e,r,c,i,a),[c]):(To(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=af;else{if(typeof e!="number"||!uf(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==se?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ut(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ut(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[xo.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ut(e)?(a=e.size,l=!1):(e=He(e),a=e.length,l=He.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};ut(e)?this._state!==se?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==se?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=pf,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ss,this,a,s);return}this._bufferedBytes-=r[Z];let o=He(i);n?this.dispatch(o,n,r,s):(this._state=se,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(hf,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[xo.extensionName];this._bufferedBytes+=r[Z],this._state=ff,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ss(this,l,s);return}this._bufferedBytes-=r[Z],this._state=se,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===se&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Co.exports=rs;function ss(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function hf(t,e,n){ss(t,e,n),t.onerror(e)}});var Bo=y((iS,Oo)=>{"use strict";var{kForOnEventAttribute:Ut,kListener:os}=ye(),ko=Symbol("kCode"),Eo=Symbol("kData"),Po=Symbol("kError"),Ro=Symbol("kMessage"),Mo=Symbol("kReason"),ft=Symbol("kTarget"),Lo=Symbol("kType"),No=Symbol("kWasClean"),Se=class{constructor(e){this[ft]=null,this[Lo]=e}get target(){return this[ft]}get type(){return this[Lo]}};Object.defineProperty(Se.prototype,"target",{enumerable:!0});Object.defineProperty(Se.prototype,"type",{enumerable:!0});var Ue=class extends Se{constructor(e,n={}){super(e),this[ko]=n.code===void 0?0:n.code,this[Mo]=n.reason===void 0?"":n.reason,this[No]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ko]}get reason(){return this[Mo]}get wasClean(){return this[No]}};Object.defineProperty(Ue.prototype,"code",{enumerable:!0});Object.defineProperty(Ue.prototype,"reason",{enumerable:!0});Object.defineProperty(Ue.prototype,"wasClean",{enumerable:!0});var pt=class extends Se{constructor(e,n={}){super(e),this[Po]=n.error===void 0?null:n.error,this[Ro]=n.message===void 0?"":n.message}get error(){return this[Po]}get message(){return this[Ro]}};Object.defineProperty(pt.prototype,"error",{enumerable:!0});Object.defineProperty(pt.prototype,"message",{enumerable:!0});var qt=class extends Se{constructor(e,n={}){super(e),this[Eo]=n.data===void 0?null:n.data}get data(){return this[Eo]}};Object.defineProperty(qt.prototype,"data",{enumerable:!0});var gf={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ut]&&s[os]===e&&!s[Ut])return;let r;if(t==="message")r=function(i,o){let a=new qt("message",{data:o?i:i.toString()});a[ft]=this,Dn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ue("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ft]=this,Dn(e,this,a)};else if(t==="error")r=function(i){let o=new pt("error",{error:i,message:i.message});o[ft]=this,Dn(e,this,o)};else if(t==="open")r=function(){let i=new Se("open");i[ft]=this,Dn(e,this,i)};else return;r[Ut]=!!n[Ut],r[os]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[os]===e&&!n[Ut]){this.removeListener(t,n);break}}};Oo.exports={CloseEvent:Ue,ErrorEvent:pt,Event:Se,EventTarget:gf,MessageEvent:qt};function Dn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var as=y((oS,Do)=>{"use strict";var{tokenChars:Wt}=ct();function fe(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function mf(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Wt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(fe(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Wt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),fe(n,t.slice(l,u),!0),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Wt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Wt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Wt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),fe(n,a,h),c===44&&(fe(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?fe(e,f,n):(a===void 0?fe(n,f,!0):r?fe(n,a,f.replace(/\\/g,"")):fe(n,a,f),fe(e,o,n)),e}function yf(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Do.exports={format:yf,parse:mf}});var qn=y((cS,Jo)=>{"use strict";var vf=require("events"),Sf=require("https"),_f=require("http"),Uo=require("net"),bf=require("tls"),{randomBytes:wf,createHash:If}=require("crypto"),{Duplex:aS,Readable:lS}=require("stream"),{URL:ls}=require("url"),xe=Ft(),Af=ns(),xf=is(),{isBlob:Tf}=ct(),{BINARY_TYPES:Ho,CLOSE_TIMEOUT:Cf,EMPTY_BUFFER:Hn,GUID:kf,kForOnEventAttribute:cs,kListener:Ef,kStatusCode:Pf,kWebSocket:F,NOOP:qo}=ye(),{EventTarget:{addEventListener:Rf,removeEventListener:Mf}}=Bo(),{format:Lf,parse:Nf}=as(),{toBuffer:Of}=Dt(),Wo=Symbol("kAborted"),us=[8,13],_e=["CONNECTING","OPEN","CLOSING","CLOSED"],Bf=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,E=class t extends vf{constructor(e,n,r){super(),this._binaryType=Ho[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Hn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Go(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ho.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Af({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new xf(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[F]=this,i[F]=this,e[F]=this,s.on("conclude",Ff),s.on("drain",Uf),s.on("error",qf),s.on("message",Wf),s.on("ping",Gf),s.on("pong",jf),i.onerror=$f,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Vo),e.on("data",Un),e.on("end",zo),e.on("error",Yo),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){J(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$o(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ds(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Hn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ds(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Hn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ds(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(s.compress=!1),this._sender.send(e||Hn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(E.prototype,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(E,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(E.prototype,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(E,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(E.prototype,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(E,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});Object.defineProperty(E.prototype,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(E.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(E.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[cs])return e[Ef];return null},set(e){for(let n of this.listeners(t))if(n[cs]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[cs]:!0})}})});E.prototype.addEventListener=Rf;E.prototype.removeEventListener=Mf;Jo.exports=E;function Go(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Cf,protocolVersion:us[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!us.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${us.join(", ")})`);let i;if(e instanceof ls)i=e;else try{i=new ls(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 p=new SyntaxError(l);if(t._redirects===0)throw p;Fn(t,p);return}let c=o?443:80,u=wf(16).toString("base64"),d=o?Sf.request:_f.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?Hf:Df),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new xe(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Lf({[xe.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!Bf.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,v]of Object.entries(p))r.headers[m.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{J(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[Wo]||(g=t._req=null,Fn(t,p))}),g.on("response",p=>{let m=p.headers.location,v=p.statusCode;if(m&&s.followRedirects&&v>=300&&v<400){if(++t._redirects>s.maxRedirects){J(t,g,"Maximum redirects exceeded");return}g.abort();let b;try{b=new ls(m,e)}catch{let x=new SyntaxError(`Invalid URL: ${m}`);Fn(t,x);return}Go(t,b,n,r)}else t.emit("unexpected-response",g,p)||J(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,m,v)=>{if(t.emit("upgrade",p),t.readyState!==E.CONNECTING)return;g=t._req=null;let b=p.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){J(t,m,"Invalid Upgrade header");return}let W=If("sha1").update(u+kf).digest("base64");if(p.headers["sec-websocket-accept"]!==W){J(t,m,"Invalid Sec-WebSocket-Accept header");return}let x=p.headers["sec-websocket-protocol"],N;if(x!==void 0?f.size?f.has(x)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":f.size&&(N="Server sent no subprotocol"),N){J(t,m,N);return}x&&(t._protocol=x);let Q=p.headers["sec-websocket-extensions"];if(Q!==void 0){if(!h){J(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let de;try{de=Nf(Q)}catch{J(t,m,"Invalid Sec-WebSocket-Extensions header");return}let it=Object.keys(de);if(it.length!==1||it[0]!==xe.extensionName){J(t,m,"Server indicated an extension that was not requested");return}try{h.accept(de[xe.extensionName])}catch{J(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=h}t.setSocket(m,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Fn(t,e){t._readyState=E.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Df(t){return t.path=t.socketPath,Uo.connect(t)}function Hf(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Uo.isIP(t.host)?"":t.host),bf.connect(t)}function J(t,e,n){t._readyState=E.CLOSING;let r=new Error(n);Error.captureStackTrace(r,J),e.setHeader?(e[Wo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ds(t,e,n){if(e){let r=Tf(e)?e.size:Of(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_e[t.readyState]})`);process.nextTick(n,r)}}function Ff(t,e){let n=this[F];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[F]!==void 0&&(n._socket.removeListener("data",Un),process.nextTick(jo,n._socket),t===1005?n.close():n.close(t,e))}function Uf(){let t=this[F];t.isPaused||t._socket.resume()}function qf(t){let e=this[F];e._socket[F]!==void 0&&(e._socket.removeListener("data",Un),process.nextTick(jo,e._socket),e.close(t[Pf])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Fo(){this[F].emitClose()}function Wf(t,e){this[F].emit("message",t,e)}function Gf(t){let e=this[F];e._autoPong&&e.pong(t,!this._isServer,qo),e.emit("ping",t)}function jf(t){this[F].emit("pong",t)}function jo(t){t.resume()}function $f(t){let e=this[F];e.readyState!==E.CLOSED&&(e.readyState===E.OPEN&&(e._readyState=E.CLOSING,$o(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $o(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Vo(){let t=this[F];if(this.removeListener("close",Vo),this.removeListener("data",Un),this.removeListener("end",zo),t._readyState=E.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[F]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Fo),t._receiver.on("finish",Fo))}function Un(t){this[F]._receiver.write(t)||this.pause()}function zo(){let t=this[F];t._readyState=E.CLOSING,t._receiver.end(),this.end()}function Yo(){let t=this[F];this.removeListener("error",Yo),this.on("error",qo),t&&(t._readyState=E.CLOSING,this.destroy())}});var Zo=y((dS,Xo)=>{"use strict";var uS=qn(),{Duplex:Vf}=require("stream");function Ko(t){t.emit("close")}function zf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Qo(t){this.removeListener("error",Qo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Yf(t,e){let n=!0,r=new Vf({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Ko,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ko,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",zf),r.on("error",Qo),r}Xo.exports=Yf});var ta=y((fS,ea)=>{"use strict";var{tokenChars:Jf}=ct();function Kf(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Jf[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ea.exports={parse:Kf}});var la=y((hS,aa)=>{"use strict";var Qf=require("events"),Wn=require("http"),{Duplex:pS}=require("stream"),{createHash:Xf}=require("crypto"),na=as(),qe=Ft(),Zf=ta(),ep=qn(),{CLOSE_TIMEOUT:tp,GUID:np,kWebSocket:rp}=ye(),sp=/^[+/0-9A-Za-z]{22}==$/,ra=0,sa=1,oa=2,fs=class extends Qf{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:tp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ep,...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=Wn.createServer((r,s)=>{let i=Wn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=ip(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ra}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===oa){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Gt,this);return}if(e&&this.once("close",e),this._state!==sa)if(this._state=sa,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(Gt,this):process.nextTick(Gt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Gt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",ia);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){We(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){We(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!sp.test(i)){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){jt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Zf.parse(l)}catch{We(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new qe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=na.parse(u);h[qe.extensionName]&&(f.accept(h[qe.extensionName]),d[qe.extensionName]=f)}catch{We(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,p,m)=>{if(!h)return jt(n,g||401,p,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return jt(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[rp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ra)return jt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Xf("sha1").update(n+np).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[qe.extensionName]){let d=e[qe.extensionName].params,f=na.format({[qe.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",sa),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(jt,this)})),a(u,s)}};oa.exports=ds;function sp(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function jt(t){t._state=ia,t.emit("close")}function sa(){this.destroy()}function $t(t,e,n,r){n=n||Wn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Wn.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",ia),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Gt,this)})),a(u,s)}};aa.exports=fs;function ip(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Gt(t){t._state=oa,t.emit("close")}function ia(){this.destroy()}function jt(t,e,n,r){n=n||Wn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Wn.STATUS_CODES[e]}\r
4
4
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function We(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,We),t.emit("wsClientError",o,n,e)}else $t(n,r,s,i)}});var ps=y((hS,la)=>{la.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var xe=y(Ge=>{var hs,cp=[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];Ge.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};Ge.getSymbolTotalCodewords=function(e){return cp[e]};Ge.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ge.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');hs=e};Ge.isKanjiModeEnabled=function(){return typeof hs<"u"};Ge.toSJIS=function(e){return hs(e)}});var Gn=y(ee=>{ee.L={bit:1};ee.M={bit:0};ee.Q={bit:3};ee.H={bit:2};function up(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ee.L;case"m":case"medium":return ee.M;case"q":case"quartile":return ee.Q;case"h":case"high":return ee.H;default:throw new Error("Unknown EC Level: "+t)}}ee.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ee.from=function(e,n){if(ee.isValid(e))return e;try{return up(e)}catch{return n}}});var da=y((yS,ua)=>{function ca(){this.buffer=[],this.length=0}ca.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++}};ua.exports=ca});var pa=y((vS,fa)=>{function Vt(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)}Vt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Vt.prototype.get=function(t,e){return this.data[t*this.size+e]};Vt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Vt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};fa.exports=Vt});var ha=y(jn=>{var dp=xe().getSymbolSize;jn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=dp(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};jn.getPositions=function(e){let n=[],r=jn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var ya=y(ma=>{var fp=xe().getSymbolSize,ga=7;ma.getPositions=function(e){let n=fp(e);return[[0,0],[n-ga,0],[0,n-ga]]}});var va=y(T=>{T.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var je={N1:3,N2:3,N3:40,N4:10};T.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};T.from=function(e){return T.isValid(e)?parseInt(e,10):void 0};T.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=je.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=je.N1+(i-5)),a=u,i=1)}s>=5&&(r+=je.N1+(s-5)),i>=5&&(r+=je.N1+(i-5))}return r};T.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*je.N2};T.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*je.N3};T.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*je.N4};function pp(t,e,n){switch(t){case T.Patterns.PATTERN000:return(e+n)%2===0;case T.Patterns.PATTERN001:return e%2===0;case T.Patterns.PATTERN010:return n%3===0;case T.Patterns.PATTERN011:return(e+n)%3===0;case T.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case T.Patterns.PATTERN101:return e*n%2+e*n%3===0;case T.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case T.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}T.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,pp(e,i,s))};T.getBestMask=function(e,n){let r=Object.keys(T.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),T.applyMask(o,e);let a=T.getPenaltyN1(e)+T.getPenaltyN2(e)+T.getPenaltyN3(e)+T.getPenaltyN4(e);T.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var ms=y(gs=>{var Ce=Gn(),$n=[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],Vn=[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];gs.getBlocksCount=function(e,n){switch(n){case Ce.L:return $n[(e-1)*4+0];case Ce.M:return $n[(e-1)*4+1];case Ce.Q:return $n[(e-1)*4+2];case Ce.H:return $n[(e-1)*4+3];default:return}};gs.getTotalCodewordsCount=function(e,n){switch(n){case Ce.L:return Vn[(e-1)*4+0];case Ce.M:return Vn[(e-1)*4+1];case Ce.Q:return Vn[(e-1)*4+2];case Ce.H:return Vn[(e-1)*4+3];default:return}}});var Sa=y(Yn=>{var zt=new Uint8Array(512),zn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)zt[n]=e,zn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)zt[n]=zt[n-255]})();Yn.log=function(e){if(e<1)throw new Error("log("+e+")");return zn[e]};Yn.exp=function(e){return zt[e]};Yn.mul=function(e,n){return e===0||n===0?0:zt[zn[e]+zn[n]]}});var _a=y(Yt=>{var ys=Sa();Yt.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=ys.mul(e[s],n[i]);return r};Yt.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=ys.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Yt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Yt.mul(n,new Uint8Array([1,ys.exp(r)]));return n}});var Ia=y((TS,wa)=>{var ba=_a();function vs(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}vs.prototype.initialize=function(e){this.degree=e,this.genPoly=ba.generateECPolynomial(this.degree)};vs.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=ba.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};wa.exports=vs});var Ss=y(Aa=>{Aa.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var _s=y(be=>{var Ta="[0-9]+",hp="[A-Z $%*+\\-./:]+",Jt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Jt=Jt.replace(/u/g,"\\u");var gp="(?:(?![A-Z0-9 $%*+\\-./:]|"+Jt+`)(?:.|[\r
8
- ]))+`;be.KANJI=new RegExp(Jt,"g");be.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");be.BYTE=new RegExp(gp,"g");be.NUMERIC=new RegExp(Ta,"g");be.ALPHANUMERIC=new RegExp(hp,"g");var mp=new RegExp("^"+Jt+"$"),yp=new RegExp("^"+Ta+"$"),vp=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");be.testKanji=function(e){return mp.test(e)};be.testNumeric=function(e){return yp.test(e)};be.testAlphanumeric=function(e){return vp.test(e)}});var ke=y(O=>{var Sp=Ss(),bs=_s();O.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};O.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};O.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};O.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};O.MIXED={bit:-1};O.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Sp.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};O.getBestModeForData=function(e){return bs.testNumeric(e)?O.NUMERIC:bs.testAlphanumeric(e)?O.ALPHANUMERIC:bs.testKanji(e)?O.KANJI:O.BYTE};O.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};O.isValid=function(e){return e&&e.bit&&e.ccBits};function _p(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return O.NUMERIC;case"alphanumeric":return O.ALPHANUMERIC;case"kanji":return O.KANJI;case"byte":return O.BYTE;default:throw new Error("Unknown mode: "+t)}}O.from=function(e,n){if(O.isValid(e))return e;try{return _p(e)}catch{return n}}});var Pa=y($e=>{var Jn=xe(),bp=ms(),xa=Gn(),Ee=ke(),ws=Ss(),ka=7973,Ca=Jn.getBCHDigit(ka);function wp(t,e,n){for(let r=1;r<=40;r++)if(e<=$e.getCapacity(r,n,t))return r}function Ea(t,e){return Ee.getCharCountIndicator(t,e)+4}function Ip(t,e){let n=0;return t.forEach(function(r){let s=Ea(r.mode,e);n+=s+r.getBitsLength()}),n}function Ap(t,e){for(let n=1;n<=40;n++)if(Ip(t,n)<=$e.getCapacity(n,e,Ee.MIXED))return n}$e.from=function(e,n){return ws.isValid(e)?parseInt(e,10):n};$e.getCapacity=function(e,n,r){if(!ws.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Ee.BYTE);let s=Jn.getSymbolTotalCodewords(e),i=bp.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Ee.MIXED)return o;let a=o-Ea(r,e);switch(r){case Ee.NUMERIC:return Math.floor(a/10*3);case Ee.ALPHANUMERIC:return Math.floor(a/11*2);case Ee.KANJI:return Math.floor(a/13);case Ee.BYTE:default:return Math.floor(a/8)}};$e.getBestVersionForData=function(e,n){let r,s=xa.from(n,xa.M);if(Array.isArray(e)){if(e.length>1)return Ap(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return wp(r.mode,r.getLength(),s)};$e.getEncodedBits=function(e){if(!ws.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Jn.getBCHDigit(n)-Ca>=0;)n^=ka<<Jn.getBCHDigit(n)-Ca;return e<<12|n}});var Na=y(La=>{var Is=xe(),Ma=1335,Tp=21522,Ra=Is.getBCHDigit(Ma);La.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Is.getBCHDigit(s)-Ra>=0;)s^=Ma<<Is.getBCHDigit(s)-Ra;return(r<<10|s)^Tp}});var Ba=y((RS,Oa)=>{var xp=ke();function ht(t){this.mode=xp.NUMERIC,this.data=t.toString()}ht.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};ht.prototype.getLength=function(){return this.data.length};ht.prototype.getBitsLength=function(){return ht.getBitsLength(this.data.length)};ht.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Oa.exports=ht});var Ha=y((MS,Da)=>{var Cp=ke(),As=["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 gt(t){this.mode=Cp.ALPHANUMERIC,this.data=t}gt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};gt.prototype.getLength=function(){return this.data.length};gt.prototype.getBitsLength=function(){return gt.getBitsLength(this.data.length)};gt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=As.indexOf(this.data[n])*45;r+=As.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(As.indexOf(this.data[n]),6)};Da.exports=gt});var Ua=y((LS,Fa)=>{var kp=ke();function mt(t){this.mode=kp.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}mt.getBitsLength=function(e){return e*8};mt.prototype.getLength=function(){return this.data.length};mt.prototype.getBitsLength=function(){return mt.getBitsLength(this.data.length)};mt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Fa.exports=mt});var Wa=y((NS,qa)=>{var Ep=ke(),Pp=xe();function yt(t){this.mode=Ep.KANJI,this.data=t}yt.getBitsLength=function(e){return e*13};yt.prototype.getLength=function(){return this.data.length};yt.prototype.getBitsLength=function(){return yt.getBitsLength(this.data.length)};yt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Pp.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)}};qa.exports=yt});var Ga=y((OS,Ts)=>{"use strict";var Kt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Kt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=s[l],g=typeof s[l]>"u",(g||h>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Kt.single_source_shortest_paths(t,e,n);return Kt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Kt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Ts<"u"&&(Ts.exports=Kt)});var Qa=y(vt=>{var A=ke(),Va=Ba(),za=Ha(),Ya=Ua(),Ja=Wa(),Qt=_s(),Kn=xe(),Rp=Ga();function ja(t){return unescape(encodeURIComponent(t)).length}function Xt(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function Ka(t){let e=Xt(Qt.NUMERIC,A.NUMERIC,t),n=Xt(Qt.ALPHANUMERIC,A.ALPHANUMERIC,t),r,s;return Kn.isKanjiModeEnabled()?(r=Xt(Qt.BYTE,A.BYTE,t),s=Xt(Qt.KANJI,A.KANJI,t)):(r=Xt(Qt.BYTE_KANJI,A.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function xs(t,e){switch(e){case A.NUMERIC:return Va.getBitsLength(t);case A.ALPHANUMERIC:return za.getBitsLength(t);case A.KANJI:return Ja.getBitsLength(t);case A.BYTE:return Ya.getBitsLength(t)}}function Mp(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Lp(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case A.NUMERIC:e.push([r,{data:r.data,mode:A.ALPHANUMERIC,length:r.length},{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.ALPHANUMERIC:e.push([r,{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.KANJI:e.push([r,{data:r.data,mode:A.BYTE,length:ja(r.data)}]);break;case A.BYTE:e.push([{data:r.data,mode:A.BYTE,length:ja(r.data)}])}}return e}function Np(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=xs(n[f].lastCount+c.length,c.mode)-xs(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=xs(c.length,c.mode)+4+A.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function $a(t,e){let n,r=A.getBestModeForData(t);if(n=A.from(e,r),n!==A.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+A.toString(n)+`.
10
- Suggested mode is: `+A.toString(r));switch(n===A.KANJI&&!Kn.isKanjiModeEnabled()&&(n=A.BYTE),n){case A.NUMERIC:return new Va(t);case A.ALPHANUMERIC:return new za(t);case A.KANJI:return new Ja(t);case A.BYTE:return new Ya(t)}}vt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push($a(r,null)):r.data&&n.push($a(r.data,r.mode)),n},[])};vt.fromString=function(e,n){let r=Ka(e,Kn.isKanjiModeEnabled()),s=Lp(r),i=Np(s,n),o=Rp.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return vt.fromArray(Mp(a))};vt.rawSplit=function(e){return vt.fromArray(Ka(e,Kn.isKanjiModeEnabled()))}});var Ms=y(Xa=>{var Xn=xe(),Cs=Gn(),Op=da(),Bp=pa(),Dp=ha(),Hp=ya(),Ps=va(),Rs=ms(),Fp=Ia(),Qn=Pa(),Up=Na(),qp=ke(),ks=Qa();function Wp(t,e){let n=t.size,r=Hp.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function Gp(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function jp(t,e){let n=Dp.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function $p(t,e){let n=t.size,r=Qn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Es(t,e,n){let r=t.size,s=Up.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function Vp(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function zp(t,e,n){let r=new Op;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),qp.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Xn.getSymbolTotalCodewords(t),i=Rs.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Yp(r,t,e)}function Yp(t,e,n){let r=Xn.getSymbolTotalCodewords(e),s=Rs.getTotalCodewordsCount(e,n),i=r-s,o=Rs.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,h=new Fp(f),g=0,p=new Array(o),m=new Array(o),v=0,w=new Uint8Array(t.buffer);for(let de=0;de<o;de++){let it=de<l?u:d;p[de]=w.slice(g,g+it),m[de]=h.encode(p[de]),g+=it,v=Math.max(v,it)}let K=new Uint8Array(r),k=0,H,Q;for(H=0;H<v;H++)for(Q=0;Q<o;Q++)H<p[Q].length&&(K[k++]=p[Q][H]);for(H=0;H<f;H++)for(Q=0;Q<o;Q++)K[k++]=m[Q][H];return K}function Jp(t,e,n,r){let s;if(Array.isArray(t))s=ks.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=ks.rawSplit(t);c=Qn.getBestVersionForData(u,n)}s=ks.fromString(t,c||40)}else throw new Error("Invalid data");let i=Qn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
7
+ `+n)}function We(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,We),t.emit("wsClientError",o,n,e)}else jt(n,r,s,i)}});var hs=y((mS,ca)=>{ca.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Te=y(Ge=>{var gs,up=[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];Ge.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};Ge.getSymbolTotalCodewords=function(e){return up[e]};Ge.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ge.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');gs=e};Ge.isKanjiModeEnabled=function(){return typeof gs<"u"};Ge.toSJIS=function(e){return gs(e)}});var Gn=y(ee=>{ee.L={bit:1};ee.M={bit:0};ee.Q={bit:3};ee.H={bit:2};function dp(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ee.L;case"m":case"medium":return ee.M;case"q":case"quartile":return ee.Q;case"h":case"high":return ee.H;default:throw new Error("Unknown EC Level: "+t)}}ee.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ee.from=function(e,n){if(ee.isValid(e))return e;try{return dp(e)}catch{return n}}});var fa=y((SS,da)=>{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++}};da.exports=ua});var ha=y((_S,pa)=>{function $t(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)}$t.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};$t.prototype.get=function(t,e){return this.data[t*this.size+e]};$t.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};$t.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};pa.exports=$t});var ga=y(jn=>{var fp=Te().getSymbolSize;jn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=fp(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};jn.getPositions=function(e){let n=[],r=jn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var va=y(ya=>{var pp=Te().getSymbolSize,ma=7;ya.getPositions=function(e){let n=pp(e);return[[0,0],[n-ma,0],[0,n-ma]]}});var Sa=y(T=>{T.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var je={N1:3,N2:3,N3:40,N4:10};T.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};T.from=function(e){return T.isValid(e)?parseInt(e,10):void 0};T.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=je.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=je.N1+(i-5)),a=u,i=1)}s>=5&&(r+=je.N1+(s-5)),i>=5&&(r+=je.N1+(i-5))}return r};T.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*je.N2};T.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*je.N3};T.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*je.N4};function hp(t,e,n){switch(t){case T.Patterns.PATTERN000:return(e+n)%2===0;case T.Patterns.PATTERN001:return e%2===0;case T.Patterns.PATTERN010:return n%3===0;case T.Patterns.PATTERN011:return(e+n)%3===0;case T.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case T.Patterns.PATTERN101:return e*n%2+e*n%3===0;case T.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case T.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}T.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,hp(e,i,s))};T.getBestMask=function(e,n){let r=Object.keys(T.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),T.applyMask(o,e);let a=T.getPenaltyN1(e)+T.getPenaltyN2(e)+T.getPenaltyN3(e)+T.getPenaltyN4(e);T.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var ys=y(ms=>{var Ce=Gn(),$n=[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],Vn=[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];ms.getBlocksCount=function(e,n){switch(n){case Ce.L:return $n[(e-1)*4+0];case Ce.M:return $n[(e-1)*4+1];case Ce.Q:return $n[(e-1)*4+2];case Ce.H:return $n[(e-1)*4+3];default:return}};ms.getTotalCodewordsCount=function(e,n){switch(n){case Ce.L:return Vn[(e-1)*4+0];case Ce.M:return Vn[(e-1)*4+1];case Ce.Q:return Vn[(e-1)*4+2];case Ce.H:return Vn[(e-1)*4+3];default:return}}});var _a=y(Yn=>{var Vt=new Uint8Array(512),zn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Vt[n]=e,zn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Vt[n]=Vt[n-255]})();Yn.log=function(e){if(e<1)throw new Error("log("+e+")");return zn[e]};Yn.exp=function(e){return Vt[e]};Yn.mul=function(e,n){return e===0||n===0?0:Vt[zn[e]+zn[n]]}});var ba=y(zt=>{var vs=_a();zt.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=vs.mul(e[s],n[i]);return r};zt.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=vs.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};zt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=zt.mul(n,new Uint8Array([1,vs.exp(r)]));return n}});var Aa=y((CS,Ia)=>{var wa=ba();function Ss(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ss.prototype.initialize=function(e){this.degree=e,this.genPoly=wa.generateECPolynomial(this.degree)};Ss.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=wa.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Ia.exports=Ss});var _s=y(xa=>{xa.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var bs=y(be=>{var Ta="[0-9]+",gp="[A-Z $%*+\\-./:]+",Yt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Yt=Yt.replace(/u/g,"\\u");var mp="(?:(?![A-Z0-9 $%*+\\-./:]|"+Yt+`)(?:.|[\r
8
+ ]))+`;be.KANJI=new RegExp(Yt,"g");be.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");be.BYTE=new RegExp(mp,"g");be.NUMERIC=new RegExp(Ta,"g");be.ALPHANUMERIC=new RegExp(gp,"g");var yp=new RegExp("^"+Yt+"$"),vp=new RegExp("^"+Ta+"$"),Sp=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");be.testKanji=function(e){return yp.test(e)};be.testNumeric=function(e){return vp.test(e)};be.testAlphanumeric=function(e){return Sp.test(e)}});var ke=y(B=>{var _p=_s(),ws=bs();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(!_p.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 ws.testNumeric(e)?B.NUMERIC:ws.testAlphanumeric(e)?B.ALPHANUMERIC:ws.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 bp(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 bp(e)}catch{return n}}});var Ra=y($e=>{var Jn=Te(),wp=ys(),Ca=Gn(),Ee=ke(),Is=_s(),Ea=7973,ka=Jn.getBCHDigit(Ea);function Ip(t,e,n){for(let r=1;r<=40;r++)if(e<=$e.getCapacity(r,n,t))return r}function Pa(t,e){return Ee.getCharCountIndicator(t,e)+4}function Ap(t,e){let n=0;return t.forEach(function(r){let s=Pa(r.mode,e);n+=s+r.getBitsLength()}),n}function xp(t,e){for(let n=1;n<=40;n++)if(Ap(t,n)<=$e.getCapacity(n,e,Ee.MIXED))return n}$e.from=function(e,n){return Is.isValid(e)?parseInt(e,10):n};$e.getCapacity=function(e,n,r){if(!Is.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Ee.BYTE);let s=Jn.getSymbolTotalCodewords(e),i=wp.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Ee.MIXED)return o;let a=o-Pa(r,e);switch(r){case Ee.NUMERIC:return Math.floor(a/10*3);case Ee.ALPHANUMERIC:return Math.floor(a/11*2);case Ee.KANJI:return Math.floor(a/13);case Ee.BYTE:default:return Math.floor(a/8)}};$e.getBestVersionForData=function(e,n){let r,s=Ca.from(n,Ca.M);if(Array.isArray(e)){if(e.length>1)return xp(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Ip(r.mode,r.getLength(),s)};$e.getEncodedBits=function(e){if(!Is.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Jn.getBCHDigit(n)-ka>=0;)n^=Ea<<Jn.getBCHDigit(n)-ka;return e<<12|n}});var Oa=y(Na=>{var As=Te(),La=1335,Tp=21522,Ma=As.getBCHDigit(La);Na.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;As.getBCHDigit(s)-Ma>=0;)s^=La<<As.getBCHDigit(s)-Ma;return(r<<10|s)^Tp}});var Da=y((LS,Ba)=>{var Cp=ke();function ht(t){this.mode=Cp.NUMERIC,this.data=t.toString()}ht.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};ht.prototype.getLength=function(){return this.data.length};ht.prototype.getBitsLength=function(){return ht.getBitsLength(this.data.length)};ht.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Ba.exports=ht});var Fa=y((NS,Ha)=>{var kp=ke(),xs=["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 gt(t){this.mode=kp.ALPHANUMERIC,this.data=t}gt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};gt.prototype.getLength=function(){return this.data.length};gt.prototype.getBitsLength=function(){return gt.getBitsLength(this.data.length)};gt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=xs.indexOf(this.data[n])*45;r+=xs.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(xs.indexOf(this.data[n]),6)};Ha.exports=gt});var qa=y((OS,Ua)=>{var Ep=ke();function mt(t){this.mode=Ep.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}mt.getBitsLength=function(e){return e*8};mt.prototype.getLength=function(){return this.data.length};mt.prototype.getBitsLength=function(){return mt.getBitsLength(this.data.length)};mt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Ua.exports=mt});var Ga=y((BS,Wa)=>{var Pp=ke(),Rp=Te();function yt(t){this.mode=Pp.KANJI,this.data=t}yt.getBitsLength=function(e){return e*13};yt.prototype.getLength=function(){return this.data.length};yt.prototype.getBitsLength=function(){return yt.getBitsLength(this.data.length)};yt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Rp.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)}};Wa.exports=yt});var ja=y((DS,Ts)=>{"use strict";var Jt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Jt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=s[l],g=typeof s[l]>"u",(g||h>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Jt.single_source_shortest_paths(t,e,n);return Jt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Jt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Ts<"u"&&(Ts.exports=Jt)});var Xa=y(vt=>{var A=ke(),za=Da(),Ya=Fa(),Ja=qa(),Ka=Ga(),Kt=bs(),Kn=Te(),Mp=ja();function $a(t){return unescape(encodeURIComponent(t)).length}function Qt(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function Qa(t){let e=Qt(Kt.NUMERIC,A.NUMERIC,t),n=Qt(Kt.ALPHANUMERIC,A.ALPHANUMERIC,t),r,s;return Kn.isKanjiModeEnabled()?(r=Qt(Kt.BYTE,A.BYTE,t),s=Qt(Kt.KANJI,A.KANJI,t)):(r=Qt(Kt.BYTE_KANJI,A.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Cs(t,e){switch(e){case A.NUMERIC:return za.getBitsLength(t);case A.ALPHANUMERIC:return Ya.getBitsLength(t);case A.KANJI:return Ka.getBitsLength(t);case A.BYTE:return Ja.getBitsLength(t)}}function Lp(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Np(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case A.NUMERIC:e.push([r,{data:r.data,mode:A.ALPHANUMERIC,length:r.length},{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.ALPHANUMERIC:e.push([r,{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.KANJI:e.push([r,{data:r.data,mode:A.BYTE,length:$a(r.data)}]);break;case A.BYTE:e.push([{data:r.data,mode:A.BYTE,length:$a(r.data)}])}}return e}function Op(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=Cs(n[f].lastCount+c.length,c.mode)-Cs(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Cs(c.length,c.mode)+4+A.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function Va(t,e){let n,r=A.getBestModeForData(t);if(n=A.from(e,r),n!==A.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+A.toString(n)+`.
10
+ Suggested mode is: `+A.toString(r));switch(n===A.KANJI&&!Kn.isKanjiModeEnabled()&&(n=A.BYTE),n){case A.NUMERIC:return new za(t);case A.ALPHANUMERIC:return new Ya(t);case A.KANJI:return new Ka(t);case A.BYTE:return new Ja(t)}}vt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Va(r,null)):r.data&&n.push(Va(r.data,r.mode)),n},[])};vt.fromString=function(e,n){let r=Qa(e,Kn.isKanjiModeEnabled()),s=Np(r),i=Op(s,n),o=Mp.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return vt.fromArray(Lp(a))};vt.rawSplit=function(e){return vt.fromArray(Qa(e,Kn.isKanjiModeEnabled()))}});var Ls=y(Za=>{var Xn=Te(),ks=Gn(),Bp=fa(),Dp=ha(),Hp=ga(),Fp=va(),Rs=Sa(),Ms=ys(),Up=Aa(),Qn=Ra(),qp=Oa(),Wp=ke(),Es=Xa();function Gp(t,e){let n=t.size,r=Fp.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function jp(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function $p(t,e){let n=Hp.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function Vp(t,e){let n=t.size,r=Qn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Ps(t,e,n){let r=t.size,s=qp.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function zp(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Yp(t,e,n){let r=new Bp;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Wp.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Xn.getSymbolTotalCodewords(t),i=Ms.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Jp(r,t,e)}function Jp(t,e,n){let r=Xn.getSymbolTotalCodewords(e),s=Ms.getTotalCodewordsCount(e,n),i=r-s,o=Ms.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,h=new Up(f),g=0,p=new Array(o),m=new Array(o),v=0,b=new Uint8Array(t.buffer);for(let de=0;de<o;de++){let it=de<l?u:d;p[de]=b.slice(g,g+it),m[de]=h.encode(p[de]),g+=it,v=Math.max(v,it)}let W=new Uint8Array(r),x=0,N,Q;for(N=0;N<v;N++)for(Q=0;Q<o;Q++)N<p[Q].length&&(W[x++]=p[Q][N]);for(N=0;N<f;N++)for(Q=0;Q<o;Q++)W[x++]=m[Q][N];return W}function Kp(t,e,n,r){let s;if(Array.isArray(t))s=Es.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Es.rawSplit(t);c=Qn.getBestVersionForData(u,n)}s=Es.fromString(t,c||40)}else throw new Error("Invalid data");let i=Qn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
12
  Minimum version required to store current data is: `+i+`.
13
- `);let o=zp(e,n,s),a=Xn.getSymbolSize(e),l=new Bp(a);return Wp(l,e),Gp(l),jp(l,e),Es(l,n,0),e>=7&&$p(l,e),Vp(l,o),isNaN(r)&&(r=Ps.getBestMask(l,Es.bind(null,l,n))),Ps.applyMask(r,l),Es(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Xa.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Cs.M,s,i;return typeof n<"u"&&(r=Cs.from(n.errorCorrectionLevel,Cs.M),s=Qn.from(n.version),i=Ps.from(n.maskPattern),n.toSJISFunc&&Xn.setToSJISFunction(n.toSJISFunc)),Jp(e,s,r,i)}});var Ls=y((HS,el)=>{"use strict";var Kp=require("util"),Za=require("stream"),ie=el.exports=function(){Za.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Kp.inherits(ie,Za);ie.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))};ie.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};ie.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()))};ie.prototype.destroySoon=ie.prototype.end;ie.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ie.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ie.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))};ie.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};ie.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 Os=y(Ns=>{"use strict";var Pe=[{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]}];Ns.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Pe.length;a++){let l=Pe[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Ns.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Pe[r].x.length,i=(e-s)/Pe[r].x.length*8+Pe[r].x[s],o=n%Pe[r].y.length,a=(n-o)/Pe[r].y.length*8+Pe[r].y[o];return i*4+a*t*4}}});var Bs=y((US,tl)=>{"use strict";tl.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Ds=y((qS,rl)=>{"use strict";var Qp=Os(),Xp=Bs();function nl(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var St=rl.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Qp.getImagePasses(n,r);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:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};St.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};St.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};St.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};St.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};St.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Xp(c,l,u);e[o]=a+d}};St.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var ol=y((WS,il)=>{"use strict";var Zp=require("util"),sl=Ls(),eh=Ds(),th=il.exports=function(t){sl.call(this);let e=[],n=this;this._filter=new eh(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Zp.inherits(th,sl)});var _t=y((GS,al)=>{"use strict";al.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 Us=y((jS,ll)=>{"use strict";var Hs=[];(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;Hs[t]=e}})();var Fs=ll.exports=function(){this._crc=-1};Fs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Hs[(this._crc^t[e])&255]^this._crc>>>8;return!0};Fs.prototype.crc32=function(){return this._crc^-1};Fs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Hs[(e^t[n])&255]^e>>>8;return e^-1}});var qs=y(($S,cl)=>{"use strict";var B=_t(),nh=Us(),U=cl.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[B.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[B.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[B.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[B.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[B.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[B.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};U.prototype.start=function(){this.read(B.PNG_SIGNATURE.length,this._parseSignature.bind(this))};U.prototype._parseSignature=function(t){let e=B.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};U.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==B.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new nh,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};U.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};U.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};U.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in B.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=B.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&B.COLORTYPE_PALETTE),color:!!(s&B.COLORTYPE_COLOR),alpha:!!(s&B.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};U.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};U.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};U.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};U.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===B.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===B.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===B.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};U.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};U.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/B.GAMMA_DIVISION),this._handleChunkEnd()};U.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};U.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===B.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};U.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};U.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ws=y(dl=>{"use strict";var ul=Os(),rh=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],sh=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function ih(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function oh(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);rh[r](e,s,d,i),i+=r}return i}function ah(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);sh[r](e,d,f,i)}s.resetAfterLine()}}dl.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=ih(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=ul.getImagePasses(n,r),f=ul.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)s===8?u=oh(d[h],l,f,i,t,u):ah(d[h],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Gs=y((zS,fl)=>{"use strict";function lh(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function ch(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function uh(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}fl.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?lh(t,l,r,s,a):(o&&ch(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),uh(t,l,r,s,n))),l}});var gl=y((YS,hl)=>{"use strict";var dh=require("util"),js=require("zlib"),pl=Ls(),fh=ol(),ph=qs(),hh=Ws(),gh=Gs(),pe=hl.exports=function(t){pl.call(this),this._parser=new ph(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()};dh.inherits(pe,pl);pe.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};pe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=js.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,js.Z_MIN_CHUNK);this._inflate=js.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};pe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new fh(this._bitmapInfo)};pe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};pe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};pe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};pe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};pe.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};pe.prototype._complete=function(t){if(this.errord)return;let e;try{let n=hh.dataToBitMap(t,this._bitmapInfo);e=gh(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var yl=y((JS,ml)=>{"use strict";var te=_t();ml.exports=function(t,e,n,r){let s=[te.COLORTYPE_COLOR_ALPHA,te.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=te.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=te.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,m,v=o;switch(r.inputColorType){case te.COLORTYPE_COLOR_ALPHA:v=i[u+3],g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_COLOR:g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_ALPHA:v=i[u+1],g=i[u],p=g,m=g;break;case te.COLORTYPE_GRAYSCALE:g=i[u],p=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(v/=o,g=Math.min(Math.max(Math.round((1-v)*f.red+v*g),0),o),p=Math.min(Math.max(Math.round((1-v)*f.green+v*p),0),o),m=Math.min(Math.max(Math.round((1-v)*f.blue+v*m),0),o))),{red:g,green:p,blue:m,alpha:v}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let m=h(i,u);switch(r.colorType){case te.COLORTYPE_COLOR_ALPHA:case te.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,s&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),s&&c.writeUInt16BE(m.alpha,d+6));break;case te.COLORTYPE_ALPHA:case te.COLORTYPE_GRAYSCALE:{let v=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=v,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(v,d),s&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var _l=y((KS,Sl)=>{"use strict";var vl=Bs();function mh(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function yh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function vh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function Sh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function _h(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function bh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function wh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function Ih(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Ah(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-vl(a,l,c);r[s+o]=u}}function Th(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-vl(o,a,l);s+=Math.abs(c)}return s}var xh={0:mh,1:vh,2:_h,3:wh,4:Ah},Ch={0:yh,1:Sh,2:bh,3:Ih,4:Th};Sl.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=Ch[i[h]](t,l,o,s);g<f&&(u=i[h],f=g)}}c[a]=u,a++,xh[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var $s=y((QS,bl)=>{"use strict";var W=_t(),kh=Us(),Eh=yl(),Ph=_l(),Rh=require("zlib"),Re=bl.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||Rh.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:W.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:W.COLORTYPE_COLOR_ALPHA,[W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.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")};Re.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Re.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Re.prototype.filterData=function(t,e,n){let r=Eh(t,e,n,this._options),s=W.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Ph(r,e,n,this._options,s)};Re.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(kh.crc32(r.slice(4,r.length-4)),r.length-4),r};Re.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*W.GAMMA_DIVISION),0),this._packChunk(W.TYPE_gAMA,e)};Re.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(W.TYPE_IHDR,n)};Re.prototype.packIDAT=function(t){return this._packChunk(W.TYPE_IDAT,t)};Re.prototype.packIEND=function(){return this._packChunk(W.TYPE_IEND,null)}});var Tl=y((XS,Al)=>{"use strict";var Mh=require("util"),wl=require("stream"),Lh=_t(),Nh=$s(),Il=Al.exports=function(t){wl.call(this);let e=t||{};this._packer=new Nh(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Mh.inherits(Il,wl);Il.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Lh.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Rl=y((Zt,Pl)=>{"use strict";var xl=require("assert").ok,bt=require("zlib"),Oh=require("util"),Cl=require("buffer").kMaxLength;function Ve(t){if(!(this instanceof Ve))return new Ve(t);t&&t.chunkSize<bt.Z_MIN_CHUNK&&(t.chunkSize=bt.Z_MIN_CHUNK),bt.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 Bh(t){return new Ve(t)}function kl(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ve.prototype._processChunk=function(t,e,n){if(typeof n=="function")return bt.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let m=i-p;if(xl(m>=0,"have should not go down"),m>0){let v=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,v.length>o&&(v=v.slice(0,o)),l.push(v),c+=v.length,o-=v.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=s-g,s=g,!0):!1}xl(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Cl)throw kl(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Cl.toString(16)+" bytes");let h=Buffer.concat(l,c);return kl(this),h};Oh.inherits(Ve,bt.Inflate);function Dh(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=bt.Z_FINISH),t._processChunk(e,n)}function El(t,e){return Dh(new Ve(e),t)}Pl.exports=Zt=El;Zt.Inflate=Ve;Zt.createInflate=Bh;Zt.inflateSync=El});var Vs=y((ZS,Ll)=>{"use strict";var Ml=Ll.exports=function(t){this._buffer=t,this._reads=[]};Ml.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ml.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 Ol=y(Nl=>{"use strict";var Hh=Vs(),Fh=Ds();Nl.process=function(t,e){let n=[],r=new Hh(t);return new Fh(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Fl=y((t_,Hl)=>{"use strict";var Bl=!0,Dl=require("zlib"),Uh=Rl();Dl.deflateSync||(Bl=!1);var qh=Vs(),Wh=Ol(),Gh=qs(),jh=Ws(),$h=Gs();Hl.exports=function(t,e){if(!Bl)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(k){n=k}let s;function i(k){s=k}function o(k){s.transColor=k}function a(k){s.palette=k}function l(){s.alpha=!0}let c;function u(k){c=k}let d=[];function f(k){d.push(k)}let h=new qh(t);if(new Gh(e,{read:h.read.bind(h),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Dl.inflateSync(p);else{let H=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=Uh(p,{chunkSize:H,maxLength:H})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let v=Wh.process(m,s);p=null;let w=jh.dataToBitMap(v,s);v=null;let K=$h(w,s);return s.data=K,s.gamma=c||0,s}});var Gl=y((n_,Wl)=>{"use strict";var Ul=!0,ql=require("zlib");ql.deflateSync||(Ul=!1);var Vh=_t(),zh=$s();Wl.exports=function(t,e){if(!Ul)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new zh(n),s=[];s.push(Buffer.from(Vh.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=ql.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var jl=y(zs=>{"use strict";var Yh=Fl(),Jh=Gl();zs.read=function(t,e){return Yh(t,e||{})};zs.write=function(t,e){return Jh(t,e)}});var zl=y(Vl=>{"use strict";var Kh=require("util"),$l=require("stream"),Qh=gl(),Xh=Tl(),Zh=jl(),j=Vl.PNG=function(t){$l.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 Qh(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 Xh(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"))};Kh.inherits(j,$l);j.sync=Zh;j.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};j.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};j.prototype.write=function(t){return this._parser.write(t),!0};j.prototype.end=function(t){this._parser.end(t)};j.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};j.prototype._gamma=function(t){this.gamma=t};j.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};j.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};j.prototype.bitblt=function(t,e,n,r,s,i,o){return j.bitblt(this,t,e,n,r,s,i,o),this};j.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};j.prototype.adjustGamma=function(){j.adjustGamma(this)}});var en=y(ze=>{function Yl(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}ze.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:Yl(e.color.dark||"#000000ff"),light:Yl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};ze.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};ze.getImageWidth=function(e,n){let r=ze.getScale(e,n);return Math.floor((e+n.margin*2)*r)};ze.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=ze.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[i[g*s+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Jl=y(he=>{var eg=require("fs"),tg=zl().PNG,Ys=en();he.render=function(e,n){let r=Ys.getOptions(n),s=r.rendererOpts,i=Ys.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new tg(s);return Ys.qrToImageData(o.data,e,r),o};he.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),he.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};he.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=he.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};he.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=eg.createWriteStream(e);a.on("error",o),a.on("close",o),he.renderToFileStream(a,n,r)};he.renderToFileStream=function(e,n,r){he.render(n,r).pack().pipe(e)}});var Kl=y(Zn=>{var ng=en(),rg={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},sg={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function ig(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Zn.render=function(t,e,n){let r=ng.getOptions(e),s=rg;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=sg);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
- `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],h=o[(u+1)*i+d];a+=ig(f,h,s)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Zn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Zn.render(n,r);i.writeFile(e,o,s)}});var Xl=y(Ql=>{Ql.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
13
+ `);let o=Yp(e,n,s),a=Xn.getSymbolSize(e),l=new Dp(a);return Gp(l,e),jp(l),$p(l,e),Ps(l,n,0),e>=7&&Vp(l,e),zp(l,o),isNaN(r)&&(r=Rs.getBestMask(l,Ps.bind(null,l,n))),Rs.applyMask(r,l),Ps(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Za.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ks.M,s,i;return typeof n<"u"&&(r=ks.from(n.errorCorrectionLevel,ks.M),s=Qn.from(n.version),i=Rs.from(n.maskPattern),n.toSJISFunc&&Xn.setToSJISFunction(n.toSJISFunc)),Kp(e,s,r,i)}});var Ns=y((US,tl)=>{"use strict";var Qp=require("util"),el=require("stream"),ie=tl.exports=function(){el.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Qp.inherits(ie,el);ie.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))};ie.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};ie.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()))};ie.prototype.destroySoon=ie.prototype.end;ie.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ie.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ie.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))};ie.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};ie.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 Bs=y(Os=>{"use strict";var Pe=[{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]}];Os.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Pe.length;a++){let l=Pe[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Os.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Pe[r].x.length,i=(e-s)/Pe[r].x.length*8+Pe[r].x[s],o=n%Pe[r].y.length,a=(n-o)/Pe[r].y.length*8+Pe[r].y[o];return i*4+a*t*4}}});var Ds=y((WS,nl)=>{"use strict";nl.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Hs=y((GS,sl)=>{"use strict";var Xp=Bs(),Zp=Ds();function rl(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var St=sl.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Xp.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:rl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:rl(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};St.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};St.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};St.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};St.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};St.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Zp(c,l,u);e[o]=a+d}};St.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var al=y((jS,ol)=>{"use strict";var eh=require("util"),il=Ns(),th=Hs(),nh=ol.exports=function(t){il.call(this);let e=[],n=this;this._filter=new th(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};eh.inherits(nh,il)});var _t=y(($S,ll)=>{"use strict";ll.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 qs=y((VS,cl)=>{"use strict";var Fs=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Fs[t]=e}})();var Us=cl.exports=function(){this._crc=-1};Us.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Fs[(this._crc^t[e])&255]^this._crc>>>8;return!0};Us.prototype.crc32=function(){return this._crc^-1};Us.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Fs[(e^t[n])&255]^e>>>8;return e^-1}});var Ws=y((zS,ul)=>{"use strict";var D=_t(),rh=qs(),U=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[D.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[D.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[D.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[D.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[D.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[D.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};U.prototype.start=function(){this.read(D.PNG_SIGNATURE.length,this._parseSignature.bind(this))};U.prototype._parseSignature=function(t){let e=D.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};U.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==D.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new rh,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};U.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};U.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};U.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in D.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=D.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&D.COLORTYPE_PALETTE),color:!!(s&D.COLORTYPE_COLOR),alpha:!!(s&D.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};U.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};U.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};U.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};U.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===D.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===D.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===D.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};U.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};U.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/D.GAMMA_DIVISION),this._handleChunkEnd()};U.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};U.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===D.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};U.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};U.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Gs=y(fl=>{"use strict";var dl=Bs(),sh=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],ih=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function oh(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function ah(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);sh[r](e,s,d,i),i+=r}return i}function lh(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);ih[r](e,d,f,i)}s.resetAfterLine()}}fl.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=oh(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=dl.getImagePasses(n,r),f=dl.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)s===8?u=ah(d[h],l,f,i,t,u):lh(d[h],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var js=y((JS,pl)=>{"use strict";function ch(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function uh(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function dh(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}pl.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?ch(t,l,r,s,a):(o&&uh(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),dh(t,l,r,s,n))),l}});var ml=y((KS,gl)=>{"use strict";var fh=require("util"),$s=require("zlib"),hl=Ns(),ph=al(),hh=Ws(),gh=Gs(),mh=js(),pe=gl.exports=function(t){hl.call(this),this._parser=new hh(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()};fh.inherits(pe,hl);pe.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};pe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=$s.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,$s.Z_MIN_CHUNK);this._inflate=$s.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};pe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new ph(this._bitmapInfo)};pe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};pe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};pe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};pe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};pe.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};pe.prototype._complete=function(t){if(this.errord)return;let e;try{let n=gh.dataToBitMap(t,this._bitmapInfo);e=mh(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var vl=y((QS,yl)=>{"use strict";var te=_t();yl.exports=function(t,e,n,r){let s=[te.COLORTYPE_COLOR_ALPHA,te.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=te.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=te.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,m,v=o;switch(r.inputColorType){case te.COLORTYPE_COLOR_ALPHA:v=i[u+3],g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_COLOR:g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_ALPHA:v=i[u+1],g=i[u],p=g,m=g;break;case te.COLORTYPE_GRAYSCALE:g=i[u],p=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(v/=o,g=Math.min(Math.max(Math.round((1-v)*f.red+v*g),0),o),p=Math.min(Math.max(Math.round((1-v)*f.green+v*p),0),o),m=Math.min(Math.max(Math.round((1-v)*f.blue+v*m),0),o))),{red:g,green:p,blue:m,alpha:v}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let m=h(i,u);switch(r.colorType){case te.COLORTYPE_COLOR_ALPHA:case te.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,s&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),s&&c.writeUInt16BE(m.alpha,d+6));break;case te.COLORTYPE_ALPHA:case te.COLORTYPE_GRAYSCALE:{let v=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=v,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(v,d),s&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var bl=y((XS,_l)=>{"use strict";var Sl=Ds();function yh(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function vh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Sh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function _h(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function bh(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function wh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function Ih(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function Ah(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function xh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-Sl(a,l,c);r[s+o]=u}}function Th(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-Sl(o,a,l);s+=Math.abs(c)}return s}var Ch={0:yh,1:Sh,2:bh,3:Ih,4:xh},kh={0:vh,1:_h,2:wh,3:Ah,4:Th};_l.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=kh[i[h]](t,l,o,s);g<f&&(u=i[h],f=g)}}c[a]=u,a++,Ch[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Vs=y((ZS,wl)=>{"use strict";var G=_t(),Eh=qs(),Ph=vl(),Rh=bl(),Mh=require("zlib"),Re=wl.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||Mh.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:G.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:G.COLORTYPE_COLOR_ALPHA,[G.COLORTYPE_GRAYSCALE,G.COLORTYPE_COLOR,G.COLORTYPE_COLOR_ALPHA,G.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([G.COLORTYPE_GRAYSCALE,G.COLORTYPE_COLOR,G.COLORTYPE_COLOR_ALPHA,G.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")};Re.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Re.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Re.prototype.filterData=function(t,e,n){let r=Ph(t,e,n,this._options),s=G.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Rh(r,e,n,this._options,s)};Re.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(Eh.crc32(r.slice(4,r.length-4)),r.length-4),r};Re.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*G.GAMMA_DIVISION),0),this._packChunk(G.TYPE_gAMA,e)};Re.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(G.TYPE_IHDR,n)};Re.prototype.packIDAT=function(t){return this._packChunk(G.TYPE_IDAT,t)};Re.prototype.packIEND=function(){return this._packChunk(G.TYPE_IEND,null)}});var Tl=y((e_,xl)=>{"use strict";var Lh=require("util"),Il=require("stream"),Nh=_t(),Oh=Vs(),Al=xl.exports=function(t){Il.call(this);let e=t||{};this._packer=new Oh(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Lh.inherits(Al,Il);Al.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Nh.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Ml=y((Xt,Rl)=>{"use strict";var Cl=require("assert").ok,bt=require("zlib"),Bh=require("util"),kl=require("buffer").kMaxLength;function Ve(t){if(!(this instanceof Ve))return new Ve(t);t&&t.chunkSize<bt.Z_MIN_CHUNK&&(t.chunkSize=bt.Z_MIN_CHUNK),bt.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 Dh(t){return new Ve(t)}function El(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ve.prototype._processChunk=function(t,e,n){if(typeof n=="function")return bt.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let m=i-p;if(Cl(m>=0,"have should not go down"),m>0){let v=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,v.length>o&&(v=v.slice(0,o)),l.push(v),c+=v.length,o-=v.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=s-g,s=g,!0):!1}Cl(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=kl)throw El(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+kl.toString(16)+" bytes");let h=Buffer.concat(l,c);return El(this),h};Bh.inherits(Ve,bt.Inflate);function Hh(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=bt.Z_FINISH),t._processChunk(e,n)}function Pl(t,e){return Hh(new Ve(e),t)}Rl.exports=Xt=Pl;Xt.Inflate=Ve;Xt.createInflate=Dh;Xt.inflateSync=Pl});var zs=y((t_,Nl)=>{"use strict";var Ll=Nl.exports=function(t){this._buffer=t,this._reads=[]};Ll.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ll.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 Bl=y(Ol=>{"use strict";var Fh=zs(),Uh=Hs();Ol.process=function(t,e){let n=[],r=new Fh(t);return new Uh(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Ul=y((r_,Fl)=>{"use strict";var Dl=!0,Hl=require("zlib"),qh=Ml();Hl.deflateSync||(Dl=!1);var Wh=zs(),Gh=Bl(),jh=Ws(),$h=Gs(),Vh=js();Fl.exports=function(t,e){if(!Dl)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(x){n=x}let s;function i(x){s=x}function o(x){s.transColor=x}function a(x){s.palette=x}function l(){s.alpha=!0}let c;function u(x){c=x}let d=[];function f(x){d.push(x)}let h=new Wh(t);if(new jh(e,{read:h.read.bind(h),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Hl.inflateSync(p);else{let N=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=qh(p,{chunkSize:N,maxLength:N})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let v=Gh.process(m,s);p=null;let b=$h.dataToBitMap(v,s);v=null;let W=Vh(b,s);return s.data=W,s.gamma=c||0,s}});var jl=y((s_,Gl)=>{"use strict";var ql=!0,Wl=require("zlib");Wl.deflateSync||(ql=!1);var zh=_t(),Yh=Vs();Gl.exports=function(t,e){if(!ql)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new Yh(n),s=[];s.push(Buffer.from(zh.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=Wl.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var $l=y(Ys=>{"use strict";var Jh=Ul(),Kh=jl();Ys.read=function(t,e){return Jh(t,e||{})};Ys.write=function(t,e){return Kh(t,e)}});var Yl=y(zl=>{"use strict";var Qh=require("util"),Vl=require("stream"),Xh=ml(),Zh=Tl(),eg=$l(),$=zl.PNG=function(t){Vl.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 Xh(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 Zh(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"))};Qh.inherits($,Vl);$.sync=eg;$.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)};$.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};$.prototype.write=function(t){return this._parser.write(t),!0};$.prototype.end=function(t){this._parser.end(t)};$.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};$.prototype._gamma=function(t){this.gamma=t};$.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};$.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};$.prototype.bitblt=function(t,e,n,r,s,i,o){return $.bitblt(this,t,e,n,r,s,i,o),this};$.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};$.prototype.adjustGamma=function(){$.adjustGamma(this)}});var Zt=y(ze=>{function Jl(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}ze.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:Jl(e.color.dark||"#000000ff"),light:Jl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};ze.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};ze.getImageWidth=function(e,n){let r=ze.getScale(e,n);return Math.floor((e+n.margin*2)*r)};ze.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=ze.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[i[g*s+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Kl=y(he=>{var tg=require("fs"),ng=Yl().PNG,Js=Zt();he.render=function(e,n){let r=Js.getOptions(n),s=r.rendererOpts,i=Js.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new ng(s);return Js.qrToImageData(o.data,e,r),o};he.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),he.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};he.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=he.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};he.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=tg.createWriteStream(e);a.on("error",o),a.on("close",o),he.renderToFileStream(a,n,r)};he.renderToFileStream=function(e,n,r){he.render(n,r).pack().pipe(e)}});var Ql=y(Zn=>{var rg=Zt(),sg={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},ig={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function og(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Zn.render=function(t,e,n){let r=rg.getOptions(e),s=sg;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=ig);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
+ `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],h=o[(u+1)*i+d];a+=og(f,h,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Zn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Zn.render(n,r);i.writeFile(e,o,s)}});var Zl=y(Xl=>{Xl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
16
16
  `;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=s[u*r+d]?i:o;a+=c+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var nc=y(tc=>{var og="\x1B[47m",ag="\x1B[40m",Js="\x1B[37m",Ks="\x1B[30m",Ye="\x1B[0m",lg=og+Ks,cg=ag+Js,ug=function(t,e,n){return{"00":Ye+" "+t,"01":Ye+e+"\u2584"+t,"02":Ye+n+"\u2584"+t,10:Ye+e+"\u2580"+t,11:" ",12:"\u2584",20:Ye+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Zl=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},ec=function(t,e,n,r){return Zl(t,e,n,r)+Zl(t,e,n,r+1)};tc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?cg:lg,c=ug(o,i?Ks:Js,i?Js:Ks),u=Ye+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[ec(s,r,h,f)];d+=c[ec(s,r,r,f)]+u}return d+=Ye,typeof n=="function"&&n(null,d),d}});var sc=y(rc=>{var dg=Xl(),fg=nc();rc.render=function(t,e,n){return e&&e.small?fg.render(t,e,n):dg.render(t,e,n)}});var Xs=y(oc=>{var pg=en();function ic(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Qs(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function hg(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?Qs("M",l+n,.5+c+n):Qs("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=Qs("h",o),o=0)):s++}return r}oc.render=function(e,n,r){let s=pg.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+ic(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+ic(s.color.dark,"stroke")+' d="'+hg(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
- `;return typeof r=="function"&&r(null,f),f}});var ac=y(er=>{var gg=Xs();er.render=gg.render;er.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+er.render(n,r);i.writeFile(e,a,s)}});var lc=y(tr=>{var Zs=en();function mg(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 yg(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}tr.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=yg()),s=Zs.getOptions(s);let o=Zs.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Zs.qrToImageData(l.data,e,s),mg(a,i,o),a.putImageData(l,0,0),i};tr.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=tr.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var uc=y(tn=>{var vg=ps(),ei=Ms(),cc=lc(),Sg=Xs();function ti(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!vg())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=ei.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=ei.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}tn.create=ei.create;tn.toCanvas=ti.bind(null,cc.render);tn.toDataURL=ti.bind(null,cc.renderToDataURL);tn.toString=ti.bind(null,function(t,e,n){return Sg.render(t,n)})});var hc=y(Me=>{var dc=ps(),ni=Ms(),_g=Jl(),fc=Kl(),bg=sc(),pc=ac();function nn(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(dc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function wg(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function nr(t){switch(t){case"svg":return pc;case"txt":case"utf8":return fc;case"png":case"image/png":default:return _g}}function Ig(t){switch(t){case"svg":return pc;case"terminal":return bg;case"utf8":default:return fc}}function rn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=ni.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=ni.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Me.create=ni.create;Me.toCanvas=uc().toCanvas;Me.toString=function(e,n,r){let s=nn(e,n,r),i=s.opts?s.opts.type:void 0,o=Ig(i);return rn(o.render,e,s)};Me.toDataURL=function(e,n,r){let s=nn(e,n,r),i=nr(s.opts.type);return rn(i.renderToDataURL,e,s)};Me.toBuffer=function(e,n,r){let s=nn(e,n,r),i=nr(s.opts.type);return rn(i.renderToBuffer,e,s)};Me.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!dc())throw new Error("Too few arguments provided");let i=nn(n,r,s),o=i.opts.type||wg(e),l=nr(o).renderToFile.bind(null,e);return rn(l,n,i)};Me.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=nn(n,r,e.emit.bind(e,"error")),o=nr("png").renderToFileStream.bind(null,e);rn(o,n,s)}});var mc=y((m_,gc)=>{gc.exports=hc()});var xd=require("http");var ip=ot(Xo(),1),op=ot(ts(),1),ap=ot(ss(),1),lp=ot(qn(),1),fs=ot(aa(),1);var re=require("fs/promises"),Cd=require("crypto"),kn=require("path"),kd=require("os"),to=ot(mc(),1);var Je=require("child_process"),on=require("fs"),x=require("path"),an=require("os");var ur=require("fs");var yc=require("os"),G=require("path"),we=(0,G.join)((0,yc.homedir)(),".vibelet"),rr=(0,G.join)(we,"logs"),sr=(0,G.join)(we,"data"),Ag=(0,G.join)(we,"runtime"),y_=(0,G.join)(Ag,"current"),vc=(0,G.join)(we,"identity.json"),Sc=(0,G.join)(we,"pairings.json"),_c=(0,G.join)(sr,"push-subscriptions.json"),ir=(0,G.join)(sr,"sessions.json"),wt=(0,G.join)(sr,"audit.jsonl"),ri=(0,G.join)(sr,"uploads"),or=(0,G.join)(rr,"daemon.stdout.log"),ar=(0,G.join)(rr,"daemon.stderr.log"),bc=(0,G.join)(we,"update-check.json"),si=(0,G.join)(we,"pairing-qr.png");var lr={stdout:!1,stderr:!1};function wc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Tg(t){return!t.destroyed&&t.writable!==!1}function Ic(t,e){if(lr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Tg(n))return lr[t]=!0,!1;try{return n.write(e,r=>{wc(r)&&(lr[t]=!0)}),!0}catch(r){return wc(r)&&(lr[t]=!0),!1}}function It(t){return Ic("stdout",t)}function cr(t){return Ic("stderr",t)}var Ac={debug:10,info:20,warn:30,error:40},xg=process.env.VIBE_LOG_LEVEL||"info";function Cg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function kg(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var xc=!Cg()&&!kg();if(xc)try{(0,ur.mkdirSync)(rr,{recursive:!0})}catch{}function Tc(t,e,n){if(Ac[t]<Ac[xg])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?cr(s+`
18
+ `,typeof n=="function"&&n(null,a),a}});var rc=y(nc=>{var ag="\x1B[47m",lg="\x1B[40m",Ks="\x1B[37m",Qs="\x1B[30m",Ye="\x1B[0m",cg=ag+Qs,ug=lg+Ks,dg=function(t,e,n){return{"00":Ye+" "+t,"01":Ye+e+"\u2584"+t,"02":Ye+n+"\u2584"+t,10:Ye+e+"\u2580"+t,11:" ",12:"\u2584",20:Ye+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},ec=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},tc=function(t,e,n,r){return ec(t,e,n,r)+ec(t,e,n,r+1)};nc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?ug:cg,c=dg(o,i?Qs:Ks,i?Ks:Qs),u=Ye+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[tc(s,r,h,f)];d+=c[tc(s,r,r,f)]+u}return d+=Ye,typeof n=="function"&&n(null,d),d}});var ic=y(sc=>{var fg=Zl(),pg=rc();sc.render=function(t,e,n){return e&&e.small?pg.render(t,e,n):fg.render(t,e,n)}});var Zs=y(ac=>{var hg=Zt();function oc(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Xs(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function gg(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?Xs("M",l+n,.5+c+n):Xs("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=Xs("h",o),o=0)):s++}return r}ac.render=function(e,n,r){let s=hg.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+oc(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+oc(s.color.dark,"stroke")+' d="'+gg(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
+ `;return typeof r=="function"&&r(null,f),f}});var lc=y(er=>{var mg=Zs();er.render=mg.render;er.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+er.render(n,r);i.writeFile(e,a,s)}});var cc=y(tr=>{var ei=Zt();function yg(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 vg(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}tr.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=vg()),s=ei.getOptions(s);let o=ei.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ei.qrToImageData(l.data,e,s),yg(a,i,o),a.putImageData(l,0,0),i};tr.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=tr.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var dc=y(en=>{var Sg=hs(),ti=Ls(),uc=cc(),_g=Zs();function ni(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Sg())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=ti.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=ti.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}en.create=ti.create;en.toCanvas=ni.bind(null,uc.render);en.toDataURL=ni.bind(null,uc.renderToDataURL);en.toString=ni.bind(null,function(t,e,n){return _g.render(t,n)})});var gc=y(Me=>{var fc=hs(),ri=Ls(),bg=Kl(),pc=Ql(),wg=ic(),hc=lc();function tn(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(fc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Ig(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function nr(t){switch(t){case"svg":return hc;case"txt":case"utf8":return pc;case"png":case"image/png":default:return bg}}function Ag(t){switch(t){case"svg":return hc;case"terminal":return wg;case"utf8":default:return pc}}function nn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=ri.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=ri.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Me.create=ri.create;Me.toCanvas=dc().toCanvas;Me.toString=function(e,n,r){let s=tn(e,n,r),i=s.opts?s.opts.type:void 0,o=Ag(i);return nn(o.render,e,s)};Me.toDataURL=function(e,n,r){let s=tn(e,n,r),i=nr(s.opts.type);return nn(i.renderToDataURL,e,s)};Me.toBuffer=function(e,n,r){let s=tn(e,n,r),i=nr(s.opts.type);return nn(i.renderToBuffer,e,s)};Me.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!fc())throw new Error("Too few arguments provided");let i=tn(n,r,s),o=i.opts.type||Ig(e),l=nr(o).renderToFile.bind(null,e);return nn(l,n,i)};Me.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=tn(n,r,e.emit.bind(e,"error")),o=nr("png").renderToFileStream.bind(null,e);nn(o,n,s)}});var yc=y((v_,mc)=>{mc.exports=gc()});var Cd=require("http");var op=ot(Zo(),1),ap=ot(ns(),1),lp=ot(is(),1),cp=ot(qn(),1),ps=ot(la(),1);var re=require("fs/promises"),kd=require("crypto"),kn=require("path"),Ed=require("os"),no=ot(yc(),1);var Je=require("child_process"),on=require("fs"),C=require("path"),an=require("os");var ur=require("fs");var vc=require("os"),j=require("path"),we=(0,j.join)((0,vc.homedir)(),".vibelet"),rr=(0,j.join)(we,"logs"),sr=(0,j.join)(we,"data"),xg=(0,j.join)(we,"runtime"),S_=(0,j.join)(xg,"current"),Sc=(0,j.join)(we,"identity.json"),_c=(0,j.join)(we,"pairings.json"),bc=(0,j.join)(sr,"push-subscriptions.json"),ir=(0,j.join)(sr,"sessions.json"),wt=(0,j.join)(sr,"audit.jsonl"),si=(0,j.join)(sr,"uploads"),or=(0,j.join)(rr,"daemon.stdout.log"),ar=(0,j.join)(rr,"daemon.stderr.log"),wc=(0,j.join)(we,"update-check.json"),ii=(0,j.join)(we,"pairing-qr.png");var lr={stdout:!1,stderr:!1};function Ic(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Tg(t){return!t.destroyed&&t.writable!==!1}function Ac(t,e){if(lr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Tg(n))return lr[t]=!0,!1;try{return n.write(e,r=>{Ic(r)&&(lr[t]=!0)}),!0}catch(r){return Ic(r)&&(lr[t]=!0),!1}}function It(t){return Ac("stdout",t)}function cr(t){return Ac("stderr",t)}var xc={debug:10,info:20,warn:30,error:40},Cg=process.env.VIBE_LOG_LEVEL||"info";function kg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Eg(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Cc=!kg()&&!Eg();if(Cc)try{(0,ur.mkdirSync)(rr,{recursive:!0})}catch{}function Tc(t,e,n){if(xc[t]<xc[Cg])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?cr(s+`
21
21
  `):It(s+`
22
- `),xc){let i=t==="error"||t==="warn"?ar:or;try{(0,ur.appendFileSync)(i,s+`
23
- `)}catch{}}}function Cc(t={}){function e(n,r,s){typeof r=="string"?Tc(n,t,r):Tc(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Cc({...t,...n})}}var R=Cc({module:"daemon"});var Eg=["fnm_multishells"],Pg=6e4,Le=process.platform==="win32",Rg=R.child({module:"config"});function ge(t){return Eg.some(e=>t.includes(e))}function Mg(t){if(!t||!ge(t))return t;try{let e=(0,x.join)((0,on.realpathSync)((0,x.dirname)(t)),(0,x.basename)(t));if((0,on.existsSync)(e)&&!ge(e))return e}catch{}return t}function ai(){return Le?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var At=null;function Ec(){if(At&&!ge(At.PATH??""))return At;for(let t of ai())try{let e=(0,Je.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
- `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return ge(n.PATH??"")?At=null:At=n,n}catch{}return At={},{}}function Lg(t=Ec()){let e=(0,an.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Le?(0,x.join)(e,"pnpm"):(0,x.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Le?[(0,x.join)(e,".npm-global","bin"),(0,x.join)(e,".local","bin"),(0,x.join)(e,".claude","bin"),n,(0,x.join)(e,"AppData","Roaming","npm"),(0,x.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,x.join)(e,".npm-global","bin"),(0,x.join)(e,".local","bin"),(0,x.join)(e,".claude","bin"),n],i=r.split(x.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(x.delimiter)}function ii(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function oi(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Ke(){let t=Ec(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=Lg(t),e.HOME||(e.HOME=(0,an.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function li(t){if(Le)try{let n=(0,Je.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function sn(t,e=3e3){try{return(0,Je.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Ke(),...Le?{shell:!0}:{}}).trim()||null}catch{return null}}function Ng(t){for(let e of ai())try{let n=(0,Je.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Og(){let t=(0,an.homedir)();return[(0,x.join)(t,".local","bin","claude"),(0,x.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,x.join)(t,".npm-global","bin","claude")]}function Bg(){if(Le){let t=li("claude");return t&&sn(t)?t:void 0}for(let t of Og())if(sn(t))return t;try{let t=(0,Je.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Ke()}).trim();if(t&&!t.includes("cmux")&&sn(t))return t}catch{}}function Dg(){let t=(0,an.homedir)(),e=[process.env.PNPM_HOME,(0,x.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,x.join)(t,".npm-global","bin","codex"),(0,x.join)(t,".local","bin","codex"),...e.map(n=>(0,x.join)(n,"codex"))]}function Hg(){if(Le){let s=li("codex");return s&&sn(s)?s:void 0}let t=s=>{let i=Mg(s);return sn(i)?i:void 0},e;for(let s of Dg()){let i=t(s);if(i){if(!ge(i))return i;e=i}}try{let s=(0,Je.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Ke()}).trim(),i=s?t(s):void 0;if(i){if(!ge(i))return i;e=e??i}}catch{}let n=Ng("codex"),r=n?t(n):void 0;if(r){if(!ge(r))return r;e=e??r}return e}function Pc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>Pg||!(0,on.existsSync)(n)||ge(n)){let o=t();n=o??e,r=i,Rg.info({name:e,path:n,transient:ge(n),isBare:o==null},"binary resolved")}return n}}var Fg=Pc(Bg,"claude"),Ug=Pc(Hg,"codex");function qg(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var kc=qg();function Wg(t,e){if(Le)return{command:li(t)??t,args:e};let n=ai()[0]??"/bin/zsh",r=`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",r,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:kc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:kc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:oi("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:oi("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:ii("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:ii("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:ii("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:oi("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return Fg()},get codexPath(){return Ug()},isTransientPath:ge,execViaLoginShell:Wg,buildSanitizedEnv:Ke};var ji=require("crypto"),od=require("fs/promises");var Fc=require("child_process"),Uc=require("fs");var dr=require("fs"),Lc=require("path");var $=require("fs");function Gg(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function ln(t,e){if(!(0,$.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,$.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=Gg(r,e.maxBytes,s,e.retainBytes),o=(0,$.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,$.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,$.ftruncateSync)(o,0),a.length>0&&(0,$.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,$.closeSync)(o)}}function Rc(t){let e=[ln(t.auditPath,{maxBytes:t.auditMaxBytes}),ln(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),ln(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Mc=!1,jg=new Set(["ts","event","source","appEvent","level"]);function $g(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Vg(t={}){let e={};for(let[n,r]of Object.entries(t))jg.has(n)||(e[n]=r);return e}function zg(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Vg(n)}}function Yg(){Mc||((0,dr.mkdirSync)((0,Lc.dirname)(wt),{recursive:!0}),Mc=!0)}var ci=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(zg(e,n,r,s))}write(e){if(!$g()){Yg();try{let n=JSON.stringify(e)+`
25
- `;ln(wt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,dr.appendFileSync)(wt,n)}catch{}}}},I=new ci;var Ne=require("fs"),Nc=require("os"),cn=require("path"),Oc=require("crypto"),ui="claude-hook:",un="x-vibelet-claude-hook-secret",dn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Jg(t,e){return`#!/usr/bin/env node
22
+ `),Cc){let i=t==="error"||t==="warn"?ar:or;try{(0,ur.appendFileSync)(i,s+`
23
+ `)}catch{}}}function kc(t={}){function e(n,r,s){typeof r=="string"?Tc(n,t,r):Tc(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>kc({...t,...n})}}var R=kc({module:"daemon"});var Pg=["fnm_multishells"],Rg=6e4,Le=process.platform==="win32",Mg=R.child({module:"config"});function ge(t){return Pg.some(e=>t.includes(e))}function Lg(t){if(!t||!ge(t))return t;try{let e=(0,C.join)((0,on.realpathSync)((0,C.dirname)(t)),(0,C.basename)(t));if((0,on.existsSync)(e)&&!ge(e))return e}catch{}return t}function li(){return Le?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var rn=null;function Pc(){if(rn&&rn.PATH&&!ge(rn.PATH))return rn;for(let t of li())try{let e=(0,Je.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
+ `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return n.PATH&&!ge(n.PATH)&&(rn=n),n}catch{}return{}}function Ng(t=Pc()){let e=(0,an.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Le?(0,C.join)(e,"pnpm"):(0,C.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Le?[(0,C.join)(e,".npm-global","bin"),(0,C.join)(e,".local","bin"),(0,C.join)(e,".claude","bin"),n,(0,C.join)(e,"AppData","Roaming","npm"),(0,C.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,C.join)(e,".npm-global","bin"),(0,C.join)(e,".local","bin"),(0,C.join)(e,".claude","bin"),n],i=r.split(C.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(C.delimiter)}function oi(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function ai(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Ke(){let t=Pc(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=Ng(t),e.HOME||(e.HOME=(0,an.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function ci(t){if(Le)try{let n=(0,Je.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function sn(t,e=3e3){try{return(0,Je.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Ke(),...Le?{shell:!0}:{}}).trim()||null}catch{return null}}function Og(t){for(let e of li())try{let n=(0,Je.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Bg(){let t=(0,an.homedir)();return[(0,C.join)(t,".local","bin","claude"),(0,C.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,C.join)(t,".npm-global","bin","claude")]}function Dg(){if(Le){let t=ci("claude");return t&&sn(t)?t:void 0}for(let t of Bg())if(sn(t))return t;try{let t=(0,Je.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Ke()}).trim();if(t&&!t.includes("cmux")&&sn(t))return t}catch{}}function Hg(){let t=(0,an.homedir)(),e=[process.env.PNPM_HOME,(0,C.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,C.join)(t,".npm-global","bin","codex"),(0,C.join)(t,".local","bin","codex"),...e.map(n=>(0,C.join)(n,"codex"))]}function Fg(){if(Le){let s=ci("codex");return s&&sn(s)?s:void 0}let t=s=>{let i=Lg(s);return sn(i)?i:void 0},e;for(let s of Hg()){let i=t(s);if(i){if(!ge(i))return i;e=i}}try{let s=(0,Je.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Ke()}).trim(),i=s?t(s):void 0;if(i){if(!ge(i))return i;e=e??i}}catch{}let n=Og("codex"),r=n?t(n):void 0;if(r){if(!ge(r))return r;e=e??r}return e}function Rc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>Rg||!(0,on.existsSync)(n)||ge(n)){let o=t();n=o??e,r=i,Mg.info({name:e,path:n,transient:ge(n),isBare:o==null},"binary resolved")}return n}}var Ug=Rc(Dg,"claude"),qg=Rc(Fg,"codex");function Wg(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var Ec=Wg();function Gg(t,e){if(Le)return{command:ci(t)??t,args:e};let n=li()[0]??"/bin/zsh",r=`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",r,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:Ec.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:Ec["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:ai("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:ai("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:oi("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:oi("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:oi("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:ai("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return Ug()},get codexPath(){return qg()},isTransientPath:ge,execViaLoginShell:Gg,buildSanitizedEnv:Ke};var $i=require("crypto"),ad=require("fs/promises");var Uc=require("child_process"),qc=require("fs");var dr=require("fs"),Nc=require("path");var V=require("fs");function jg(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function ln(t,e){if(!(0,V.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,V.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=jg(r,e.maxBytes,s,e.retainBytes),o=(0,V.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,V.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,V.ftruncateSync)(o,0),a.length>0&&(0,V.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,V.closeSync)(o)}}function Mc(t){let e=[ln(t.auditPath,{maxBytes:t.auditMaxBytes}),ln(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),ln(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Lc=!1,$g=new Set(["ts","event","source","appEvent","level"]);function Vg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function zg(t={}){let e={};for(let[n,r]of Object.entries(t))$g.has(n)||(e[n]=r);return e}function Yg(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...zg(n)}}function Jg(){Lc||((0,dr.mkdirSync)((0,Nc.dirname)(wt),{recursive:!0}),Lc=!0)}var ui=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(Yg(e,n,r,s))}write(e){if(!Vg()){Jg();try{let n=JSON.stringify(e)+`
25
+ `;ln(wt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,dr.appendFileSync)(wt,n)}catch{}}}},I=new ui;var Ne=require("fs"),Oc=require("os"),cn=require("path"),Bc=require("crypto"),di="claude-hook:",un="x-vibelet-claude-hook-secret",dn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Kg(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 Kg(t,e){return`#!/usr/bin/env node
46
+ `}function Qg(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
48
  const fallback = ${JSON.stringify(JSON.stringify(dn))};
49
49
  const chunks = [];
@@ -79,43 +79,43 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function Bc(t,e){let n=(0,cn.join)((0,Nc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Oc.randomUUID)()}`);(0,Ne.mkdirSync)(n,{recursive:!0});let r=(0,cn.join)(n,"settings.json"),s=(0,cn.join)(n,"session_hook_forwarder.cjs"),i=(0,cn.join)(n,"permission_hook_forwarder.cjs");return(0,Ne.writeFileSync)(s,Jg(t,e),"utf8"),(0,Ne.writeFileSync)(i,Kg(t,e),"utf8"),(0,Ne.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function fr(t){if(t)try{(0,Ne.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var ne=R.child({module:"claude"}),qc="claude-permission-denial:",Qg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Xg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function di(t){Xg()&&cr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
- `)}function Zg(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
84
- `):""}function em(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function tm(t){if(typeof t=="string")return t;let e=Zg(t);return e||(em(t)?"":JSON.stringify(t))}function nm(t){return/requested permissions|haven't granted/i.test(t)}function Dc(t){return t.replace(Qg,"").replace(/\s+/g," ").trim()}function rm(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function sm(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 im(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Hc(t){let e=Dc(t.resultText??""),n=(t.stderrLines??[]).map(Dc).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&sm(i));if(r)return im(r);let s=[e,...n].find(i=>!!i&&!rm(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function pr(t){return t.startsWith(qc)}var fn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ne.info({sessionId:this.sessionId,cwd:e},"session initialized"),I.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),fr(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Bc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ne.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),di(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=r;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",r);o=c.command,a=c.args}else o=i;this.proc=(0,Fc.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Uc.existsSync)(this.cwd)&&(u=`Working directory does not exist: ${this.cwd}`),ne.error({sessionId:this.sessionId,error:u,cwd:this.cwd},"spawn error"),I.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:u}),this.handler?.({type:"error",sessionId:this.sessionId,message:u})}),this.buffer="",this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
85
- `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ne.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(ne.debug({sessionId:this.sessionId,stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(c,u)=>{ne.info({sessionId:this.sessionId,exitCode:c,signal:u},"process exited");let d=this.interrupted;this.proc=null,fr(this.hookFiles),this.hookFiles=null,this.interrupted=!1,d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ne.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Hc({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ne.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ne.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
86
- `),!0}setApprovalMode(e){this.approvalMode=e,ne.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ne.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,fr(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(ne.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),I.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=tm(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&nm(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){di("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Hc({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${qc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;di("Claude finished. Run `claude --continue` to continue on desktop."),I.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 $c=require("child_process"),Vc=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 r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();R.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},_=new fi;var Wc=require("node:fs"),pi=require("node:path"),om="@vibelet/cli";function am(t){try{let e=JSON.parse((0,Wc.readFileSync)(t,"utf8"));if(e.name===om&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function lm(){return"1.0.9"}var Tt=lm();var C=R.child({module:"codex"});function cm(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 um(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 V(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function P(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var dm=new Set(["aborted","interrupted","cancelled","canceled"]);function fm(t){let e=P(t);return e?e.toLowerCase():null}function pm(t){let e=P(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function hi(t){return t?P(t.itemId)??P(t.id)??P(t.callId)??P(t.call_id):null}function gi(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function zc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Yc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function hm(t){if(!Array.isArray(t))return null;for(let e of t){let n=V(e);if(!n)continue;let r=P(n.id),s=Array.isArray(n.options)?n.options.map(l=>V(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>P(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>zc(l))??i[0],a=i.find(l=>Yc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function gm(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>V(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>V(o)).filter(o=>!!o).map(o=>P(o.label)).filter(o=>!!o)),n=e.some(s=>zc(s)),r=e.some(s=>Yc(s));return n&&r}function Gc(t){let e=pm(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=P(t.server),r=P(t.tool)??P(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:V(t.arguments)??V(t.input)??{}}:null}return null}function mm(t){if(!Array.isArray(t))return"";for(let e of t){let n=V(e);if(!n)continue;let r=P(n.question)??P(n.header);if(r)return r}return""}function jc(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 pn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)||s==="codex"){let u=S.execViaLoginShell("codex",o);i=u.command,o=u.args,C.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,C.info({spawnCmd:i,args:o},"spawning");I.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,$c.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let d=u.message;u.code==="ENOENT"&&e&&!(0,Vc.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),C.error({error:d,cwd:e},"spawn error"),I.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",u=>{this.buffer+=u.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{C.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let d=u.toString().trim();d&&(C.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",u=>{C.info({threadId:this.threadId,exitCode:u},"process exited"),u&&u!==0&&C.error({threadId:this.threadId,exitCode:u,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 ${u}`));this.pending.clear(),this.exitHandler?.(u),u&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${u}`})});let l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Tt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let c=jc(this.approvalMode,e);if(n){let u=await this.rpc("thread/resume",{threadId:n,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,persistExtendedHistory:!0});this.threadId=u?.thread?.id??n,C.info({threadId:this.threadId},"thread resumed"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let u=await this.rpc("thread/start",{cwd:e,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=u?.thread?.id??u?.threadId??"",C.info({threadId:this.threadId},"thread created"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=jc(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,C.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{C.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,C.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return C.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
- `),!0}restorePendingApproval(e){let n=um(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,C.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
89
- `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),C.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
82
+ `}function Dc(t,e){let n=(0,cn.join)((0,Oc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Bc.randomUUID)()}`);(0,Ne.mkdirSync)(n,{recursive:!0});let r=(0,cn.join)(n,"settings.json"),s=(0,cn.join)(n,"session_hook_forwarder.cjs"),i=(0,cn.join)(n,"permission_hook_forwarder.cjs");return(0,Ne.writeFileSync)(s,Kg(t,e),"utf8"),(0,Ne.writeFileSync)(i,Qg(t,e),"utf8"),(0,Ne.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function fr(t){if(t)try{(0,Ne.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var ne=R.child({module:"claude"}),Wc="claude-permission-denial:",Xg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Zg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function fi(t){Zg()&&cr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
+ `)}function em(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
84
+ `):""}function tm(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function nm(t){if(typeof t=="string")return t;let e=em(t);return e||(tm(t)?"":JSON.stringify(t))}function rm(t){return/requested permissions|haven't granted/i.test(t)}function Hc(t){return t.replace(Xg,"").replace(/\s+/g," ").trim()}function sm(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function im(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 om(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Fc(t){let e=Hc(t.resultText??""),n=(t.stderrLines??[]).map(Hc).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&im(i));if(r)return om(r);let s=[e,...n].find(i=>!!i&&!sm(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function pr(t){return t.startsWith(Wc)}var fn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ne.info({sessionId:this.sessionId,cwd:e},"session initialized"),I.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),fr(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Dc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ne.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),fi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=r;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",r);o=c.command,a=c.args}else o=i;this.proc=(0,Uc.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&this.cwd&&!(0,qc.existsSync)(this.cwd)&&(u=`Working directory does not exist: ${this.cwd}`),ne.error({sessionId:this.sessionId,error:u,cwd:this.cwd},"spawn error"),I.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:u}),this.handler?.({type:"error",sessionId:this.sessionId,message:u})}),this.buffer="",this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
85
+ `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ne.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(ne.debug({sessionId:this.sessionId,stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(c,u)=>{ne.info({sessionId:this.sessionId,exitCode:c,signal:u},"process exited");let d=this.interrupted;this.proc=null,fr(this.hookFiles),this.hookFiles=null,this.interrupted=!1,d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ne.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Fc({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ne.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ne.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
86
+ `),!0}setApprovalMode(e){this.approvalMode=e,ne.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ne.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,fr(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(ne.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),I.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=nm(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&rm(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){fi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Fc({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Wc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;fi("Claude finished. Run `claude --continue` to continue on desktop."),I.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 Vc=require("child_process"),zc=require("fs");var pi=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();R.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},_=new pi;var Gc=require("node:fs"),hi=require("node:path"),am="@vibelet/cli";function lm(t){try{let e=JSON.parse((0,Gc.readFileSync)(t,"utf8"));if(e.name===am&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function cm(){return"1.0.10"}var At=cm();var k=R.child({module:"codex"});function um(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 dm(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function z(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function P(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var fm=new Set(["aborted","interrupted","cancelled","canceled"]);function pm(t){let e=P(t);return e?e.toLowerCase():null}function hm(t){let e=P(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function gi(t){return t?P(t.itemId)??P(t.id)??P(t.callId)??P(t.call_id):null}function mi(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Yc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Jc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function gm(t){if(!Array.isArray(t))return null;for(let e of t){let n=z(e);if(!n)continue;let r=P(n.id),s=Array.isArray(n.options)?n.options.map(l=>z(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>P(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Yc(l))??i[0],a=i.find(l=>Jc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function mm(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>z(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>z(o)).filter(o=>!!o).map(o=>P(o.label)).filter(o=>!!o)),n=e.some(s=>Yc(s)),r=e.some(s=>Jc(s));return n&&r}function jc(t){let e=hm(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:mi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:mi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=P(t.server),r=P(t.tool)??P(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:z(t.arguments)??z(t.input)??{}}:null}return null}function ym(t){if(!Array.isArray(t))return"";for(let e of t){let n=z(e);if(!n)continue;let r=P(n.question)??P(n.header);if(r)return r}return""}function $c(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 pn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)||s==="codex"){let u=S.execViaLoginShell("codex",o);i=u.command,o=u.args,k.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,k.info({spawnCmd:i,args:o},"spawning");I.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Vc.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let d=u.message;u.code==="ENOENT"&&e&&!(0,zc.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),k.error({error:d,cwd:e},"spawn error"),I.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",u=>{this.buffer+=u.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{k.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let d=u.toString().trim();d&&(k.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",u=>{k.info({threadId:this.threadId,exitCode:u},"process exited"),u&&u!==0&&k.error({threadId:this.threadId,exitCode:u,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 ${u}`));this.pending.clear(),this.exitHandler?.(u),u&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${u}`})});let l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:At},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let c=$c(this.approvalMode,e);if(n){let u=await this.rpc("thread/resume",{threadId:n,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,persistExtendedHistory:!0});this.threadId=u?.thread?.id??n,k.info({threadId:this.threadId},"thread resumed"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let u=await this.rpc("thread/start",{cwd:e,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=u?.thread?.id??u?.threadId??"",k.info({threadId:this.threadId},"thread created"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=$c(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,k.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{k.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,k.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return k.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
+ `),!0}restorePendingApproval(e){let n=dm(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,k.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
89
+ `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),k.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
90
90
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
91
- `)}resolveToolContext(e){let n=V(e?.item)??e??null,r=hi(n);if(!r)return null;let s=n?Gc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?gi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),I.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){C.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:cm(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!gm(o)){C.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=hm(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},mm(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/permissions/requestApproval"){C.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}C.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(C.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=V(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&C.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||C.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=V(r?.item),i=hi(s),o=s?Gc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=V(r?.item)??r,i=hi(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=P(r?.reason)??P(V(r?.turn)?.reason);C.info({threadId:this.threadId,reason:s},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=V(r?.turn),i=fm(s?.status),o=V(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&dm.has(i)){C.info({threadId:this.threadId,status:i},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}C.info({threadId:this.threadId,status:i??"completed"},"turn completed"),I.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&C.debug({method:n},"unhandled notification");break}}};var M=require("fs/promises"),Oi=require("fs"),Bi=require("readline"),L=require("path"),ae=require("os");var ym=new Set(["New session","Resumed session","Untitled session"]),vm=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Sm(t){return t.replace(/\s+/g," ").trim()}function hr(t){return typeof t!="string"?void 0:Sm(t)||void 0}function Jc(t){let e=hr(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 xt(t){let e=hr(t);return!e||ym.has(e)||Jc(e)}function _m(t){for(let e of t.replace(/\r/g,"").split(`
92
- `)){let n=hr(e);if(n&&!bm(n)&&!wm(n))return n}}function bm(t){return vm.some(e=>t.startsWith(e))}function wm(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Im(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function mi(t,e=80){if(typeof t!="string")return;let n=_m(t);if(!n)return;let r=Im(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Jc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Qe(t,e){for(let n of t){let r=hr(n);if(!(!r||xt(r)))return r}return mi(e)}var Xc=require("child_process"),Zc=require("util");var eu=(0,Zc.promisify)(Xc.execFile),tu=5e3,Am=2500,Tm=3e3,nu=8,gr=new Map,yi=new Map,Kc=null;function xm(t){let e=gr.get(t);return e?Date.now()>e.expiresAt?(gr.delete(t),null):e.value??void 0:null}function Cm(t,e){if(e===void 0){gr.delete(t);return}gr.set(t,{value:e,expiresAt:Date.now()+tu})}async function km(t){if(!t)return;if(Kc)return Kc(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await eu("git",["-C",t,...n],{env:Ke(),timeout:Am,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function Em(t){let e=xm(t);if(e!==null)return e;let n=yi.get(t);if(n)return n;let r=km(t).then(s=>(Cm(t,s),s)).finally(()=>{yi.delete(t)});return yi.set(t,r),r}async function ru(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function su(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await ru(e,nu,async r=>{n.set(r,await Em(r))}),n}var Si=new Map,vi=new Map,Qc=null;function Pm(t,e){if(e===void 0){Si.delete(t);return}Si.set(t,{value:e,expiresAt:Date.now()+tu})}async function Rm(t){if(t){if(Qc)return Qc(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await eu("git",["-C",t,"diff","HEAD","--shortstat"],{env:Ke(),timeout:Tm,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[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 Mm(t){let e=Si.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=vi.get(t);if(n)return n;let r=Rm(t).then(s=>(Pm(t,s),s)).finally(()=>{vi.delete(t)});return vi.set(t,r),r}async function iu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await ru(e,nu,async r=>{n.set(r,await Mm(r))}),n}var lu=require("child_process"),yr=require("fs/promises"),Xe=require("path"),cu=require("os"),uu=require("util");var Lm=(0,uu.promisify)(lu.execFile),_i=R.child({module:"process-scanner"}),ou=1500,Nm="(^|[^[:alnum:]_.-])(claude|codex)([^[:alnum:]_.-]|$)",Om=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,Bm=500,Dm=15e3,gn=null,hn=null;function vr(){gn=null}var Hm=new Set(["sh","bash","zsh","fish"]),Fm=new Set(["env","nohup","timeout","gtimeout"]),Um=new Set(["node","nodejs","bun","tsx"]),qm=new Set(["-e","--eval","-p","--print"]),Wm=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function Gm(t){return t.replace(/^['"]|['"]$/g,"")}function du(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Gm)}function au(t){let e=(0,Xe.basename)(t);return e==="claude"||e==="codex"?e:null}function jm(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=fu(du(e.trim()),!0);if(n)return n}return null}function fu(t,e=!1){let n=0;for(;n<t.length;){let r=t[n],s=(0,Xe.basename)(r);if(Fm.has(s)){if(n+=1,s==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(s==="timeout"||s==="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(Hm.has(s)){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?jm(l):null}}return null}if(Um.has(s)){let o=n+1;for(;o<t.length;){let l=t[o];if(qm.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,Wm.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=au(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=au(r);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function bi(t,e=!1){return fu(du(t),e)}function Sr(t){let e=bi(t);return e?{agent:e.agent,args:e.args}:null}function pu(t){return Om.test(t)&&bi(t)!==null}function $m(t,e){let n=Sr(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function Vm(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function zm(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function Ym(t,e){let n=Sr(e);if(!(!n||n.agent!==t))return t==="claude"?Vm(n.args):zm(n.args)}function mr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Jm(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Km(t,e){let n=bi(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(r=>r.startsWith("--listen=")))}function Qm(t){let e=[...new Set(t.sessionFiles)].filter(i=>Jm(t.agent,i)),n=$m(t.agent,t.command),r=Ym(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=Ct(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function Xm(t,e){let n=t,r=e;(mr(e.confidence)>mr(t.confidence)||mr(e.confidence)===mr(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function wi(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Xm(s,n):n)}return[...e.values()]}function Zm(t){try{return process.kill(t,0),!0}catch{return!1}}async function _r(t,e){try{let{stdout:n}=await Lm(t,e,{maxBuffer:8388608,timeout:ou});return n}catch(n){let r=String(n);return r.includes("ESRCH")||r.includes("No such process")?_i.debug({file:t,args:e,error:r},"process scan command skipped \u2014 process exited"):_i.warn({file:t,args:e,timeoutMs:ou,error:r},"process scan command failed"),""}}async function ey(t){if(!t.sessionFilePath)return t;let e=await Ze(t.sessionFilePath,t.agent);if(!e)return null;let n=await Ii(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function ty(t){return process.platform==="win32"?"":(await _r("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
- `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function ny(t){if(process.platform==="win32")return[];let n=(await _r("lsof",["-p",String(t),"-Fn"])).split(`
94
- `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function ry(){return(await _r("pgrep",["-fal",Nm])).split(`
95
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2];if(!pu(s))return null;let i=Sr(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function sy(){return(await _r("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"])).split(`
96
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!pu(s))return null;let i=Sr(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function iy(){return process.platform==="win32"?sy():ry()}async function oy(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await iy();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let r=n.filter(o=>Zm(o.pid));t&&(t.aliveProcesses=r.length);let s=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(r.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await ty(o.pid),sessionFiles:await ny(o.pid)})));return t&&(t.lsofMs+=s()),t&&(t.snapshots=i.length),i}function ay(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function ly(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,Xe.join)((0,cu.homedir)(),".claude","projects",ay(e)),s=(await(0,yr.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(s.length===0)return null;let i=null;if(await Promise.all(s.map(async l=>{let c=await(0,yr.stat)((0,Xe.join)(n,l)).catch(()=>null);c&&(!i||c.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:c.mtimeMs})})),!i)return null;let o=(0,Xe.join)(n,i.name),a=Ct(t,o);return a?{sessionId:a,filePath:o}:null}return gu(e)}catch{return null}}async function cy(){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 oy(t),r=[],s=[];for(let u of n){let d=Qm(u);if(d){r.push(d);continue}Km(u.agent,u.command)&&s.push(u)}t.directCandidates=r.length,t.fallbackLookups=s.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(s.map(async u=>{let d=await ly(u.agent,u.cwd);return d?{agent:u.agent,pid:u.pid,cwd:u.cwd,command:u.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(u=>u!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...r,...o.filter(u=>u!==null)].map(u=>ey(u)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(u=>u!==null).length;let c=wi(l.filter(u=>u!==null));return t.totalMs=e(),(t.totalMs>=Bm||t.fallbackLookups>0)&&_i.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:c.length},"process running sessions scanned"),gn={value:c,expiresAt:Date.now()+Dm},c}async function hu(){return gn&&Date.now()<gn.expiresAt?gn.value:hn||(hn=cy().finally(()=>{hn=null}),hn)}var vu=require("fs"),Oe=require("fs/promises"),Ti=require("os"),yn=require("path");var mn=R.child({module:"activity-watcher"}),uy=12e4,dy=5e3,fy=6e4,mu=5;function py(){return(0,yn.join)((0,Ti.homedir)(),".claude","projects")}function hy(){return(0,yn.join)((0,Ti.homedir)(),".codex","sessions")}async function yu(t){try{return await(0,Oe.realpath)(t)}catch{return t}}function br(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Ai=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 yu(e?.claudeDir??py()),r=await yu(e?.codexDir??hy());if(this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges(),e?.usePolling){let s=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},s);a.unref?.(),this.pollTimers.push(a)}}else for(let[s,i]of this.roots)this.startNativeWatch(s,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(s=>{mn.warn({error:String(s)},"activity watcher rescan failed")})},fy),this.rescanTimer.unref?.(),mn.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 r=(0,vu.watch)(e,{recursive:!0,persistent:!0},(s,i)=>{if(!i)return;let o=(0,yn.join)(e,i.toString());br(o,n)&&this.resolveFsEvent(n,o)});r.on("error",s=>{mn.warn({error:String(s),root:e},"activity watcher error")}),this.watchers.push(r)}catch(r){mn.warn({error:String(r),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let r=await(0,Oe.stat)(n).catch(()=>null);if(!r){this.handleUnlink(n);return}r.isFile()&&await this.handleFsChange(n,r.mtimeMs)}async pollScan(e,n){let r=await this.walkSessionFiles(n,mu),s=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of r){if(!br(o,e))continue;s.add(o);let l=this.filePathIndex.get(o);if(l){let u=this.entries.get(l);if(!u||a<=u.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(s.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=uy){let n=Date.now(),r=n-e,s=n-dy,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,mu);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{br(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,Oe.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let c=(0,yn.join)(i,l.name);if(l.isDirectory()){await s(c,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let u=await(0,Oe.stat)(c).catch(()=>null);u&&r.push({filePath:c,mtimeMs:u.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!br(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,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,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await Ze(n,e);if(!l)return;let c=`${e}:${l.sessionId}`,u=this.entries.get(c);if(u){u.lastActivityMs=Math.max(u.lastActivityMs,r),u.mtimeMs=Math.max(u.mtimeMs,s),u.filePath!==n&&(this.filePathIndex.delete(u.filePath),u.filePath=n),this.filePathIndex.set(n,c);return}this.entries.set(c,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:r,mtimeMs:s}),this.filePathIndex.set(n,c)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,Oe.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){mn.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()}},kt=new Ai;var et=R.child({module:"inventory"}),Iu=6e3,gy=1e4;function my(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function yy(){return kt.listActive().map(my)}var Au={listScannedSessions:bn,listWatcherSessions:yy,scanRunningSessions:hu,searchSessionContent:Ru},oe=vy(),Sn=null,wr=0,Ar=0,Ir=0,xi=0,Ci=new Set;function vy(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Sy(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,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})}function _y(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 Su(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Sy).sort(),runningSessions:t.runningSessions.map(_y).sort()})}function by(){for(let t of Ci)try{t()}catch(e){et.warn({error:String(e)},"session inventory backfill listener failed")}}function vn(){_.gauge("session.inventory.external_cached_sessions",oe.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",oe.runningSessions.length),_.gauge("session.inventory.backfill_inflight",Sn?1:0)}function Tu(t){return Ci.add(t),()=>{Ci.delete(t)}}function xu(){return{cachedSessions:oe.scannedSessions.length,runningSessions:oe.runningSessions.length,cacheAgeMs:oe.refreshedAt?Math.max(0,Date.now()-oe.refreshedAt):void 0,backfillInFlight:!!Sn,lastBackfillDurationMs:Ir||void 0,lastBackfillCompletedAt:Ar?new Date(Ar).toISOString():void 0,lastBackfillAppliedAt:xi?new Date(xi).toISOString():void 0}}vn();function Cu(){return kt.onActivity(()=>{Pu(Au,Iu)})}var Et={daemonActive:3,externalRunning:2,idle:1},_u={high:3,medium:2,low:1};function ku(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function wy(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||Et[e.runtime.state]-Et[t.runtime.state]||ku(t,e)}function Iy(t,e){return Et[e.state]>Et[t.state]?e:Et[e.state]<Et[t.state]?t:_u[e.confidence]>_u[t.confidence]?e:t}function Ay(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Ty(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function xy(t,e){return e?t?!(xt(e)&&!xt(t)):!0:!1}function ki(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Cy(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...ki()},managed:t.managed,approvalMode:t.approvalMode}}function ky(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 Ey(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function Py(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=xy(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=Iy(s.runtime,n.runtime),c=s.sources.slice();for(let h of n.sources)c.includes(h)||c.push(h);let u=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),f=u?s.lastActivityAt:d?n.lastActivityAt:Ty(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,branch:a,title:i,createdAt:Ay(s.createdAt,n.createdAt),lastActivityAt:f,sources:c,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function Ry(...t){let e=new Map;for(let n of t)Py(e,n);return[...e.values()]}function My(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let c=(l.title??"").toLowerCase(),u=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",f=c.includes(o)||u.includes(o)||(d?d.includes(o):!1),h=s?.has(l.sessionId)??!1;if(!f&&!h)return!1}return!0});return r&&et.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function Ly(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function bu(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),c=Ry(t.sessionRecords.map(Cy),t.scannedSessions,t.runningSessions.map(w=>ky(w,t.scannedAt)),t.activeSessions.map(Ey)),u=t.deletedSessionIds?.size?c.filter(w=>!t.deletedSessionIds?.has(w.sessionId)):c,d=My(u,r,s,i,o,a),f=d.filter(w=>w.runtime.state!=="idle"||w.managed).sort(wy),h=d.filter(w=>w.runtime.state==="idle"&&!w.managed).sort(ku),g=Ly(h,n),p=h.slice(g,g+l),v=g+p.length<h.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...f,...p],nextCursor:v}}async function wu(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([su(e),iu(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function _n(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;et.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||et.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function Ny(t=Date.now()){return oe.refreshedAt===0||t-oe.refreshedAt>=gy}async function Eu(t,e){let[n,r]=await Promise.all([_n("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),_n("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return wi([...n,...r])}async function Oy(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([_n("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),Eu(t,e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Pu(t,e){if(Sn)return;let n=wr,r=_.startTimer("session.inventory.backfill_latency_ms");Sn=Oy(t,e).then(s=>{if(n!==wr)return;let i=Su(oe);oe=s;let o=Su(s),a=r();Ir=a,Ar=Date.now(),vn(),i!==o&&(xi=Date.now(),_.increment("session.inventory.backfill_applied"),et.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),by())}).catch(s=>{n===wr&&(Ir=r(),Ar=Date.now(),vn(),et.warn({error:String(s),durationMs:Ir},"session inventory external backfill failed"))}).finally(()=>{n===wr&&(Sn=null,vn())}),vn()}async function Tr(t){let e={...Au,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??Iu);if(!t.search){let u=_.startTimer("session.inventory.fast_path_latency_ms");Ny()&&Pu(e,n);let d=oe,f=bu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return u(),f;let h=await wu(f);return u(),h}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([_n("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),Eu(e,n),_n("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);et.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let c=bu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?c:wu(c)}var Be=R.child({module:"scanner"});function Di(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Hi=3e4,Mi=Di(Hi),Li=Di(Hi),Cr=Di(Hi),Ei=new Map,Pi=new Map,xr=null,tt=24;function Er(){Mi.clear(),Li.clear(),Cr.clear()}function Du(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function nt(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}async function Hu(){let t=(0,L.join)((0,ae.homedir)(),".codex","sessions"),e=await(0,M.readdir)(t).catch(()=>[]),n=[];for(let s of e){let i=(0,L.join)(t,s),o=await(0,M.readdir)(i).catch(()=>[]);for(let a of o){let l=(0,L.join)(i,a),c=await(0,M.readdir)(l).catch(()=>[]);for(let u of c){let d=(0,L.join)(l,u),f=await(0,M.readdir)(d).catch(()=>[]);for(let h of f)h.endsWith(".jsonl")&&n.push((0,L.join)(d,h))}}}let r=await nt(n,tt,async s=>{let i=await(0,M.stat)(s).catch(()=>null);return{path:s,mtimeMs:i?.mtimeMs??0}});return r.sort((s,i)=>i.mtimeMs-s.mtimeMs),r}function By(t){let e=`codex-latest:${(0,ae.homedir)()}`,n=new Map;for(let r of t)n.has(r.cwd)||n.set(r.cwd,r.match);Cr.set(e,n)}function*Fu(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
97
- `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Ri=512*1024,Mu=256*1024;async function Uu(t,e){if(e<=Ri)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Buffer.alloc(Ri),{bytesRead:s}=await n.read(r,0,Ri,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function Dy(t,e){if(e<=Mu)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Math.max(0,e-Mu),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Lu(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Hy(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function Fy(t){return t?.type==="permission-mode"?Lu(t.permissionMode):Lu(t?.permissionMode)}function Uy(t){if(t?.type==="turn_context")return Hy(t.payload)}async function qu(t,e,n){let r,s=await Dy(t,n);for(let i of s.split(`
98
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?Fy(o):Uy(o);a&&(r=a)}return r}function Fi(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 Wu(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Fi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Pr(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 qy=["<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 Wy(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?qy.some(r=>n.startsWith(r)):!1}function Rr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Pr(t.message.content);return Wy(t,e)?"":e}function Gy(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function jy(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(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
91
+ `)}resolveToolContext(e){let n=z(e?.item)??e??null,r=gi(n);if(!r)return null;let s=n?jc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?mi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),I.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){k.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:um(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!mm(o)){k.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=gm(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},ym(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/permissions/requestApproval"){k.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}k.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(k.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=z(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&k.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||k.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=z(r?.item),i=gi(s),o=s?jc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=z(r?.item)??r,i=gi(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=P(r?.reason)??P(z(r?.turn)?.reason);k.info({threadId:this.threadId,reason:s},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=z(r?.turn),i=pm(s?.status),o=z(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&fm.has(i)){k.info({threadId:this.threadId,status:i},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}k.info({threadId:this.threadId,status:i??"completed"},"turn completed"),I.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&k.debug({method:n},"unhandled notification");break}}};var M=require("fs/promises"),Bi=require("fs"),Di=require("readline"),L=require("path"),ae=require("os");var vm=new Set(["New session","Resumed session","Untitled session"]),Sm=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function _m(t){return t.replace(/\s+/g," ").trim()}function hr(t){return typeof t!="string"?void 0:_m(t)||void 0}function Kc(t){let e=hr(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 xt(t){let e=hr(t);return!e||vm.has(e)||Kc(e)}function bm(t){for(let e of t.replace(/\r/g,"").split(`
92
+ `)){let n=hr(e);if(n&&!wm(n)&&!Im(n))return n}}function wm(t){return Sm.some(e=>t.startsWith(e))}function Im(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Am(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function yi(t,e=80){if(typeof t!="string")return;let n=bm(t);if(!n)return;let r=Am(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Kc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Qe(t,e){for(let n of t){let r=hr(n);if(!(!r||xt(r)))return r}return yi(e)}var Zc=require("child_process"),eu=require("util");var tu=(0,eu.promisify)(Zc.execFile),nu=5e3,xm=2500,Tm=3e3,ru=8,gr=new Map,vi=new Map,Qc=null;function Cm(t){let e=gr.get(t);return e?Date.now()>e.expiresAt?(gr.delete(t),null):e.value??void 0:null}function km(t,e){if(e===void 0){gr.delete(t);return}gr.set(t,{value:e,expiresAt:Date.now()+nu})}async function Em(t){if(!t)return;if(Qc)return Qc(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await tu("git",["-C",t,...n],{env:Ke(),timeout:xm,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function Pm(t){let e=Cm(t);if(e!==null)return e;let n=vi.get(t);if(n)return n;let r=Em(t).then(s=>(km(t,s),s)).finally(()=>{vi.delete(t)});return vi.set(t,r),r}async function su(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function iu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await su(e,ru,async r=>{n.set(r,await Pm(r))}),n}var _i=new Map,Si=new Map,Xc=null;function Rm(t,e){if(e===void 0){_i.delete(t);return}_i.set(t,{value:e,expiresAt:Date.now()+nu})}async function Mm(t){if(t){if(Xc)return Xc(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await tu("git",["-C",t,"diff","HEAD","--shortstat"],{env:Ke(),timeout:Tm,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[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 Lm(t){let e=_i.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=Si.get(t);if(n)return n;let r=Mm(t).then(s=>(Rm(t,s),s)).finally(()=>{Si.delete(t)});return Si.set(t,r),r}async function ou(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await su(e,ru,async r=>{n.set(r,await Lm(r))}),n}var lu=require("child_process"),vr=require("fs/promises"),Xe=require("path"),cu=require("os"),uu=require("util");var Nm=(0,uu.promisify)(lu.execFile),yr=R.child({module:"process-scanner"}),du=5e3,Om=1500,Bm=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,Dm=500,Hm=15e3,gn=null,hn=null;function Sr(){gn=null}var Fm=new Set(["sh","bash","zsh","fish"]),Um=new Set(["env","nohup","timeout","gtimeout"]),qm=new Set(["node","nodejs","bun","tsx"]),Wm=new Set(["-e","--eval","-p","--print"]),Gm=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function jm(t){return t.replace(/^['"]|['"]$/g,"")}function fu(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(jm)}function au(t){let e=(0,Xe.basename)(t);return e==="claude"||e==="codex"?e:null}function $m(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=pu(fu(e.trim()),!0);if(n)return n}return null}function pu(t,e=!1){let n=0;for(;n<t.length;){let r=t[n],s=(0,Xe.basename)(r);if(Um.has(s)){if(n+=1,s==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(s==="timeout"||s==="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(Fm.has(s)){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?$m(l):null}}return null}if(qm.has(s)){let o=n+1;for(;o<t.length;){let l=t[o];if(Wm.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,Gm.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=au(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=au(r);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function bi(t,e=!1){return pu(fu(t),e)}function _r(t){let e=bi(t);return e?{agent:e.agent,args:e.args}:null}function hu(t){return Bm.test(t)&&bi(t)!==null}function Vm(t,e){let n=_r(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function zm(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function Ym(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function Jm(t,e){let n=_r(e);if(!(!n||n.agent!==t))return t==="claude"?zm(n.args):Ym(n.args)}function mr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Km(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Qm(t,e){let n=bi(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(r=>r.startsWith("--listen=")))}function Xm(t){let e=[...new Set(t.sessionFiles)].filter(i=>Km(t.agent,i)),n=Vm(t.agent,t.command),r=Jm(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=Tt(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function Zm(t,e){let n=t,r=e;(mr(e.confidence)>mr(t.confidence)||mr(e.confidence)===mr(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function wi(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Zm(s,n):n)}return[...e.values()]}function ey(t){try{return process.kill(t,0),!0}catch{return!1}}async function br(t,e,n=Om){try{let{stdout:r}=await Nm(t,e,{maxBuffer:8388608,timeout:n});return r}catch(r){let s=typeof r=="object"&&r!==null?{code:"code"in r?r.code:void 0,signal:"signal"in r?r.signal:void 0,killed:"killed"in r?r.killed:void 0}:{},i=String(r);return i.includes("ESRCH")||i.includes("No such process")?yr.debug({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command skipped \u2014 process exited"):yr.warn({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command failed"),""}}async function ty(t){if(!t.sessionFilePath)return t;let e=await Ze(t.sessionFilePath,t.agent);if(!e)return null;let n=await Ai(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function ny(t){return process.platform==="win32"?"":(await br("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function ry(t){if(process.platform==="win32")return[];let n=(await br("lsof",["-p",String(t),"-Fn"])).split(`
94
+ `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function sy(t){return t.split(`
95
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2];if(!hu(s))return null;let i=_r(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function iy(){let t=await br("ps",["-axo","pid=,command="],du);return sy(t)}async function oy(){return(await br("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],du)).split(`
96
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!hu(s))return null;let i=_r(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function ay(){return process.platform==="win32"?oy():iy()}async function ly(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await ay();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let r=n.filter(o=>ey(o.pid));t&&(t.aliveProcesses=r.length);let s=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(r.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await ny(o.pid),sessionFiles:await ry(o.pid)})));return t&&(t.lsofMs+=s()),t&&(t.snapshots=i.length),i}function cy(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function uy(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,Xe.join)((0,cu.homedir)(),".claude","projects",cy(e)),s=(await(0,vr.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(s.length===0)return null;let i=null;if(await Promise.all(s.map(async l=>{let c=await(0,vr.stat)((0,Xe.join)(n,l)).catch(()=>null);c&&(!i||c.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:c.mtimeMs})})),!i)return null;let o=(0,Xe.join)(n,i.name),a=Tt(t,o);return a?{sessionId:a,filePath:o}:null}return mu(e)}catch{return null}}async function dy(){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 ly(t),r=[],s=[];for(let u of n){let d=Xm(u);if(d){r.push(d);continue}Qm(u.agent,u.command)&&s.push(u)}t.directCandidates=r.length,t.fallbackLookups=s.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(s.map(async u=>{let d=await uy(u.agent,u.cwd);return d?{agent:u.agent,pid:u.pid,cwd:u.cwd,command:u.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(u=>u!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...r,...o.filter(u=>u!==null)].map(u=>ty(u)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(u=>u!==null).length;let c=wi(l.filter(u=>u!==null));return t.totalMs=e(),(t.totalMs>=Dm||t.fallbackLookups>0)&&yr.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:c.length},"process running sessions scanned"),gn={value:c,expiresAt:Date.now()+Hm},c}async function Ii(){return gn&&Date.now()<gn.expiresAt?gn.value:hn||(hn=dy().finally(()=>{hn=null}),hn)}async function gu(t){try{return(await Ii()).some(n=>n.sessionId===t)}catch(e){return yr.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var Su=require("fs"),Oe=require("fs/promises"),Ti=require("os"),yn=require("path");var mn=R.child({module:"activity-watcher"}),fy=12e4,py=5e3,hy=6e4,yu=5;function gy(){return(0,yn.join)((0,Ti.homedir)(),".claude","projects")}function my(){return(0,yn.join)((0,Ti.homedir)(),".codex","sessions")}async function vu(t){try{return await(0,Oe.realpath)(t)}catch{return t}}function wr(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var xi=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 vu(e?.claudeDir??gy()),r=await vu(e?.codexDir??my());if(this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges(),e?.usePolling){let s=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},s);a.unref?.(),this.pollTimers.push(a)}}else for(let[s,i]of this.roots)this.startNativeWatch(s,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(s=>{mn.warn({error:String(s)},"activity watcher rescan failed")})},hy),this.rescanTimer.unref?.(),mn.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 r=(0,Su.watch)(e,{recursive:!0,persistent:!0},(s,i)=>{if(!i)return;let o=(0,yn.join)(e,i.toString());wr(o,n)&&this.resolveFsEvent(n,o)});r.on("error",s=>{mn.warn({error:String(s),root:e},"activity watcher error")}),this.watchers.push(r)}catch(r){mn.warn({error:String(r),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let r=await(0,Oe.stat)(n).catch(()=>null);if(!r){this.handleUnlink(n);return}r.isFile()&&await this.handleFsChange(n,r.mtimeMs)}async pollScan(e,n){let r=await this.walkSessionFiles(n,yu),s=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of r){if(!wr(o,e))continue;s.add(o);let l=this.filePathIndex.get(o);if(l){let u=this.entries.get(l);if(!u||a<=u.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(s.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=fy){let n=Date.now(),r=n-e,s=n-py,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,yu);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{wr(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,Oe.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let c=(0,yn.join)(i,l.name);if(l.isDirectory()){await s(c,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let u=await(0,Oe.stat)(c).catch(()=>null);u&&r.push({filePath:c,mtimeMs:u.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!wr(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,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,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await Ze(n,e);if(!l)return;let c=`${e}:${l.sessionId}`,u=this.entries.get(c);if(u){u.lastActivityMs=Math.max(u.lastActivityMs,r),u.mtimeMs=Math.max(u.mtimeMs,s),u.filePath!==n&&(this.filePathIndex.delete(u.filePath),u.filePath=n),this.filePathIndex.set(n,c);return}this.entries.set(c,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:r,mtimeMs:s}),this.filePathIndex.set(n,c)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,Oe.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){mn.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()}},Ct=new xi;var et=R.child({module:"inventory"}),Au=6e3,yy=1e4;function vy(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function Sy(){return Ct.listActive().map(vy)}var xu={listScannedSessions:bn,listWatcherSessions:Sy,scanRunningSessions:Ii,searchSessionContent:Mu},oe=_y(),Sn=null,Ir=0,xr=0,Ar=0,Ci=0,ki=new Set;function _y(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function by(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,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})}function wy(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 _u(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(by).sort(),runningSessions:t.runningSessions.map(wy).sort()})}function Iy(){for(let t of ki)try{t()}catch(e){et.warn({error:String(e)},"session inventory backfill listener failed")}}function vn(){_.gauge("session.inventory.external_cached_sessions",oe.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",oe.runningSessions.length),_.gauge("session.inventory.backfill_inflight",Sn?1:0)}function Tu(t){return ki.add(t),()=>{ki.delete(t)}}function Cu(){return{cachedSessions:oe.scannedSessions.length,runningSessions:oe.runningSessions.length,cacheAgeMs:oe.refreshedAt?Math.max(0,Date.now()-oe.refreshedAt):void 0,backfillInFlight:!!Sn,lastBackfillDurationMs:Ar||void 0,lastBackfillCompletedAt:xr?new Date(xr).toISOString():void 0,lastBackfillAppliedAt:Ci?new Date(Ci).toISOString():void 0}}vn();function ku(){return Ct.onActivity(()=>{Ru(xu,Au)})}var kt={daemonActive:3,externalRunning:2,idle:1},bu={high:3,medium:2,low:1};function Eu(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Ay(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||kt[e.runtime.state]-kt[t.runtime.state]||Eu(t,e)}function xy(t,e){return kt[e.state]>kt[t.state]?e:kt[e.state]<kt[t.state]?t:bu[e.confidence]>bu[t.confidence]?e:t}function Ty(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Cy(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function ky(t,e){return e?t?!(xt(e)&&!xt(t)):!0:!1}function Ei(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Ey(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...Ei()},managed:t.managed,approvalMode:t.approvalMode}}function Py(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 Ry(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function My(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=ky(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=xy(s.runtime,n.runtime),c=s.sources.slice();for(let h of n.sources)c.includes(h)||c.push(h);let u=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),f=u?s.lastActivityAt:d?n.lastActivityAt:Cy(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,branch:a,title:i,createdAt:Ty(s.createdAt,n.createdAt),lastActivityAt:f,sources:c,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function Ly(...t){let e=new Map;for(let n of t)My(e,n);return[...e.values()]}function Ny(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let c=(l.title??"").toLowerCase(),u=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",f=c.includes(o)||u.includes(o)||(d?d.includes(o):!1),h=s?.has(l.sessionId)??!1;if(!f&&!h)return!1}return!0});return r&&et.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function Oy(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function wu(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),c=Ly(t.sessionRecords.map(Ey),t.scannedSessions,t.runningSessions.map(b=>Py(b,t.scannedAt)),t.activeSessions.map(Ry)),u=t.deletedSessionIds?.size?c.filter(b=>!t.deletedSessionIds?.has(b.sessionId)):c,d=Ny(u,r,s,i,o,a),f=d.filter(b=>b.runtime.state!=="idle"||b.managed).sort(Ay),h=d.filter(b=>b.runtime.state==="idle"&&!b.managed).sort(Eu),g=Oy(h,n),p=h.slice(g,g+l),v=g+p.length<h.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...f,...p],nextCursor:v}}async function Iu(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([iu(e),ou(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function _n(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;et.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||et.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function By(t=Date.now()){return oe.refreshedAt===0||t-oe.refreshedAt>=yy}async function Pu(t,e){let[n,r]=await Promise.all([_n("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),_n("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return wi([...n,...r])}async function Dy(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([_n("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),Pu(t,e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Ru(t,e){if(Sn)return;let n=Ir,r=_.startTimer("session.inventory.backfill_latency_ms");Sn=Dy(t,e).then(s=>{if(n!==Ir)return;let i=_u(oe);oe=s;let o=_u(s),a=r();Ar=a,xr=Date.now(),vn(),i!==o&&(Ci=Date.now(),_.increment("session.inventory.backfill_applied"),et.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),Iy())}).catch(s=>{n===Ir&&(Ar=r(),xr=Date.now(),vn(),et.warn({error:String(s),durationMs:Ar},"session inventory external backfill failed"))}).finally(()=>{n===Ir&&(Sn=null,vn())}),vn()}async function Tr(t){let e={...xu,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??Au);if(!t.search){let u=_.startTimer("session.inventory.fast_path_latency_ms");By()&&Ru(e,n);let d=oe,f=wu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return u(),f;let h=await Iu(f);return u(),h}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([_n("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),Pu(e,n),_n("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);et.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let c=wu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?c:Iu(c)}var Be=R.child({module:"scanner"});function Hi(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Fi=3e4,Li=Hi(Fi),Ni=Hi(Fi),kr=Hi(Fi),Pi=new Map,Ri=new Map,Cr=null,tt=24;function Pr(){Li.clear(),Ni.clear(),kr.clear()}function Hu(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function nt(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}async function Fu(){let t=(0,L.join)((0,ae.homedir)(),".codex","sessions"),e=await(0,M.readdir)(t).catch(()=>[]),n=[];for(let s of e){let i=(0,L.join)(t,s),o=await(0,M.readdir)(i).catch(()=>[]);for(let a of o){let l=(0,L.join)(i,a),c=await(0,M.readdir)(l).catch(()=>[]);for(let u of c){let d=(0,L.join)(l,u),f=await(0,M.readdir)(d).catch(()=>[]);for(let h of f)h.endsWith(".jsonl")&&n.push((0,L.join)(d,h))}}}let r=await nt(n,tt,async s=>{let i=await(0,M.stat)(s).catch(()=>null);return{path:s,mtimeMs:i?.mtimeMs??0}});return r.sort((s,i)=>i.mtimeMs-s.mtimeMs),r}function Hy(t){let e=`codex-latest:${(0,ae.homedir)()}`,n=new Map;for(let r of t)n.has(r.cwd)||n.set(r.cwd,r.match);kr.set(e,n)}function*Uu(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
97
+ `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Mi=512*1024,Lu=256*1024;async function qu(t,e){if(e<=Mi)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Buffer.alloc(Mi),{bytesRead:s}=await n.read(r,0,Mi,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function Fy(t,e){if(e<=Lu)return(0,M.readFile)(t,"utf-8");let n=await(0,M.open)(t,"r");try{let r=Math.max(0,e-Lu),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Nu(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Uy(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function qy(t){return t?.type==="permission-mode"?Nu(t.permissionMode):Nu(t?.permissionMode)}function Wy(t){if(t?.type==="turn_context")return Uy(t.payload)}async function Wu(t,e,n){let r,s=await Fy(t,n);for(let i of s.split(`
98
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?qy(o):Wy(o);a&&(r=a)}return r}function Ui(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 Gu(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Ui(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Rr(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 Gy=["<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 jy(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Gy.some(r=>n.startsWith(r)):!1}function Mr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Rr(t.message.content);return jy(t,e)?"":e}function $y(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function Vy(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(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
99
99
  `):""}).filter(Boolean).join(`
100
- `):""}function $y(t){let e=jy(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 Gu(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function kr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:ki()}}function Ct(t,e){let n=(0,L.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 Vy(t,e){let n=await Uu(t,e),r=Fu(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Qe([u.customTitle,u.summary])),!l){let d=Rr(u),f=Qe([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Ct("claude",t)||(0,L.basename)(t,".jsonl"),cwd:s,title:o??l??Qe([],a),approvalMode:await qu(t,"claude",e)}:null}async function zy(t,e){let n=await Uu(t,e),r=Fu(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Qe([u.payload?.title,u.title])),!l){let d=Wu(u),f=d&&!Gu(d)?Qe([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Ct("codex",t)||(0,L.basename)(t,".jsonl"),cwd:s,title:o??l??Qe([],a),approvalMode:await qu(t,"codex",e)}:null}async function Ze(t,e){let n=await(0,M.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Vy(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await zy(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Nu(t,e){let n=(0,L.join)((0,ae.homedir)(),".claude","projects");try{let r;t?r=[Du(t)]:r=(await(0,M.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,L.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,L.join)(c,d))}let i=await nt(s,tt,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await nt(i,tt,async l=>{let c=await Ze(l.path,"claude");return c&&e&&e.push(kr(c)),c})).filter(l=>l!==null).map(l=>kr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Be.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Ou(t,e){try{let n=await Hu(),r=await nt(n,tt,async i=>{let o=await Ze(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(kr(o)),o});return By(r.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),r.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>kr(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Be.warn({error:String(n)},"failed to list codex sessions"),[]}}async function gu(t){if(!t)return null;let e=`codex-latest:${(0,ae.homedir)()}`,n=Cr.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}xr||(xr=(async()=>{let i=await Hu(),o=await nt(i,tt,async l=>{let c=await Ze(l.path,"codex");return c?{cwd:c.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:c.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return Cr.set(e,a),a})().finally(()=>{xr=null}));let s=(await xr).get(t);return s?{sessionId:s.sessionId,filePath:s.path}:null}async function bn(t,e,n){let s=`list:${(0,ae.homedir)()}:${t??"all"}:${e??""}`,i=Mi.get(s);if(i)return i;let o=Ei.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Nu(e,n);else if(t==="codex")l=await Ou(e,n);else{let[c,u]=await Promise.all([Nu(e,n),Ou(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return Mi.set(s,l),l})();return Ei.set(s,a),a.finally(()=>Ei.delete(s)),a}async function Ru(t,e){let r=`search:${(0,ae.homedir)()}:${t}:${e??"all"}`,s=Li.get(r);if(s)return s;let i=Pi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,L.join)((0,ae.homedir)(),".claude","projects");try{let f=await(0,M.readdir)(d,{withFileTypes:!0}),h=[];for(let p of f){if(!p.isDirectory())continue;let m=(0,L.join)(d,p.name),v=await(0,M.readdir)(m).catch(()=>[]);for(let w of v)w.endsWith(".jsonl")&&h.push((0,L.join)(m,w))}let g=await nt(h,tt,p=>Bu(p,l,"claude"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,L.join)((0,ae.homedir)(),".codex","sessions");try{let f=[];async function h(p){let m=await(0,M.readdir)(p,{withFileTypes:!0}).catch(()=>[]);for(let v of m){let w=(0,L.join)(p,v.name);v.isDirectory()?await h(w):v.name.endsWith(".jsonl")&&f.push(w)}}await h(d);let g=await nt(f,tt,p=>Bu(p,l,"codex"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Li.set(r,a),a})();return Pi.set(r,o),o.finally(()=>Pi.delete(r)),o}async function Bu(t,e,n){let r=(0,Oi.createReadStream)(t,{encoding:"utf-8"}),s=(0,Bi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Yy:Jy,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||Ct(n,t):null}function Yy(t){return t?.type==="user"&&t.message?.role==="user"?Rr(t):t?.type==="assistant"&&t.message?.role==="assistant"?Pr(t.message.content):""}function Jy(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Fi(t.payload.content)}let e=Wu(t);return e||""}async function Ni(t,e){let n=(0,Oi.createReadStream)(t,{encoding:"utf-8"}),r=(0,Bi.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function ju(t,e){let n=(0,L.join)((0,ae.homedir)(),".claude","projects"),r=e?Du(e):null,s=await(0,M.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,L.join)(n,o,`${t}.jsonl`);if((await(0,M.stat)(a).catch(()=>null))?.isFile())return a}return null}async function $u(t,e,n){if(e==="claude")return ju(t,n);let r=(0,L.join)((0,ae.homedir)(),".codex","sessions");return Vu(r,t)}function Ky(t){if(t?.type==="user"&&t.message?.role==="user")return Gy(t.message.content)?{kind:"toolResult",...$y(t)?{interrupted:!0}:{}}:Rr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Pr(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 Qy(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 Ii(t,e){if(e!=="claude")return{};let n=null;try{await Ni(t,r=>{let s=Ky(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Be.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Qy(n)}async function Ui(t,e,n){let r=await $u(t,e,n);return r?Ii(r,e):{}}async function wn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await ju(t,n);i&&await Ni(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=Rr(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=Pr(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Be.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await $u(t,e,n);i&&await Ni(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=Fi(o.payload.content);l&&(a==="user"&&Gu(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Be.warn({error:String(i)},"failed to read codex session history")}return r}async function Vu(t,e){try{let n=await(0,M.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,L.join)(t,r.name);if(r.isDirectory()){let i=await Vu(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Be.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Pt=require("fs"),Ku=require("path");var Xy=500,zu=200;function Yu(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=zu?e:e.slice(-zu)}function Zy(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 ev(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Ju(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Yu(t.acceptedClientMessageIds),interruptedClientMessageIds:Yu(t.interruptedClientMessageIds),pendingApproval:ev(t.pendingApproval)}}function tv(t){if(Array.isArray(t))return{records:t.map(Ju),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Ju):[],deletedSessionIds:Zy(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var Mr=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},Xy)}loadFromDisk(){try{let e=(0,Pt.readFileSync)(ir,"utf-8");return tv(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,Pt.mkdirSync)((0,Ku.dirname)(ir),{recursive:!0}),(0,Pt.writeFileSync)(ir,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Rt=require("path"),Qu=require("os");function Lr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Rt.join)((0,Qu.homedir)(),t.slice(2)):t}function nv(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function qi(t,e){let n=Lr(nv(t));if(!n||(0,Rt.isAbsolute)(n))return n;let r=Lr(e??"");return r?(0,Rt.resolve)(r,n):n}var Xu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Mt=require("fs"),Zu=require("path");function rv(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function sv(t){try{let e=(0,Mt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(rv):[]}catch{return[]}}function In(t,e){(0,Mt.mkdirSync)((0,Zu.dirname)(t),{recursive:!0}),(0,Mt.writeFileSync)(t,JSON.stringify(e,null,2)+`
101
- `,"utf8")}var Nr=class{constructor(e=_c){this.pushSubscriptionsPath=e;this.records=sv(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],In(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,In(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,In(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&In(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],In(this.pushSubscriptionsPath,this.records)}};var z=R.child({module:"push"}),iv="https://exp.host/--/api/v2/push/send",ov="https://exp.host/--/api/v2/push/getReceipts",av=[0,1e3,3e3],An=new Nr;function lv(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 cv(t){return new Promise(e=>{setTimeout(e,t)})}function ed(t){return t==="DeviceNotRegistered"}function uv(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function dv(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function fv(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function pv(t,e,n,r){let s=new Map(t);for(let i of av){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(ov,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){z.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){z.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){z.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=fv(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(z.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),ed(f)){let h=r.unregisterToken(u);z.info({token:u,errorCode:f,removed:h},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&z.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function hv(t){let e=t?.pushStore??An,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??cv;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...lv(a)&&a.eventType==="approval_request"?{categoryId:Xu.approvalRequestV1}:{}}));try{let u=await n(iv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){z.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){z.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:h}=uv(d,l),g=dv(d,l);for(let{token:p,ticket:m}of h){let v=m.details?.error;if(z.error({token:p,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),ed(v)){let w=e.unregisterToken(p);z.info({token:p,errorCode:v,removed:w},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await pv(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function Wi(t,e){An.register(t,e),z.info({deviceId:t,token:e,total:An.count()},"push token registered")}function Gi(t,e){let n=An.unregister(t,e);z.info({deviceId:t,token:e,total:An.count(),removed:n},"push token unregistered")}var Or=hv();var b=R.child({module:"manager"}),gv="Done.",mv="Approval required",td=180,Lt=200;function Ie(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>Lt&&e.splice(0,e.length-Lt));return e}function Br(t){return t?.length?{acceptedClientMessageIds:Ie(t)}:{}}function me(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:Ie(t.acceptedClientMessageIds),interruptedClientMessageIds:Ie(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function nd(t){t.managed||(t.managed=!0)}function rd(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&pr(e)}function sd(t,e,n){return{sessionId:t,agent:e,...n}}function yv(t){return t.startsWith(ui)}function id(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 Dr=class{constructor(e=Or){this.pushSender=e;this.removeInventoryBackfillListener=Tu(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new Mr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs,r=S.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(b.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;b.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:o.agent}),I.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(b.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:o.agent}),I.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){b.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(b.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!rd(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){I.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(mv,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"&&pr(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")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),I.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o}),_.increment("driver.exit",{agent:n,abnormal:o&&o!==0?"true":"false"});let a=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&rd(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",a||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(me(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof pn&&s&&n.setModel(s),e!=="claude"||!(n instanceof fn))return;let i=r??(0,ji.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=dn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&yv(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),dn;if(r.approvalMode==="autoApprove")return id(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return dn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${ui}${l.trim()||(0,ji.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},I.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=Ie(r?.acceptedClientMessageIds),h=Ie(r?.interruptedClientMessageIds),g=r?.isResponding,p=r?"memory":"client",m=this.store.find(e);if(m)i=m.agent,o=m.cwd||o,a=m.approvalMode??a,l=m.pendingApproval??l,c=m.title||c,u=m.createdAt||u,d=m.lastActivityAt||d,f=Ie(m.acceptedClientMessageIds,f),h=Ie(m.interruptedClientMessageIds,h),p="record";else if(!r){let w=(await bn(n??i)).find(K=>K.sessionId===e);w&&(i=w.agent,o=w.cwd||o,c=w.title??c,u=w.createdAt,d=w.lastActivityAt,g=w.runtime.isResponding??g,p="scanner")}if(!i&&n&&(i=n,p=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,interruptedClientMessageIds:h,source:p,managed:r?.managed??m?.managed,isResponding:g||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(sd(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(sd(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(me(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<=td?n:`${n.slice(0,Math.max(1,td-3)).trimEnd()}...`:gv}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(me(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;_.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return bn(e,n)}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Tr({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},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Lr(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,od.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return b.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(l){b.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;b.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let p={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,p),this.registerClaudeHookSession(p),this.store.upsert(me(p)),this.updateGauges(),Er(),vr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(p,e);return}let u=_.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();b.info({sessionId:d,agent:r,spawnMs:f},"session created"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let h={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(me(h)),this.updateGauges(),Er(),vr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){b.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await wn(r,s,a.cwd),h=this.annotateHistoryMessages(f,a.acceptedClientMessageIds,a.interruptedClientMessageIds),g=this.currentPartialReplyText(a);if(f.length>0||g||a.approvalMode||a.pendingApproval){let p={type:"session.history",sessionId:r,messages:h,...Br(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:g,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(p))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=_.startTimer("driver.spawn"),h=this.createDriver(s),g=this.configureDriverBeforeStart(s,h),p=await h.start(c,r,u),m=f();b.info({sessionId:p,agent:s,spawnMs:m},"session resumed"),_.increment("session.resume",{agent:s}),I.emit("session.resume",{sessionId:p,agent:s,cwd:c});let v={sessionId:p,agent:s,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],interruptedClientMessageIds:l?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(p,v),this.registerClaudeHookSession(v),this.store.upsert(me(v)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(v,s," (resumed)",e),this.restoreDriverPendingApproval(h,v.pendingApproval);let w=await wn(r,s,c),K=this.annotateHistoryMessages(w,v.acceptedClientMessageIds,v.interruptedClientMessageIds);if(w.length>0||v.pendingApproval){b.info({sessionId:r,historyCount:w.length},"sending history messages");let k={type:"session.history",sessionId:p,messages:K,...Br(v.acceptedClientMessageIds),approvalMode:u,pendingApproval:v.pendingApproval};e.readyState===1&&e.send(JSON.stringify(k))}this.reply(e,n,!0,{sessionId:p})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Lt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Lt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Lt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Lt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let u=0;u<e.length;u+=1)e[u]?.role==="user"&&i.push(u);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,c=i.length-o;for(let u=0;u<o;u+=1){let d=n[l+u];s.has(d)&&a.set(i[c+u],"interrupted")}return a.size===0?e:e.map((u,d)=>u.role==="user"&&a.has(d)?{...u,delivery:"interrupted"}:u)}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:f.agent,source:f.source}),I.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let h=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,h,c?.claudeHookSecret);await h.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(h,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=h,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=Ie(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.interruptedClientMessageIds=Ie(c.interruptedClientMessageIds,f.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:h,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,interruptedClientMessageIds:f.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(me(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(h){this.reply(e,n,!1,void 0,`Failed to reconnect: ${h}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),I.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),nd(c),xt(c.title)){let f=mi(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(me(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
100
+ `):""}function zy(t){let e=Vy(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 ju(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Er(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Ei()}}function Tt(t,e){let n=(0,L.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 Yy(t,e){let n=await qu(t,e),r=Uu(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Qe([u.customTitle,u.summary])),!l){let d=Mr(u),f=Qe([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Tt("claude",t)||(0,L.basename)(t,".jsonl"),cwd:s,title:o??l??Qe([],a),approvalMode:await Wu(t,"claude",e)}:null}async function Jy(t,e){let n=await qu(t,e),r=Uu(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Qe([u.payload?.title,u.title])),!l){let d=Gu(u),f=d&&!ju(d)?Qe([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Tt("codex",t)||(0,L.basename)(t,".jsonl"),cwd:s,title:o??l??Qe([],a),approvalMode:await Wu(t,"codex",e)}:null}async function Ze(t,e){let n=await(0,M.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Yy(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Jy(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Ou(t,e){let n=(0,L.join)((0,ae.homedir)(),".claude","projects");try{let r;t?r=[Hu(t)]:r=(await(0,M.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,L.join)(n,l),u=await(0,M.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,L.join)(c,d))}let i=await nt(s,tt,async l=>{let c=await(0,M.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await nt(i,tt,async l=>{let c=await Ze(l.path,"claude");return c&&e&&e.push(Er(c)),c})).filter(l=>l!==null).map(l=>Er(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Be.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Bu(t,e){try{let n=await Fu(),r=await nt(n,tt,async i=>{let o=await Ze(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Er(o)),o});return Hy(r.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),r.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Er(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Be.warn({error:String(n)},"failed to list codex sessions"),[]}}async function mu(t){if(!t)return null;let e=`codex-latest:${(0,ae.homedir)()}`,n=kr.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Cr||(Cr=(async()=>{let i=await Fu(),o=await nt(i,tt,async l=>{let c=await Ze(l.path,"codex");return c?{cwd:c.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:c.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return kr.set(e,a),a})().finally(()=>{Cr=null}));let s=(await Cr).get(t);return s?{sessionId:s.sessionId,filePath:s.path}:null}async function bn(t,e,n){let s=`list:${(0,ae.homedir)()}:${t??"all"}:${e??""}`,i=Li.get(s);if(i)return i;let o=Pi.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Ou(e,n);else if(t==="codex")l=await Bu(e,n);else{let[c,u]=await Promise.all([Ou(e,n),Bu(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return Li.set(s,l),l})();return Pi.set(s,a),a.finally(()=>Pi.delete(s)),a}async function Mu(t,e){let r=`search:${(0,ae.homedir)()}:${t}:${e??"all"}`,s=Ni.get(r);if(s)return s;let i=Ri.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,L.join)((0,ae.homedir)(),".claude","projects");try{let f=await(0,M.readdir)(d,{withFileTypes:!0}),h=[];for(let p of f){if(!p.isDirectory())continue;let m=(0,L.join)(d,p.name),v=await(0,M.readdir)(m).catch(()=>[]);for(let b of v)b.endsWith(".jsonl")&&h.push((0,L.join)(m,b))}let g=await nt(h,tt,p=>Du(p,l,"claude"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,L.join)((0,ae.homedir)(),".codex","sessions");try{let f=[];async function h(p){let m=await(0,M.readdir)(p,{withFileTypes:!0}).catch(()=>[]);for(let v of m){let b=(0,L.join)(p,v.name);v.isDirectory()?await h(b):v.name.endsWith(".jsonl")&&f.push(b)}}await h(d);let g=await nt(f,tt,p=>Du(p,l,"codex"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Ni.set(r,a),a})();return Ri.set(r,o),o.finally(()=>Ri.delete(r)),o}async function Du(t,e,n){let r=(0,Bi.createReadStream)(t,{encoding:"utf-8"}),s=(0,Di.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Ky:Qy,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||Tt(n,t):null}function Ky(t){return t?.type==="user"&&t.message?.role==="user"?Mr(t):t?.type==="assistant"&&t.message?.role==="assistant"?Rr(t.message.content):""}function Qy(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Ui(t.payload.content)}let e=Gu(t);return e||""}async function Oi(t,e){let n=(0,Bi.createReadStream)(t,{encoding:"utf-8"}),r=(0,Di.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function $u(t,e){let n=(0,L.join)((0,ae.homedir)(),".claude","projects"),r=e?Hu(e):null,s=await(0,M.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,L.join)(n,o,`${t}.jsonl`);if((await(0,M.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Vu(t,e,n){if(e==="claude")return $u(t,n);let r=(0,L.join)((0,ae.homedir)(),".codex","sessions");return zu(r,t)}function Xy(t){if(t?.type==="user"&&t.message?.role==="user")return $y(t.message.content)?{kind:"toolResult",...zy(t)?{interrupted:!0}:{}}:Mr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Rr(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 Zy(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 Ai(t,e){if(e!=="claude")return{};let n=null;try{await Oi(t,r=>{let s=Xy(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Be.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Zy(n)}async function qi(t,e,n){let r=await Vu(t,e,n);return r?Ai(r,e):{}}async function wn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await $u(t,n);i&&await Oi(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=Mr(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=Rr(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Be.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await Vu(t,e,n);i&&await Oi(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=Ui(o.payload.content);l&&(a==="user"&&ju(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Be.warn({error:String(i)},"failed to read codex session history")}return r}async function zu(t,e){try{let n=await(0,M.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,L.join)(t,r.name);if(r.isDirectory()){let i=await zu(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Be.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Et=require("fs"),Qu=require("path");var ev=500,Yu=200;function Ju(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Yu?e:e.slice(-Yu)}function tv(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 nv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Ku(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Ju(t.acceptedClientMessageIds),interruptedClientMessageIds:Ju(t.interruptedClientMessageIds),pendingApproval:nv(t.pendingApproval)}}function rv(t){if(Array.isArray(t))return{records:t.map(Ku),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Ku):[],deletedSessionIds:tv(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var Lr=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},ev)}loadFromDisk(){try{let e=(0,Et.readFileSync)(ir,"utf-8");return rv(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,Et.mkdirSync)((0,Qu.dirname)(ir),{recursive:!0}),(0,Et.writeFileSync)(ir,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Pt=require("path"),Xu=require("os");function Nr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Pt.join)((0,Xu.homedir)(),t.slice(2)):t}function sv(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function Wi(t,e){let n=Nr(sv(t));if(!n||(0,Pt.isAbsolute)(n))return n;let r=Nr(e??"");return r?(0,Pt.resolve)(r,n):n}var Zu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Rt=require("fs"),ed=require("path");function iv(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function ov(t){try{let e=(0,Rt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(iv):[]}catch{return[]}}function In(t,e){(0,Rt.mkdirSync)((0,ed.dirname)(t),{recursive:!0}),(0,Rt.writeFileSync)(t,JSON.stringify(e,null,2)+`
101
+ `,"utf8")}var Or=class{constructor(e=bc){this.pushSubscriptionsPath=e;this.records=ov(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],In(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,In(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,In(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&In(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],In(this.pushSubscriptionsPath,this.records)}};var Y=R.child({module:"push"}),av="https://exp.host/--/api/v2/push/send",lv="https://exp.host/--/api/v2/push/getReceipts",cv=[0,1e3,3e3],An=new Or;function uv(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 dv(t){return new Promise(e=>{setTimeout(e,t)})}function td(t){return t==="DeviceNotRegistered"}function fv(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function pv(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function hv(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function gv(t,e,n,r){let s=new Map(t);for(let i of cv){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(lv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){Y.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){Y.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){Y.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=hv(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(Y.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),td(f)){let h=r.unregisterToken(u);Y.info({token:u,errorCode:f,removed:h},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&Y.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function mv(t){let e=t?.pushStore??An,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??dv;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...uv(a)&&a.eventType==="approval_request"?{categoryId:Zu.approvalRequestV1}:{}}));try{let u=await n(av,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){Y.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){Y.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:h}=fv(d,l),g=pv(d,l);for(let{token:p,ticket:m}of h){let v=m.details?.error;if(Y.error({token:p,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),td(v)){let b=e.unregisterToken(p);Y.info({token:p,errorCode:v,removed:b},"push token removed after ticket rejection")}}f.length>0&&(Y.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await gv(g,n,r,e)}catch(u){Y.error({error:String(u)},"push send error")}}}function Gi(t,e){An.register(t,e),Y.info({deviceId:t,token:e,total:An.count()},"push token registered")}function ji(t,e){let n=An.unregister(t,e);Y.info({deviceId:t,token:e,total:An.count(),removed:n},"push token unregistered")}var Br=mv();var w=R.child({module:"manager"}),yv="Done.",vv="Approval required",nd=180,Mt=200;function Ie(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>Mt&&e.splice(0,e.length-Mt));return e}function Dr(t){return t?.length?{acceptedClientMessageIds:Ie(t)}:{}}function me(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:Ie(t.acceptedClientMessageIds),interruptedClientMessageIds:Ie(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function rd(t){t.managed||(t.managed=!0)}function sd(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&pr(e)}function id(t,e,n){return{sessionId:t,agent:e,...n}}function Sv(t){return t.startsWith(di)}function od(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 Hr=class{constructor(e=Br,n=gu){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=Tu(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new Lr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs,r=S.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(w.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;w.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:o.agent}),I.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(w.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:o.agent}),I.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){w.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(w.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!sd(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){I.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(vv,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"&&pr(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")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){w.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}w.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),I.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o}),_.increment("driver.exit",{agent:n,abnormal:o&&o!==0?"true":"false"});let a=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&sd(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",a||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){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.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(me(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){w.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,w.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){w.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof pn&&s&&n.setModel(s),e!=="claude"||!(n instanceof fn))return;let i=r??(0,$i.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=dn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&Sv(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),dn;if(r.approvalMode==="autoApprove")return od(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return dn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${di}${l.trim()||(0,$i.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},I.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=Ie(r?.acceptedClientMessageIds),h=Ie(r?.interruptedClientMessageIds),g=r?.isResponding,p=r?"memory":"client",m=this.store.find(e);if(m)i=m.agent,o=m.cwd||o,a=m.approvalMode??a,l=m.pendingApproval??l,c=m.title||c,u=m.createdAt||u,d=m.lastActivityAt||d,f=Ie(m.acceptedClientMessageIds,f),h=Ie(m.interruptedClientMessageIds,h),p="record";else if(!r){let b=(await bn(n??i)).find(W=>W.sessionId===e);b&&(i=b.agent,o=b.cwd||o,c=b.title??c,u=b.createdAt,d=b.lastActivityAt,g=b.runtime.isResponding??g,p="scanner")}if(!i&&n&&(i=n,p=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,interruptedClientMessageIds:h,source:p,managed:r?.managed??m?.managed,isResponding:g||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(id(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(id(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(me(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<=nd?n:`${n.slice(0,Math.max(1,nd-3)).trimEnd()}...`:yv}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(me(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;_.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return bn(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.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){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(){Tr({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},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Nr(s),w.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,ad.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return w.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,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(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;w.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let p={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,p),this.registerClaudeHookSession(p),this.store.upsert(me(p)),this.updateGauges(),Pr(),Sr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(p,e);return}let u=_.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();w.info({sessionId:d,agent:r,spawnMs:f},"session created"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let h={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(me(h)),this.updateGauges(),Pr(),Sr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){w.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await wn(r,s,a.cwd),h=this.annotateHistoryMessages(f,a.acceptedClientMessageIds,a.interruptedClientMessageIds),g=this.currentPartialReplyText(a);if(f.length>0||g||a.approvalMode||a.pendingApproval){let p={type:"session.history",sessionId:r,messages:h,...Dr(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:g,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(p))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=_.startTimer("driver.spawn"),h=this.createDriver(s),g=this.configureDriverBeforeStart(s,h),p=await h.start(c,r,u),m=f();w.info({sessionId:p,agent:s,spawnMs:m},"session resumed"),_.increment("session.resume",{agent:s}),I.emit("session.resume",{sessionId:p,agent:s,cwd:c});let v={sessionId:p,agent:s,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],interruptedClientMessageIds:l?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(p,v),this.registerClaudeHookSession(v),this.store.upsert(me(v)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(v,s," (resumed)",e),this.restoreDriverPendingApproval(h,v.pendingApproval);let b=await wn(r,s,c),W=this.annotateHistoryMessages(b,v.acceptedClientMessageIds,v.interruptedClientMessageIds);if(b.length>0||v.pendingApproval){w.info({sessionId:r,historyCount:b.length},"sending history messages");let x={type:"session.history",sessionId:p,messages:W,...Dr(v.acceptedClientMessageIds),approvalMode:u,pendingApproval:v.pendingApproval};e.readyState===1&&e.send(JSON.stringify(x))}this.reply(e,n,!0,{sessionId:p})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Mt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Mt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Mt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Mt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let u=0;u<e.length;u+=1)e[u]?.role==="user"&&i.push(u);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,c=i.length-o;for(let u=0;u<o;u+=1){let d=n[l+u];s.has(d)&&a.set(i[c+u],"interrupted")}return a.size===0?e:e.map((u,d)=>u.role==="user"&&a.has(d)?{...u,delivery:"interrupted"}:u)}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){w.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:f.agent,source:f.source}),I.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let h=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,h,c?.claudeHookSecret);await h.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(h,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=h,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=Ie(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.interruptedClientMessageIds=Ie(c.interruptedClientMessageIds,f.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:h,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,interruptedClientMessageIds:f.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(me(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(h){this.reply(e,n,!1,void 0,`Failed to reconnect: ${h}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(w.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),I.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),rd(c),xt(c.title)){let f=yi(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(me(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
102
102
  `):"",d=u?s?`${s}
103
103
 
104
- ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let c=this.getDeletedSessionIds(),u;try{u=await Tr({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(h){b.warn({error:String(h)},"failed to build reconnect snapshot session list"),u={sessions:[],nextCursor:void 0}}u={...u,inventoryVersion:this.inventoryVersion};let d;if(o&&!c.has(o)){let h=a??u.sessions.find(m=>m.sessionId===o)?.agent,g=this.sessions.get(o);g&&g.clients.add(e);let p=await this.resolveReconnectSession(o,h,g);if(p){let m=await wn(o,p.agent,g?.cwd??p.cwd),v=this.annotateHistoryMessages(m,g?.acceptedClientMessageIds??p.acceptedClientMessageIds,g?.interruptedClientMessageIds??p.interruptedClientMessageIds),w=g?{}:await Ui(o,p.agent,p.cwd);d={sessionId:o,agent:p.agent,messages:v,...Br(g?.acceptedClientMessageIds??p.acceptedClientMessageIds),isResponding:g?.isResponding??w.isResponding??p.isResponding,partialReplyText:g?this.currentPartialReplyText(g):w.partialReplyText,approvalMode:g?.approvalMode??p.approvalMode,...g?.pendingApproval?{pendingApproval:g.pendingApproval}:{}}}}let f=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:u.sessions,nextCursor:u.nextCursor,inventoryVersion:u.inventoryVersion,...d?{activeSession:d}:{},...f.length>0?{pendingApprovals:f}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(id(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&pr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(me(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(me(i)),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("session.interrupt",{sessionId:r,agent:s.agent}),!s.driver){(s.isResponding||s.bufferedPrompts.length>0)&&(b.info({sessionId:r,agent:s.agent},"interrupting driverless session with stale responding state"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId})),this.reply(e,n,!0);return}if(s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;b.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:s.agent},"stopping session"),I.emit("session.stop",{sessionId:r,agent:s.agent}),nd(s);let i=s.isResponding||s.bufferedPrompts.length>0||s.startupInProgress;this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.isResponding=!1,s.currentReplyText="",s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(b.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),I.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Er(),vr(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r),o=i?.active?i:void 0;if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let a=o?.cwd??i?.cwd??this.store.find(r)?.cwd??"",l=this.store.find(r),c=await wn(r,s,a),u=this.annotateHistoryMessages(c,i?.acceptedClientMessageIds??l?.acceptedClientMessageIds,i?.interruptedClientMessageIds??l?.interruptedClientMessageIds),d=o||i?{}:await Ui(r,s,a),f=o?.isResponding??d.isResponding,h=o?this.currentPartialReplyText(o):d.partialReplyText;b.info({sessionId:r,historyCount:c.length,isResponding:f,approvalMode:i?.approvalMode??l?.approvalMode},"sending history");let g={type:"session.history",sessionId:r,messages:u,...Br(i?.acceptedClientMessageIds??l?.acceptedClientMessageIds),isResponding:f,partialReplyText:h,approvalMode:i?.approvalMode??l?.approvalMode,pendingApproval:i?.pendingApproval??l?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a,l){try{let c=await Tr({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...c,inventoryVersion:this.inventoryVersion})}catch(c){this.reply(e,n,!1,void 0,String(c))}}createDriver(e){switch(e){case"claude":return new fn;case"codex":return new pn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function $i(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var ad=require("child_process");function vv(t,e){return(0,ad.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Sv(t){let e=t.split(`
105
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function ld(t,e=vv){let n;try{n=Sv(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var Nt=require("fs"),Vi=require("os"),ud=require("crypto"),dd=require("path");function fd(t){return(0,ud.randomBytes)(t).toString("base64url")}function _v(){return`d_${fd(12)}`}function bv(){return(0,Vi.hostname)()}function wv(){let t=(0,Vi.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Iv(t){return{daemonId:_v(),daemonSecret:fd(32),displayName:bv(),canonicalHost:wv(),port:t,createdAt:new Date().toISOString()}}function cd(t,e){(0,Nt.mkdirSync)((0,dd.dirname)(e),{recursive:!0}),(0,Nt.writeFileSync)(e,JSON.stringify(t,null,2)+`
106
- `,"utf8")}function pd(t,e=vc){try{let r=(0,Nt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,cd(i,e)),i}}catch{}let n=Iv(t);return cd(n,e),n}var Ot=require("crypto"),Bt=require("fs"),gd=require("path");function zi(t){return(0,Ot.randomBytes)(t).toString("base64url")}function Yi(t){return(0,Ot.createHash)("sha256").update(t).digest("hex")}function hd(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Ot.timingSafeEqual)(n,r)}function Av(t){try{let e=(0,Bt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function Tn(t,e){(0,Bt.mkdirSync)((0,gd.dirname)(t),{recursive:!0}),(0,Bt.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
- `,"utf8")}var Hr=class{constructor(e=Sc){this.pairingsPath=e;this.records=Av(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${zi(8)}`,s=zi(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=zi(32),i={deviceId:e,deviceName:n,tokenHash:Yi(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Tn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Yi(n);return hd(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),Tn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Yi(e),s=this.records.find(i=>!i.revokedAt&&hd(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),Tn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Tn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Tn(this.pairingsPath,this.records)}};function rt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Tv(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Ji(t,e){return Tv(t)??e}function Fr(t,e){return!!(t&&e&&t===e)}function Ki(t,e,n,r=!0){return t?Fr(t,e)?!0:!!n(t,r):!1}var vd=require("child_process");function Ur(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Qi(t){if(!Ur(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function xv(t){if(!Ur(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Cv(t){if(!Ur(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function kv(t){if(!Ur(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function qr(t){return!!t&&!xv(t)&&!Cv(t)}function le(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Xi(t){return le(t.replace(/^https?:\/\//,""))??t}function Ev(t,e){return(t??[]).map(n=>le(n)).filter(n=>!!n).filter(n=>qr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Pv(t){let e=Xi(t);return Qi(e)||e.endsWith(".ts.net")}function Rv(t){let e=Xi(t);return kv(e)||e.endsWith(".local")}function Mv(t){return Xi(t).endsWith(".trycloudflare.com")}function md(t,e){return Pv(t)?"tailscale":Rv(t)?"local_network":e?"configured_host":"fallback"}function Sd(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}`;e.has(s)||(e.add(s),n.push(r))}return n}function Lv(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function Nv(t){try{let e=new URL(t),n=le(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=Mv(n);return{kind:"relay",host:n,port:s,source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function Ov(t,e,n){let r=le(t)||"localhost",s=Ev(e,r);return Sd([{kind:"direct",host:r,port:n,source:md(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:md(i,!1),stability:"stable"}))])}function _d(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Bv(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||qr(s.address)&&(Qi(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function yd(t){let e=JSON.parse(t),n=le(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>le(o)).filter(o=>!!o).filter(o=>Qi(o)&&qr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function bd(t=vd.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return yd(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return yd(n)}catch{return{fallbackHosts:[]}}}function wd(t){let e=Ov(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?Nv(t.relayUrl):null,r=Sd([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:le(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:Lv(r),port:s.port,connections:r}}function Id(t){let e=le(t.canonicalHost),n=le(t.configuredCanonicalHost)||le(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Bv(t.interfaces)].map(s=>le(s)).filter(s=>!!s).filter(s=>qr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Ad(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 q=R.child({module:"daemon"}),xn=R.child({module:"ws"});function Dv(){try{let t=JSON.parse(require("fs").readFileSync(bc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var D=pd(S.port),J=new Dr((t,e,n)=>Or(t,e,{daemonId:D.daemonId,canonicalHost:Cn().canonicalHost,...n??{}})),ue=new Hr,Gr=new Set,De=new WeakMap,Td=!1,Ed=Date.now(),Dt=null,Wr=null,Hv=1e3;function Fv(){let t=bd();return Id({canonicalHost:D.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:_d(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,kd.networkInterfaces)()})}function Cn(){let t=Date.now();if(Wr&&Wr.expiresAt>t)return Wr.value;let e=Fv(),n=wd({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:D.port,relayUrl:S.relayUrl});return Wr={value:n,expiresAt:t+Hv},n}function Uv(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability])),e}async function qv(t){let e=JSON.stringify(Uv(t));await(0,re.mkdir)(we,{recursive:!0}),await to.default.toFile(si,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await to.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});It(`
104
+ ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let c=this.getDeletedSessionIds(),u;try{u=await Tr({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(h){w.warn({error:String(h)},"failed to build reconnect snapshot session list"),u={sessions:[],nextCursor:void 0}}u={...u,inventoryVersion:this.inventoryVersion};let d;if(o&&!c.has(o)){let h=a??u.sessions.find(m=>m.sessionId===o)?.agent,g=this.sessions.get(o);g&&g.clients.add(e);let p=await this.resolveReconnectSession(o,h,g);if(p){let m=await wn(o,p.agent,g?.cwd??p.cwd),v=this.annotateHistoryMessages(m,g?.acceptedClientMessageIds??p.acceptedClientMessageIds,g?.interruptedClientMessageIds??p.interruptedClientMessageIds),b=g?{}:await qi(o,p.agent,p.cwd),W=!g&&!!b.isResponding,x=W?await this.externalProcessPresenceCheck(o):!1,N=W&&!x?{}:b;d={sessionId:o,agent:p.agent,messages:v,...Dr(g?.acceptedClientMessageIds??p.acceptedClientMessageIds),isResponding:g?.isResponding??N.isResponding??(W&&!x?void 0:p.isResponding),...x?{externallyResponding:!0}:{},partialReplyText:g?this.currentPartialReplyText(g):N.partialReplyText,approvalMode:g?.approvalMode??p.approvalMode,...g?.pendingApproval?{pendingApproval:g.pendingApproval}:{}}}}let f=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:u.sessions,nextCursor:u.nextCursor,inventoryVersion:u.inventoryVersion,...d?{activeSession:d}:{},...f.length>0?{pendingApprovals:f}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(od(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&pr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(me(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),w.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):w.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(me(i)),this.noteInventoryChanged("session_updated"),w.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("session.interrupt",{sessionId:r,agent:s.agent}),!s.driver){(s.isResponding||s.bufferedPrompts.length>0)&&(w.info({sessionId:r,agent:s.agent},"interrupting driverless session with stale responding state"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId})),this.reply(e,n,!0);return}if(s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;w.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:s.agent},"stopping session"),I.emit("session.stop",{sessionId:r,agent:s.agent}),rd(s);let i=s.isResponding||s.bufferedPrompts.length>0||s.startupInProgress;this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.isResponding=!1,s.currentReplyText="",s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(w.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),I.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Pr(),Sr(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r),o=i?.active?i:void 0;if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let a=o?.cwd??i?.cwd??this.store.find(r)?.cwd??"",l=this.store.find(r),c=await wn(r,s,a),u=this.annotateHistoryMessages(c,i?.acceptedClientMessageIds??l?.acceptedClientMessageIds,i?.interruptedClientMessageIds??l?.interruptedClientMessageIds),d=o||i?{}:await qi(r,s,a),f=!o&&!!d.isResponding,h=f?await this.externalProcessPresenceCheck(r):!1,g=h?!0:void 0,p=f&&!h?{}:d,m=o?.isResponding??p.isResponding,v=o?this.currentPartialReplyText(o):p.partialReplyText;w.info({sessionId:r,historyCount:c.length,isResponding:m,externallyResponding:g,approvalMode:i?.approvalMode??l?.approvalMode},"sending history");let b={type:"session.history",sessionId:r,messages:u,...Dr(i?.acceptedClientMessageIds??l?.acceptedClientMessageIds),isResponding:m,externallyResponding:g,partialReplyText:v,approvalMode:i?.approvalMode??l?.approvalMode,pendingApproval:i?.pendingApproval??l?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(b)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a,l){try{let c=await Tr({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...c,inventoryVersion:this.inventoryVersion})}catch(c){this.reply(e,n,!1,void 0,String(c))}}createDriver(e){switch(e){case"claude":return new fn;case"codex":return new pn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function Vi(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var ld=require("child_process");function _v(t,e){return(0,ld.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function bv(t){let e=t.split(`
105
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function cd(t,e=_v){let n;try{n=bv(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var Lt=require("fs"),zi=require("os"),dd=require("crypto"),fd=require("path");function pd(t){return(0,dd.randomBytes)(t).toString("base64url")}function wv(){return`d_${pd(12)}`}function Iv(){return(0,zi.hostname)()}function Av(){let t=(0,zi.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function xv(t){return{daemonId:wv(),daemonSecret:pd(32),displayName:Iv(),canonicalHost:Av(),port:t,createdAt:new Date().toISOString()}}function ud(t,e){(0,Lt.mkdirSync)((0,fd.dirname)(e),{recursive:!0}),(0,Lt.writeFileSync)(e,JSON.stringify(t,null,2)+`
106
+ `,"utf8")}function hd(t,e=Sc){try{let r=(0,Lt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,ud(i,e)),i}}catch{}let n=xv(t);return ud(n,e),n}var Nt=require("crypto"),Ot=require("fs"),md=require("path");function Yi(t){return(0,Nt.randomBytes)(t).toString("base64url")}function Ji(t){return(0,Nt.createHash)("sha256").update(t).digest("hex")}function gd(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Nt.timingSafeEqual)(n,r)}function Tv(t){try{let e=(0,Ot.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function xn(t,e){(0,Ot.mkdirSync)((0,md.dirname)(t),{recursive:!0}),(0,Ot.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
+ `,"utf8")}var Fr=class{constructor(e=_c){this.pairingsPath=e;this.records=Tv(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${Yi(8)}`,s=Yi(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=Yi(32),i={deviceId:e,deviceName:n,tokenHash:Ji(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),xn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Ji(n);return gd(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),xn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ji(e),s=this.records.find(i=>!i.revokedAt&&gd(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),xn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),xn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),xn(this.pairingsPath,this.records)}};function rt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Cv(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Ki(t,e){return Cv(t)??e}function Ur(t,e){return!!(t&&e&&t===e)}function Qi(t,e,n,r=!0){return t?Ur(t,e)?!0:!!n(t,r):!1}var Sd=require("child_process");function qr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Xi(t){if(!qr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function kv(t){if(!qr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Ev(t){if(!qr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Pv(t){if(!qr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function Wr(t){return!!t&&!kv(t)&&!Ev(t)}function le(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Zi(t){return le(t.replace(/^https?:\/\//,""))??t}function Rv(t,e){return(t??[]).map(n=>le(n)).filter(n=>!!n).filter(n=>Wr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Mv(t){let e=Zi(t);return Xi(e)||e.endsWith(".ts.net")}function Lv(t){let e=Zi(t);return Pv(e)||e.endsWith(".local")}function Nv(t){return Zi(t).endsWith(".trycloudflare.com")}function yd(t,e){return Mv(t)?"tailscale":Lv(t)?"local_network":e?"configured_host":"fallback"}function _d(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}`;e.has(s)||(e.add(s),n.push(r))}return n}function Ov(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function Bv(t){try{let e=new URL(t),n=le(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=Nv(n);return{kind:"relay",host:n,port:s,source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function Dv(t,e,n){let r=le(t)||"localhost",s=Rv(e,r);return _d([{kind:"direct",host:r,port:n,source:yd(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:yd(i,!1),stability:"stable"}))])}function bd(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Hv(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||Wr(s.address)&&(Xi(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function vd(t){let e=JSON.parse(t),n=le(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>le(o)).filter(o=>!!o).filter(o=>Xi(o)&&Wr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function wd(t=Sd.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return vd(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return vd(n)}catch{return{fallbackHosts:[]}}}function Id(t){let e=Dv(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?Bv(t.relayUrl):null,r=_d([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:le(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:Ov(r),port:s.port,connections:r}}function Ad(t){let e=le(t.canonicalHost),n=le(t.configuredCanonicalHost)||le(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Hv(t.interfaces)].map(s=>le(s)).filter(s=>!!s).filter(s=>Wr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function xd(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 q=R.child({module:"daemon"}),Tn=R.child({module:"ws"});function Fv(){try{let t=JSON.parse(require("fs").readFileSync(wc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var H=hd(S.port),K=new Hr((t,e,n)=>Br(t,e,{daemonId:H.daemonId,canonicalHost:Cn().canonicalHost,...n??{}})),ue=new Fr,jr=new Set,De=new WeakMap,Td=!1,Pd=Date.now(),Bt=null,Gr=null,Uv=1e3;function qv(){let t=wd();return Ad({canonicalHost:H.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:bd(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Ed.networkInterfaces)()})}function Cn(){let t=Date.now();if(Gr&&Gr.expiresAt>t)return Gr.value;let e=qv(),n=Id({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:H.port,relayUrl:S.relayUrl});return Gr={value:n,expiresAt:t+Uv},n}function Wv(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability])),e}async function Gv(t){let e=JSON.stringify(Wv(t));await(0,re.mkdir)(we,{recursive:!0}),await no.default.toFile(ii,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await no.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});It(`
108
108
  Scan this QR code with Vibelet app:
109
109
 
110
110
  ${n}
111
111
  `),It(`If Vibelet app can't scan the terminal QR, open this PNG instead:
112
- ${si}
113
- `)}async function Zi(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function N(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function Wv(t){let e=(0,kn.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 Pd(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function Gv(t,e){if(rt(t.socket.remoteAddress))return!0;let n=Ji(t.headers.authorization,e.searchParams.get("token"));return Ki(n,S.legacyToken,(r,s)=>ue.validateAnyPairToken(r,s),!1)}function jv(){let t=ue.openWindow(Pd(),S.pairReusable),e=Cn();return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function $v(t,e){let n=qi(t,e),r=await(0,re.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,re.stat)((0,kn.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var En=(0,xd.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=Cn(),i=Dv(),o={status:"ok",version:Tt,...i?{latestVersion:i}:{}};if(!Gv(t,n)){N(e,200,o);return}let a={...o,status:"ok",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Ed)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:ue.pairedCount(),wsClients:ce.clients.size,drivers:J.getDriverCounts(),sessionInventory:xu(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),N(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,jv());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}ue.reset(),N(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,{status:"stopping"}),setTimeout(()=>st("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Zi(t),i=t.headers[un],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),N(e,200,{ok:!0})}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Zi(t),i=t.headers[un],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);N(e,200,a)}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await Zi(t);if(s.daemonId!==D.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){N(e,400,{error:"invalid_pair_request"});return}if(!ue.consumeWindow(s.pairNonce)){N(e,401,{error:"pair_window_expired"});return}let o=ue.issuePairToken(s.deviceId,s.deviceName),a=Cn();N(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=Ji(t.headers.authorization,n.searchParams.get("token"));if(!Ki(r,S.legacyToken,(s,i)=>ue.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){N(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,re.mkdir)(ri,{recursive:!0});let u=`${Date.now()}_${(0,Cd.randomBytes)(8).toString("hex")}${o}`,d=(0,kn.join)(ri,u);await(0,re.writeFile)(d,Buffer.concat(l)),q.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){q.error({error:String(u)},"upload failed"),N(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=qi(s,i);if(!(await(0,re.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=Wv(o),c=await(0,re.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${Tt}`)}),ce=new fs.default({server:En});En.on("connection",t=>{Gr.add(t),t.on("close",()=>{Gr.delete(t)})});ce.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Fr(r,S.legacyToken))De.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=ue.validateAnyPairToken(r);if(s)De.set(t,{authMode:"query_token",deviceId:s.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}xn.info({clients:ce.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",ce.clients.size),I.emit("ws.connect",{clients:ce.clients.size,authMode:De.get(t)?.authMode??"pending",deviceId:De.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Ad(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!De.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Fr(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===D.daemonId&&ue.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===D.daemonId){let l=ue.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){De.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),_.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:D.daemonId,displayName:D.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)I.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?q.error:a.level==="warn"?q.warn:q.info).call(q,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await $v(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=De.get(t);$i(i,{deviceId:a?.deviceId,registerToken:Wi,unregisterToken:Gi,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=De.get(t);$i(i,{deviceId:a?.deviceId,registerToken:Wi,unregisterToken:Gi,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){xn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{xn.info({clients:ce.clients.size,code:s},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(s)}),_.gauge("ws.clients",ce.clients.size),I.emit("ws.disconnect",{clients:ce.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{xn.error({error:s.message},"websocket error")})});function eo(){for(let t of Gr)try{t.destroy()}catch{}Gr.clear()}function Rd(){let t=Rc({auditPath:wt,stdoutLogPath:or,stderrLogPath:ar,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&q.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 Vv(){Dt||(Dt=setInterval(Rd,S.storageHousekeepingIntervalMs),Dt.unref())}function zv(){Dt&&(clearInterval(Dt),Dt=null)}function st(t,e=0){if(!Td){Td=!0,q.info({reason:t,exitCode:e},"shutting down"),I.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Ed)/1e3)}),_.stopPeriodicLog(),zv(),kt.stop().catch(()=>{}),J.shutdown();for(let n of ce.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ce.close(n=>{n&&q.error({error:String(n)},"websocket close error")}),En.close(n=>{if(n){q.error({error:String(n)},"http close error"),eo(),process.exit(1);return}eo(),process.exit(e)}),setTimeout(()=>{q.error("force exiting after shutdown timeout"),eo(),process.exit(e||1)},3e3).unref()}}ce.on("error",t=>{xn.error({error:t.message},"wss error")});En.on("error",t=>{if(t.code==="EADDRINUSE"){let e=ld(S.port).filter(n=>n.pid!==process.pid);q.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else q.error({error:String(t)},"server error");st(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>st("SIGINT"));process.once("SIGTERM",()=>st("SIGTERM"));process.once("SIGHUP",()=>st("SIGHUP"));process.once("SIGTTIN",()=>st("SIGTTIN"));process.once("SIGTSTP",()=>st("SIGTSTP"));process.on("uncaughtException",t=>{q.error({error:String(t),stack:t.stack},"uncaughtException"),I.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{q.error({reason:String(t)},"unhandledRejection"),I.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});En.listen(S.port,async()=>{Rd(),I.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),Vv(),Cu(),kt.start().catch(r=>{q.warn({error:String(r)},"session activity watcher failed to start")});let t=Cn();q.info({port:S.port,pairingPort:t.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=ue.openWindow(Pd(),S.pairReusable),n={type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};It(`
112
+ ${ii}
113
+ `)}async function eo(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function O(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function jv(t){let e=(0,kn.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 Rd(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function $v(t,e){if(rt(t.socket.remoteAddress))return!0;let n=Ki(t.headers.authorization,e.searchParams.get("token"));return Qi(n,S.legacyToken,(r,s)=>ue.validateAnyPairToken(r,s),!1)}function Vv(){let t=ue.openWindow(Rd(),S.pairReusable),e=Cn();return{type:"vibelet-pair",daemonId:H.daemonId,displayName:H.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 zv(t,e){let n=Wi(t,e),r=await(0,re.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,re.stat)((0,kn.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var En=(0,Cd.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=Cn(),i=Fv(),o={status:"ok",version:At,...i?{latestVersion:i}:{}};if(!$v(t,n)){O(e,200,o);return}let a={...o,status:"ok",daemonId:H.daemonId,displayName:H.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Pd)/1e3),activeSessions:K.getActiveSessionCount(),pairedDevices:ue.pairedCount(),wsClients:ce.clients.size,drivers:K.getDriverCounts(),sessionInventory:Cu(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),O(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!rt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}O(e,200,Vv());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!rt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}ue.reset(),O(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!rt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}O(e,200,{status:"stopping"}),setTimeout(()=>st("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!rt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}try{let s=await eo(t),i=t.headers[un],o=Array.isArray(i)?i[0]:i;K.handleClaudeSessionStartHook(o,s),O(e,200,{ok:!0})}catch(s){O(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!rt(t.socket.remoteAddress)){O(e,403,{error:"forbidden"});return}try{let s=await eo(t),i=t.headers[un],o=Array.isArray(i)?i[0]:i,a=await K.handleClaudePermissionHook(o,s);O(e,200,a)}catch(s){O(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await eo(t);if(s.daemonId!==H.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){O(e,400,{error:"invalid_pair_request"});return}if(!ue.consumeWindow(s.pairNonce)){O(e,401,{error:"pair_window_expired"});return}let o=ue.issuePairToken(s.deviceId,s.deviceName),a=Cn();O(e,200,{daemonId:H.daemonId,displayName:H.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){O(e,400,{error:String(s)})}return}let r=Ki(t.headers.authorization,n.searchParams.get("token"));if(!Qi(r,S.legacyToken,(s,i)=>ue.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){O(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,re.mkdir)(si,{recursive:!0});let u=`${Date.now()}_${(0,kd.randomBytes)(8).toString("hex")}${o}`,d=(0,kn.join)(si,u);await(0,re.writeFile)(d,Buffer.concat(l)),q.info({filePath:d,size:c},"file uploaded"),O(e,200,{path:d})}catch(u){q.error({error:String(u)},"upload failed"),O(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=Wi(s,i);if(!(await(0,re.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=jv(o),c=await(0,re.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${At}`)}),ce=new ps.default({server:En});En.on("connection",t=>{jr.add(t),t.on("close",()=>{jr.delete(t)})});ce.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Ur(r,S.legacyToken))De.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),K.addGlobalClient(t),K.prewarmCaches();else if(r){let s=ue.validateAnyPairToken(r);if(s)De.set(t,{authMode:"query_token",deviceId:s.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),K.addGlobalClient(t),K.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}Tn.info({clients:ce.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",ce.clients.size),I.emit("ws.connect",{clients:ce.clients.size,authMode:De.get(t)?.authMode??"pending",deviceId:De.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(xd(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!De.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Ur(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===H.daemonId&&ue.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===H.daemonId){let l=ue.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){De.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),_.increment("ws.auth.success",{mode:"auth_hello"}),K.addGlobalClient(t),K.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:H.daemonId,displayName:H.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)I.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?q.error:a.level==="warn"?q.warn:q.info).call(q,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await zv(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=De.get(t);Vi(i,{deviceId:a?.deviceId,registerToken:Gi,unregisterToken:ji,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=De.get(t);Vi(i,{deviceId:a?.deviceId,registerToken:Gi,unregisterToken:ji,respond:l=>t.send(JSON.stringify(l))});return}await K.handle(t,o)}catch(i){Tn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{Tn.info({clients:ce.clients.size,code:s},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(s)}),_.gauge("ws.clients",ce.clients.size),I.emit("ws.disconnect",{clients:ce.clients.size,code:s}),K.removeClient(t)}),t.on("error",s=>{Tn.error({error:s.message},"websocket error")})});function to(){for(let t of jr)try{t.destroy()}catch{}jr.clear()}function Md(){let t=Mc({auditPath:wt,stdoutLogPath:or,stderrLogPath:ar,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&q.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 Yv(){Bt||(Bt=setInterval(Md,S.storageHousekeepingIntervalMs),Bt.unref())}function Jv(){Bt&&(clearInterval(Bt),Bt=null)}function st(t,e=0){if(!Td){Td=!0,q.info({reason:t,exitCode:e},"shutting down"),I.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Pd)/1e3)}),_.stopPeriodicLog(),Jv(),Ct.stop().catch(()=>{}),K.shutdown();for(let n of ce.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ce.close(n=>{n&&q.error({error:String(n)},"websocket close error")}),En.close(n=>{if(n){q.error({error:String(n)},"http close error"),to(),process.exit(1);return}to(),process.exit(e)}),setTimeout(()=>{q.error("force exiting after shutdown timeout"),to(),process.exit(e||1)},3e3).unref()}}ce.on("error",t=>{Tn.error({error:t.message},"wss error")});En.on("error",t=>{if(t.code==="EADDRINUSE"){let e=cd(S.port).filter(n=>n.pid!==process.pid);q.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else q.error({error:String(t)},"server error");st(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>st("SIGINT"));process.once("SIGTERM",()=>st("SIGTERM"));process.once("SIGHUP",()=>st("SIGHUP"));process.once("SIGTTIN",()=>st("SIGTTIN"));process.once("SIGTSTP",()=>st("SIGTSTP"));process.on("uncaughtException",t=>{q.error({error:String(t),stack:t.stack},"uncaughtException"),I.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{q.error({reason:String(t)},"unhandledRejection"),I.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});En.listen(S.port,async()=>{Md(),I.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),Yv(),ku(),Ct.start().catch(r=>{q.warn({error:String(r)},"session activity watcher failed to start")});let t=Cn();q.info({port:S.port,pairingPort:t.port,daemonId:H.daemonId,displayName:H.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=ue.openWindow(Rd(),S.pairReusable),n={type:"vibelet-pair",daemonId:H.daemonId,displayName:H.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};It(`
114
114
  \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
115
- \u2551 Vibelet Daemon v${Tt} \u2551
115
+ \u2551 Vibelet Daemon v${At} \u2551
116
116
  \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
117
117
  \u2551 Port: ${String(n.port).padEnd(28)}\u2551
118
- \u2551 ID: ${D.daemonId.slice(0,28).padEnd(28)}\u2551
118
+ \u2551 ID: ${H.daemonId.slice(0,28).padEnd(28)}\u2551
119
119
  \u2551 Host: ${n.canonicalHost.slice(0,28).padEnd(28)}\u2551
120
120
  \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
121
121
 
@@ -125,4 +125,4 @@ Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
125
125
 
126
126
  Claude: ${S.claudePath}
127
127
  Codex: ${S.codexPath}
128
- `);try{await qv(n)}catch{}});
128
+ `);try{await Gv(n)}catch{}});