@vibelet/cli 1.2.7 → 1.2.9

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 jf=Object.create;var Fo=Object.defineProperty;var $f=Object.getOwnPropertyDescriptor;var zf=Object.getOwnPropertyNames;var Vf=Object.getPrototypeOf,Qf=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Jf=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zf(e))!Qf.call(t,r)&&r!==n&&Fo(t,r,{get:()=>e[r],enumerable:!(s=$f(e,r))||s.enumerable});return t};var ft=(t,e,n)=>(n=t!=null?jf(Vf(t)):{},Jf(e||!t||!t.__esModule?Fo(n,"default",{value:t,enumerable:!0}):n,t));var ve=v((Ab,Wo)=>{"use strict";var Uo=["nodebuffer","arraybuffer","fragments"],Ho=typeof Blob<"u";Ho&&Uo.push("blob");Wo.exports={BINARY_TYPES:Uo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ho,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Yt=v((Tb,Qn)=>{"use strict";var{EMPTY_BUFFER:Yf}=ve(),yr=Buffer[Symbol.species];function Kf(t,e){if(t.length===0)return Yf;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),s=0;for(let r=0;r<t.length;r++){let i=t[r];n.set(i,s),s+=i.length}return s<e?new yr(n.buffer,n.byteOffset,s):n}function qo(t,e,n,s,r){for(let i=0;i<r;i++)n[s+i]=t[i]^e[i&3]}function Go(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Xf(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 yr(t):ArrayBuffer.isView(t)?e=new yr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),vr.readOnly=!1),e}Qn.exports={concat:Kf,mask:qo,toArrayBuffer:Xf,toBuffer:vr,unmask:Go};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Qn.exports.mask=function(e,n,s,r,i){i<48?qo(e,n,s,r,i):t.mask(e,n,s,r,i)},Qn.exports.unmask=function(e,n){e.length<32?Go(e,n):t.unmask(e,n)}}catch{}});var zo=v((Cb,$o)=>{"use strict";var jo=Symbol("kDone"),Sr=Symbol("kRun"),_r=class{constructor(e){this[jo]=()=>{this.pending--,this[Sr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sr]()}[Sr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[jo])}}};$o.exports=_r});var Xt=v((kb,Yo)=>{"use strict";var Kt=require("zlib"),Vo=Yt(),Zf=zo(),{kStatusCode:Qo}=ve(),ep=Buffer[Symbol.species],tp=Buffer.from([0,0,255,255]),Yn=Symbol("permessage-deflate"),Se=Symbol("total-length"),pt=Symbol("callback"),ke=Symbol("buffers"),ht=Symbol("error"),Jn,br=class{constructor(e,n,s){if(this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Jn){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Jn=new Zf(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,s=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(s.server_no_context_takeover=!0),n.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(s.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?s.client_max_window_bits=n.clientMaxWindowBits:(s.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(s=>{let r=n[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);n[s]=r})}),e}decompress(e,n,s){Jn.add(r=>{this._decompress(e,n,(i,o)=>{r(),s(i,o)})})}compress(e,n,s){Jn.add(r=>{this._compress(e,n,(i,o)=>{r(),s(i,o)})})}_decompress(e,n,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Kt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Yn]=this,this._inflate[Se]=0,this._inflate[ke]=[],this._inflate.on("error",sp),this._inflate.on("data",Jo)}this._inflate[pt]=s,this._inflate.write(e),n&&this._inflate.write(tp),this._inflate.flush(()=>{let i=this._inflate[ht];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=Vo.concat(this._inflate[ke],this._inflate[Se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Se]=0,this._inflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,n,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Kt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[ke]=[],this._deflate.on("data",np)}this._deflate[pt]=s,this._deflate.write(e),this._deflate.flush(Kt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Vo.concat(this._deflate[ke],this._deflate[Se]);n&&(i=new ep(i.buffer,i.byteOffset,i.length-4)),this._deflate[pt]=null,this._deflate[Se]=0,this._deflate[ke]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Yo.exports=br;function np(t){this[ke].push(t),this[Se]+=t.length}function Jo(t){if(this[Se]+=t.length,this[Yn]._maxPayload<1||this[Se]<=this[Yn]._maxPayload){this[ke].push(t);return}this[ht]=new RangeError("Max payload size exceeded"),this[ht].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ht][Qo]=1009,this.removeListener("data",Jo),this.reset()}function sp(t){if(this[Yn]._inflate=null,this[ht]){this[pt](this[ht]);return}t[Qo]=1007,this[pt](t)}});var gt=v((xb,Kn)=>{"use strict";var{isUtf8:Ko}=require("buffer"),{hasBlob:rp}=ve(),ip=[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 op(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wr(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 ap(t){return rp&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Kn.exports={isBlob:ap,isValidStatusCode:op,isValidUTF8:wr,tokenChars:ip};if(Ko)Kn.exports.isValidUTF8=function(t){return t.length<24?wr(t):Ko(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Kn.exports.isValidUTF8=function(e){return e.length<32?wr(e):t(e)}}catch{}});var kr=v((Rb,ra)=>{"use strict";var{Writable:lp}=require("stream"),Xo=Xt(),{BINARY_TYPES:cp,EMPTY_BUFFER:Zo,kStatusCode:up,kWebSocket:dp}=ve(),{concat:Ir,toArrayBuffer:fp,unmask:pp}=Yt(),{isValidStatusCode:hp,isValidUTF8:ea}=gt(),Xn=Buffer[Symbol.species],ne=0,ta=1,na=2,sa=3,Ar=4,Tr=5,Zn=6,Cr=class extends lp{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[dp]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ne}_write(e,n,s){if(this._opcode===8&&this._state==ne)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Xn(s.buffer,s.byteOffset+e,s.length-e),new Xn(s.buffer,s.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=n.length-e;e>=s.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new Xn(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ne:this.getInfo(e);break;case ta:this.getPayloadLength16(e);break;case na:this.getPayloadLength64(e);break;case sa:this.getMask();break;case Ar:this.getData(e);break;case Tr:case Zn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(n[0]&64)===64;if(s&&!this._extensions[Xo.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=ta:this._payloadLength===127?this._state=na:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),s=n.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=sa:this._state=Ar}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ar}getData(e){let n=Zo;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&&pp(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Tr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Xo.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return n(r);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ne;return}let n=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=Ir(s,n):this._binaryType==="arraybuffer"?r=fp(Ir(s,n)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit("message",r,!0),this._state=ne,this.startLoop(e)}))}else{let r=Ir(s,n);if(!this._skipUTF8Validation&&!ea(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Tr||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit("message",r,!1),this._state=ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Zo),this.end();else{let s=e.readUInt16BE(0);if(!hp(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let r=new Xn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ea(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ne,this.startLoop(n)}))}createError(e,n,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[up]=r,o}};ra.exports=Cr});var Er=v((Pb,aa)=>{"use strict";var{Duplex:Eb}=require("stream"),{randomFillSync:gp}=require("crypto"),ia=Xt(),{EMPTY_BUFFER:mp,kWebSocket:yp,NOOP:vp}=ve(),{isBlob:mt,isValidStatusCode:Sp}=gt(),{mask:oa,toBuffer:Ge}=Yt(),se=Symbol("kByteLength"),_p=Buffer.alloc(4),es=8*1024,je,yt=es,ce=0,bp=1,wp=2,xr=class t{constructor(e,n,s){this._extensions=n||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ce,this.onerror=vp,this[yp]=void 0}static frame(e,n){let s,r=!1,i=2,o=!1;n.mask&&(s=n.maskBuffer||_p,n.generateMask?n.generateMask(s):(yt===es&&(je===void 0&&(je=Buffer.alloc(es)),gp(je,0,es),yt=0),s[0]=je[yt++],s[1]=je[yt++],s[2]=je[yt++],s[3]=je[yt++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[se]!==void 0?a=n[se]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(r?a+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(a,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[i-4]=s[0],u[i-3]=s[1],u[i-2]=s[2],u[i-1]=s[3],o?[u,e]:r?(oa(e,s,u,i,a),[u]):(oa(e,s,e,0,a),[u,e])):[u,e]}close(e,n,s,r){let i;if(e===void 0)i=mp;else{if(typeof e!="number"||!Sp(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[se]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ce?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(t.frame(i,o),r)}ping(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):mt(e)?(r=e.size,i=!1):(e=Ge(e),r=e.length,i=Ge.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):mt(e)?(r=e.size,i=!1):(e=Ge(e),r=e.length,i=Ge.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,n,s){let r=this._extensions[ia.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):mt(e)?(a=e.size,l=!1):(e=Ge(e),a=e.length,l=Ge.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[se]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==ce?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,n,s,r){this._bufferedBytes+=s[se],this._state=wp,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Rr,this,a,r);return}this._bufferedBytes-=s[se];let o=Ge(i);n?this.dispatch(o,n,s,r):(this._state=ce,this.sendFrame(t.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(Ip,this,i,r)})}dispatch(e,n,s,r){if(!n){this.sendFrame(t.frame(e,s),r);return}let i=this._extensions[ia.extensionName];this._bufferedBytes+=s[se],this._state=bp,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Rr(this,l,r);return}this._bufferedBytes-=s[se],this._state=ce,s.readOnly=!1,this.sendFrame(t.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===ce&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][se],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][se],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};aa.exports=xr;function Rr(t,e,n){typeof n=="function"&&n(e);for(let s=0;s<t._queue.length;s++){let r=t._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function Ip(t,e,n){Rr(t,e,n),t.onerror(e)}});var ma=v((Mb,ga)=>{"use strict";var{kForOnEventAttribute:Zt,kListener:Pr}=ve(),la=Symbol("kCode"),ca=Symbol("kData"),ua=Symbol("kError"),da=Symbol("kMessage"),fa=Symbol("kReason"),vt=Symbol("kTarget"),pa=Symbol("kType"),ha=Symbol("kWasClean"),_e=class{constructor(e){this[vt]=null,this[pa]=e}get target(){return this[vt]}get type(){return this[pa]}};Object.defineProperty(_e.prototype,"target",{enumerable:!0});Object.defineProperty(_e.prototype,"type",{enumerable:!0});var $e=class extends _e{constructor(e,n={}){super(e),this[la]=n.code===void 0?0:n.code,this[fa]=n.reason===void 0?"":n.reason,this[ha]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[la]}get reason(){return this[fa]}get wasClean(){return this[ha]}};Object.defineProperty($e.prototype,"code",{enumerable:!0});Object.defineProperty($e.prototype,"reason",{enumerable:!0});Object.defineProperty($e.prototype,"wasClean",{enumerable:!0});var St=class extends _e{constructor(e,n={}){super(e),this[ua]=n.error===void 0?null:n.error,this[da]=n.message===void 0?"":n.message}get error(){return this[ua]}get message(){return this[da]}};Object.defineProperty(St.prototype,"error",{enumerable:!0});Object.defineProperty(St.prototype,"message",{enumerable:!0});var en=class extends _e{constructor(e,n={}){super(e),this[ca]=n.data===void 0?null:n.data}get data(){return this[ca]}};Object.defineProperty(en.prototype,"data",{enumerable:!0});var Ap={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Zt]&&r[Pr]===e&&!r[Zt])return;let s;if(t==="message")s=function(i,o){let a=new en("message",{data:o?i:i.toString()});a[vt]=this,ts(e,this,a)};else if(t==="close")s=function(i,o){let a=new $e("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[vt]=this,ts(e,this,a)};else if(t==="error")s=function(i){let o=new St("error",{error:i,message:i.message});o[vt]=this,ts(e,this,o)};else if(t==="open")s=function(){let i=new _e("open");i[vt]=this,ts(e,this,i)};else return;s[Zt]=!!n[Zt],s[Pr]=e,n.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Pr]===e&&!n[Zt]){this.removeListener(t,n);break}}};ga.exports={CloseEvent:$e,ErrorEvent:St,Event:_e,EventTarget:Ap,MessageEvent:en};function ts(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Mr=v((Lb,ya)=>{"use strict";var{tokenChars:tn}=gt();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Tp(t){let e=Object.create(null),n=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,u=-1,c=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),o===void 0)if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(d!==0&&(u===32||u===9))c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);u===44?(he(e,h,n),n=Object.create(null)):o=h,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(u===32||u===9)c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d),he(n,t.slice(l,c),!0),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),l=c=-1}else if(u===61&&l!==-1&&c===-1)a=t.slice(l,d),l=c=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(tn[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:s||(s=!0),r=!1}else if(i)if(tn[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)i=!0;else if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(l!==-1&&(u===32||u===9))c===-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let h=t.slice(l,c);s&&(h=h.replace(/\\/g,""),s=!1),he(n,a,h),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=d);let f=t.slice(l,c);return o===void 0?he(e,f,n):(a===void 0?he(n,f,!0):s?he(n,a,f.replace(/\\/g,"")):he(n,a,f),he(e,o,n)),e}function Cp(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ya.exports={format:Cp,parse:Tp}});var is=v((Db,Ra)=>{"use strict";var kp=require("events"),xp=require("https"),Rp=require("http"),_a=require("net"),Ep=require("tls"),{randomBytes:Pp,createHash:Mp}=require("crypto"),{Duplex:Nb,Readable:Ob}=require("stream"),{URL:Lr}=require("url"),xe=Xt(),Lp=kr(),Np=Er(),{isBlob:Op}=gt(),{BINARY_TYPES:va,CLOSE_TIMEOUT:Dp,EMPTY_BUFFER:ns,GUID:Bp,kForOnEventAttribute:Nr,kListener:Fp,kStatusCode:Up,kWebSocket:$,NOOP:ba}=ve(),{EventTarget:{addEventListener:Hp,removeEventListener:Wp}}=ma(),{format:qp,parse:Gp}=Mr(),{toBuffer:jp}=Yt(),wa=Symbol("kAborted"),Or=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],$p=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,N=class t extends kp{constructor(e,n,s){super(),this._binaryType=va[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ns,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(s=n,n=[]):n=[n]),Ia(this,e,n,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){va.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,s){let r=new Lp({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Np(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[$]=this,i[$]=this,e[$]=this,r.on("conclude",Qp),r.on("drain",Jp),r.on("error",Yp),r.on("message",Kp),r.on("ping",Xp),r.on("pong",Zp),i.onerror=eh,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ca),e.on("data",rs),e.on("end",ka),e.on("error",xa),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[xe.extensionName]&&this._extensions[xe.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ta(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ns,n,s)}pong(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ns,n,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(s=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Dr(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(r.compress=!1),this._sender.send(e||ns,r,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(N.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(N.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(N.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nr])return e[Fp];return null},set(e){for(let n of this.listeners(t))if(n[Nr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Nr]:!0})}})});N.prototype.addEventListener=Hp;N.prototype.removeEventListener=Wp;Ra.exports=N;function Ia(t,e,n,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Dp,protocolVersion:Or[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!Or.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Or.join(", ")})`);let i;if(e instanceof Lr)i=e;else try{i=new Lr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(t._redirects===0)throw m;ss(t,m);return}let u=o?443:80,c=Pp(16).toString("base64"),d=o?xp.request:Rp.request,f=new Set,h;if(r.createConnection=r.createConnection||(o?Vp:zp),r.defaultPort=r.defaultPort||u,r.port=i.port||u,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(h=new xe(r.perMessageDeflate!==!0?r.perMessageDeflate:{},!1,r.maxPayload),r.headers["Sec-WebSocket-Extensions"]=qp({[xe.extensionName]:h.offer()})),n.length){for(let m of n){if(typeof m!="string"||!$p.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let m=r.path.split(":");r.socketPath=m[0],r.path=m[1]}let g;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?r.socketPath:i.host;let m=s&&s.headers;if(s={...s,headers:{}},m)for(let[p,y]of Object.entries(m))s.headers[p.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,m||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),g=t._req=d(r),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(r);r.timeout&&g.on("timeout",()=>{Z(t,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[wa]||(g=t._req=null,ss(t,m))}),g.on("response",m=>{let p=m.headers.location,y=m.statusCode;if(p&&r.followRedirects&&y>=300&&y<400){if(++t._redirects>r.maxRedirects){Z(t,g,"Maximum redirects exceeded");return}g.abort();let C;try{C=new Lr(p,e)}catch{let T=new SyntaxError(`Invalid URL: ${p}`);ss(t,T);return}Ia(t,C,n,s)}else t.emit("unexpected-response",g,m)||Z(t,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,p,y)=>{if(t.emit("upgrade",m),t.readyState!==N.CONNECTING)return;g=t._req=null;let C=m.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Z(t,p,"Invalid Upgrade header");return}let A=Mp("sha1").update(c+Bp).digest("base64");if(m.headers["sec-websocket-accept"]!==A){Z(t,p,"Invalid Sec-WebSocket-Accept header");return}let T=m.headers["sec-websocket-protocol"],I;if(T!==void 0?f.size?f.has(T)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":f.size&&(I="Server sent no subprotocol"),I){Z(t,p,I);return}T&&(t._protocol=T);let D=m.headers["sec-websocket-extensions"];if(D!==void 0){if(!h){Z(t,p,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=Gp(D)}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(R);if(X.length!==1||X[0]!==xe.extensionName){Z(t,p,"Server indicated an extension that was not requested");return}try{h.accept(R[xe.extensionName])}catch{Z(t,p,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=h}t.setSocket(p,y,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(g,t):g.end()}function ss(t,e){t._readyState=N.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function zp(t){return t.path=t.socketPath,_a.connect(t)}function Vp(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=_a.isIP(t.host)?"":t.host),Ep.connect(t)}function Z(t,e,n){t._readyState=N.CLOSING;let s=new Error(n);Error.captureStackTrace(s,Z),e.setHeader?(e[wa]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ss,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Dr(t,e,n){if(e){let s=Op(e)?e.size:jp(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(n){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,s)}}function Qp(t,e){let n=this[$];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$]!==void 0&&(n._socket.removeListener("data",rs),process.nextTick(Aa,n._socket),t===1005?n.close():n.close(t,e))}function Jp(){let t=this[$];t.isPaused||t._socket.resume()}function Yp(t){let e=this[$];e._socket[$]!==void 0&&(e._socket.removeListener("data",rs),process.nextTick(Aa,e._socket),e.close(t[Up])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Sa(){this[$].emitClose()}function Kp(t,e){this[$].emit("message",t,e)}function Xp(t){let e=this[$];e._autoPong&&e.pong(t,!this._isServer,ba),e.emit("ping",t)}function Zp(t){this[$].emit("pong",t)}function Aa(t){t.resume()}function eh(t){let e=this[$];e.readyState!==N.CLOSED&&(e.readyState===N.OPEN&&(e._readyState=N.CLOSING,Ta(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ta(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ca(){let t=this[$];if(this.removeListener("close",Ca),this.removeListener("data",rs),this.removeListener("end",ka),t._readyState=N.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[$]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Sa),t._receiver.on("finish",Sa))}function rs(t){this[$]._receiver.write(t)||this.pause()}function ka(){let t=this[$];t._readyState=N.CLOSING,t._receiver.end(),this.end()}function xa(){let t=this[$];this.removeListener("error",xa),this.on("error",ba),t&&(t._readyState=N.CLOSING,this.destroy())}});var La=v((Fb,Ma)=>{"use strict";var Bb=is(),{Duplex:th}=require("stream");function Ea(t){t.emit("close")}function nh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Pa(t){this.removeListener("error",Pa),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sh(t,e){let n=!0,s=new th({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(n=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(t.readyState===t.CLOSED){i(r),process.nextTick(Ea,s);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(r),process.nextTick(Ea,s)}),n&&t.terminate()},s._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(r,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(r,i,o)});return}t.send(r,o)},s.on("end",nh),s.on("error",Pa),s}Ma.exports=sh});var Oa=v((Ub,Na)=>{"use strict";var{tokenChars:rh}=gt();function ih(t){let e=new Set,n=-1,s=-1,r=0;for(r;r<t.length;r++){let o=t.charCodeAt(r);if(s===-1&&rh[o]===1)n===-1&&(n=r);else if(r!==0&&(o===32||o===9))s===-1&&n!==-1&&(s=r);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Na.exports={parse:ih}});var qa=v((Wb,Wa)=>{"use strict";var oh=require("events"),os=require("http"),{Duplex:Hb}=require("stream"),{createHash:ah}=require("crypto"),Da=Mr(),ze=Xt(),lh=Oa(),ch=is(),{CLOSE_TIMEOUT:uh,GUID:dh,kWebSocket:fh}=ve(),ph=/^[+/0-9A-Za-z]{22}==$/,Ba=0,Fa=1,Ha=2,Br=class extends oh{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:uh,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ch,...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=os.createServer((s,r)=>{let i=os.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=hh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ba}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===Ha){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(nn,this);return}if(e&&this.once("close",e),this._state!==Fa)if(this._state=Fa,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(nn,this):process.nextTick(nn,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{nn(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,s,r){n.on("error",Ua);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ve(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ve(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!ph.test(i)){Ve(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ve(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){sn(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=lh.parse(l)}catch{Ve(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let c=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&c!==void 0){let f=new ze(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=Da.parse(c);h[ze.extensionName]&&(f.accept(h[ze.extensionName]),d[ze.extensionName]=f)}catch{Ve(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,g,m,p)=>{if(!h)return sn(n,g||401,m,p);this.completeUpgrade(d,i,u,e,n,s,r)});return}if(!this.options.verifyClient(f))return sn(n,401)}this.completeUpgrade(d,i,u,e,n,s,r)}completeUpgrade(e,n,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[fh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ba)return sn(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ah("sha1").update(n+dh).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[ze.extensionName]){let d=e[ze.extensionName].params,f=Da.format({[ze.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${f}`),c._extensions=e}this.emit("headers",u,r),i.write(u.concat(`\r
1
+ "use strict";var $f=Object.create;var Wo=Object.defineProperty;var zf=Object.getOwnPropertyDescriptor;var Vf=Object.getOwnPropertyNames;var Qf=Object.getPrototypeOf,Jf=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Yf=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vf(e))!Jf.call(t,r)&&r!==n&&Wo(t,r,{get:()=>e[r],enumerable:!(s=zf(e,r))||s.enumerable});return t};var ft=(t,e,n)=>(n=t!=null?$f(Qf(t)):{},Yf(e||!t||!t.__esModule?Wo(n,"default",{value:t,enumerable:!0}):n,t));var ve=v((Tb,jo)=>{"use strict";var qo=["nodebuffer","arraybuffer","fragments"],Go=typeof Blob<"u";Go&&qo.push("blob");jo.exports={BINARY_TYPES:qo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Go,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Yt=v((kb,Qn)=>{"use strict";var{EMPTY_BUFFER:Kf}=ve(),Sr=Buffer[Symbol.species];function Xf(t,e){if(t.length===0)return Kf;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),s=0;for(let r=0;r<t.length;r++){let i=t[r];n.set(i,s),s+=i.length}return s<e?new Sr(n.buffer,n.byteOffset,s):n}function $o(t,e,n,s,r){for(let i=0;i<r;i++)n[s+i]=t[i]^e[i&3]}function zo(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Zf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function _r(t){if(_r.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Sr(t):ArrayBuffer.isView(t)?e=new Sr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),_r.readOnly=!1),e}Qn.exports={concat:Xf,mask:$o,toArrayBuffer:Zf,toBuffer:_r,unmask:zo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Qn.exports.mask=function(e,n,s,r,i){i<48?$o(e,n,s,r,i):t.mask(e,n,s,r,i)},Qn.exports.unmask=function(e,n){e.length<32?zo(e,n):t.unmask(e,n)}}catch{}});var Jo=v((Cb,Qo)=>{"use strict";var Vo=Symbol("kDone"),br=Symbol("kRun"),wr=class{constructor(e){this[Vo]=()=>{this.pending--,this[br]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[br]()}[br](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Vo])}}};Qo.exports=wr});var Xt=v((xb,Zo)=>{"use strict";var Kt=require("zlib"),Yo=Yt(),ep=Jo(),{kStatusCode:Ko}=ve(),tp=Buffer[Symbol.species],np=Buffer.from([0,0,255,255]),Yn=Symbol("permessage-deflate"),Se=Symbol("total-length"),pt=Symbol("callback"),Ce=Symbol("buffers"),ht=Symbol("error"),Jn,Ir=class{constructor(e,n,s){if(this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Jn){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Jn=new ep(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,s=e.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(s.server_no_context_takeover=!0),n.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(s.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?s.client_max_window_bits=n.clientMaxWindowBits:(s.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(s=>{let r=n[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);n[s]=r})}),e}decompress(e,n,s){Jn.add(r=>{this._decompress(e,n,(i,o)=>{r(),s(i,o)})})}compress(e,n,s){Jn.add(r=>{this._compress(e,n,(i,o)=>{r(),s(i,o)})})}_decompress(e,n,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Kt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Yn]=this,this._inflate[Se]=0,this._inflate[Ce]=[],this._inflate.on("error",rp),this._inflate.on("data",Xo)}this._inflate[pt]=s,this._inflate.write(e),n&&this._inflate.write(np),this._inflate.flush(()=>{let i=this._inflate[ht];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=Yo.concat(this._inflate[Ce],this._inflate[Se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Se]=0,this._inflate[Ce]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,n,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Kt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[Ce]=[],this._deflate.on("data",sp)}this._deflate[pt]=s,this._deflate.write(e),this._deflate.flush(Kt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Yo.concat(this._deflate[Ce],this._deflate[Se]);n&&(i=new tp(i.buffer,i.byteOffset,i.length-4)),this._deflate[pt]=null,this._deflate[Se]=0,this._deflate[Ce]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Zo.exports=Ir;function sp(t){this[Ce].push(t),this[Se]+=t.length}function Xo(t){if(this[Se]+=t.length,this[Yn]._maxPayload<1||this[Se]<=this[Yn]._maxPayload){this[Ce].push(t);return}this[ht]=new RangeError("Max payload size exceeded"),this[ht].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ht][Ko]=1009,this.removeListener("data",Xo),this.reset()}function rp(t){if(this[Yn]._inflate=null,this[ht]){this[pt](this[ht]);return}t[Ko]=1007,this[pt](t)}});var gt=v((Rb,Kn)=>{"use strict";var{isUtf8:ea}=require("buffer"),{hasBlob:ip}=ve(),op=[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 ap(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ar(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function lp(t){return ip&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Kn.exports={isBlob:lp,isValidStatusCode:ap,isValidUTF8:Ar,tokenChars:op};if(ea)Kn.exports.isValidUTF8=function(t){return t.length<24?Ar(t):ea(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Kn.exports.isValidUTF8=function(e){return e.length<32?Ar(e):t(e)}}catch{}});var Rr=v((Eb,aa)=>{"use strict";var{Writable:cp}=require("stream"),ta=Xt(),{BINARY_TYPES:up,EMPTY_BUFFER:na,kStatusCode:dp,kWebSocket:fp}=ve(),{concat:Tr,toArrayBuffer:pp,unmask:hp}=Yt(),{isValidStatusCode:gp,isValidUTF8:sa}=gt(),Xn=Buffer[Symbol.species],ne=0,ra=1,ia=2,oa=3,kr=4,Cr=5,Zn=6,xr=class extends cp{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||up[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[fp]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ne}_write(e,n,s){if(this._opcode===8&&this._state==ne)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Xn(s.buffer,s.byteOffset+e,s.length-e),new Xn(s.buffer,s.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=n.length-e;e>=s.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new Xn(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ne:this.getInfo(e);break;case ra:this.getPayloadLength16(e);break;case ia:this.getPayloadLength64(e);break;case oa:this.getMask();break;case kr:this.getData(e);break;case Cr:case Zn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(n[0]&64)===64;if(s&&!this._extensions[ta.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=ra:this._payloadLength===127?this._state=ia:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),s=n.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=oa:this._state=kr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=kr}getData(e){let n=na;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&&hp(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Cr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ta.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return n(r);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ne;return}let n=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=Tr(s,n):this._binaryType==="arraybuffer"?r=pp(Tr(s,n)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit("message",r,!0),this._state=ne,this.startLoop(e)}))}else{let r=Tr(s,n);if(!this._skipUTF8Validation&&!sa(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Cr||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit("message",r,!1),this._state=ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,na),this.end();else{let s=e.readUInt16BE(0);if(!gp(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let r=new Xn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!sa(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ne):(this._state=Zn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ne,this.startLoop(n)}))}createError(e,n,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[dp]=r,o}};aa.exports=xr});var Mr=v((Mb,ua)=>{"use strict";var{Duplex:Pb}=require("stream"),{randomFillSync:mp}=require("crypto"),la=Xt(),{EMPTY_BUFFER:yp,kWebSocket:vp,NOOP:Sp}=ve(),{isBlob:mt,isValidStatusCode:_p}=gt(),{mask:ca,toBuffer:Ge}=Yt(),se=Symbol("kByteLength"),bp=Buffer.alloc(4),es=8*1024,je,yt=es,ce=0,wp=1,Ip=2,Er=class t{constructor(e,n,s){this._extensions=n||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ce,this.onerror=Sp,this[vp]=void 0}static frame(e,n){let s,r=!1,i=2,o=!1;n.mask&&(s=n.maskBuffer||bp,n.generateMask?n.generateMask(s):(yt===es&&(je===void 0&&(je=Buffer.alloc(es)),mp(je,0,es),yt=0),s[0]=je[yt++],s[1]=je[yt++],s[2]=je[yt++],s[3]=je[yt++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[se]!==void 0?a=n[se]:(e=Buffer.from(e),a=e.length):(a=e.length,r=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(r?a+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(a,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[i-4]=s[0],u[i-3]=s[1],u[i-2]=s[2],u[i-1]=s[3],o?[u,e]:r?(ca(e,s,u,i,a),[u]):(ca(e,s,e,0,a),[u,e])):[u,e]}close(e,n,s,r){let i;if(e===void 0)i=yp;else{if(typeof e!="number"||!_p(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[se]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ce?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(t.frame(i,o),r)}ping(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):mt(e)?(r=e.size,i=!1):(e=Ge(e),r=e.length,i=Ge.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,n,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):mt(e)?(r=e.size,i=!1):(e=Ge(e),r=e.length,i=Ge.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[se]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==ce?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,n,s){let r=this._extensions[la.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):mt(e)?(a=e.size,l=!1):(e=Ge(e),a=e.length,l=Ge.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[se]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};mt(e)?this._state!==ce?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==ce?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,n,s,r){this._bufferedBytes+=s[se],this._state=Ip,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Pr,this,a,r);return}this._bufferedBytes-=s[se];let o=Ge(i);n?this.dispatch(o,n,s,r):(this._state=ce,this.sendFrame(t.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(Ap,this,i,r)})}dispatch(e,n,s,r){if(!n){this.sendFrame(t.frame(e,s),r);return}let i=this._extensions[la.extensionName];this._bufferedBytes+=s[se],this._state=wp,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Pr(this,l,r);return}this._bufferedBytes-=s[se],this._state=ce,s.readOnly=!1,this.sendFrame(t.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===ce&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][se],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][se],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};ua.exports=Er;function Pr(t,e,n){typeof n=="function"&&n(e);for(let s=0;s<t._queue.length;s++){let r=t._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function Ap(t,e,n){Pr(t,e,n),t.onerror(e)}});var Sa=v((Lb,va)=>{"use strict";var{kForOnEventAttribute:Zt,kListener:Lr}=ve(),da=Symbol("kCode"),fa=Symbol("kData"),pa=Symbol("kError"),ha=Symbol("kMessage"),ga=Symbol("kReason"),vt=Symbol("kTarget"),ma=Symbol("kType"),ya=Symbol("kWasClean"),_e=class{constructor(e){this[vt]=null,this[ma]=e}get target(){return this[vt]}get type(){return this[ma]}};Object.defineProperty(_e.prototype,"target",{enumerable:!0});Object.defineProperty(_e.prototype,"type",{enumerable:!0});var $e=class extends _e{constructor(e,n={}){super(e),this[da]=n.code===void 0?0:n.code,this[ga]=n.reason===void 0?"":n.reason,this[ya]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[da]}get reason(){return this[ga]}get wasClean(){return this[ya]}};Object.defineProperty($e.prototype,"code",{enumerable:!0});Object.defineProperty($e.prototype,"reason",{enumerable:!0});Object.defineProperty($e.prototype,"wasClean",{enumerable:!0});var St=class extends _e{constructor(e,n={}){super(e),this[pa]=n.error===void 0?null:n.error,this[ha]=n.message===void 0?"":n.message}get error(){return this[pa]}get message(){return this[ha]}};Object.defineProperty(St.prototype,"error",{enumerable:!0});Object.defineProperty(St.prototype,"message",{enumerable:!0});var en=class extends _e{constructor(e,n={}){super(e),this[fa]=n.data===void 0?null:n.data}get data(){return this[fa]}};Object.defineProperty(en.prototype,"data",{enumerable:!0});var Tp={addEventListener(t,e,n={}){for(let r of this.listeners(t))if(!n[Zt]&&r[Lr]===e&&!r[Zt])return;let s;if(t==="message")s=function(i,o){let a=new en("message",{data:o?i:i.toString()});a[vt]=this,ts(e,this,a)};else if(t==="close")s=function(i,o){let a=new $e("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[vt]=this,ts(e,this,a)};else if(t==="error")s=function(i){let o=new St("error",{error:i,message:i.message});o[vt]=this,ts(e,this,o)};else if(t==="open")s=function(){let i=new _e("open");i[vt]=this,ts(e,this,i)};else return;s[Zt]=!!n[Zt],s[Lr]=e,n.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Lr]===e&&!n[Zt]){this.removeListener(t,n);break}}};va.exports={CloseEvent:$e,ErrorEvent:St,Event:_e,EventTarget:Tp,MessageEvent:en};function ts(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Nr=v((Nb,_a)=>{"use strict";var{tokenChars:tn}=gt();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function kp(t){let e=Object.create(null),n=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,u=-1,c=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),o===void 0)if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(d!==0&&(u===32||u===9))c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let p=t.slice(l,c);u===44?(he(e,p,n),n=Object.create(null)):o=p,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(u===32||u===9)c===-1&&l!==-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d),he(n,t.slice(l,c),!0),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),l=c=-1}else if(u===61&&l!==-1&&c===-1)a=t.slice(l,d),l=c=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(tn[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:s||(s=!0),r=!1}else if(i)if(tn[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)i=!0;else if(c===-1&&tn[u]===1)l===-1&&(l=d);else if(l!==-1&&(u===32||u===9))c===-1&&(c=d);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1&&(c=d);let p=t.slice(l,c);s&&(p=p.replace(/\\/g,""),s=!1),he(n,a,p),u===44&&(he(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=d);let f=t.slice(l,c);return o===void 0?he(e,f,n):(a===void 0?he(n,f,!0):s?he(n,a,f.replace(/\\/g,"")):he(n,a,f),he(e,o,n)),e}function Cp(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}_a.exports={format:Cp,parse:kp}});var is=v((Bb,Ma)=>{"use strict";var xp=require("events"),Rp=require("https"),Ep=require("http"),Ia=require("net"),Pp=require("tls"),{randomBytes:Mp,createHash:Lp}=require("crypto"),{Duplex:Ob,Readable:Db}=require("stream"),{URL:Or}=require("url"),xe=Xt(),Np=Rr(),Op=Mr(),{isBlob:Dp}=gt(),{BINARY_TYPES:ba,CLOSE_TIMEOUT:Bp,EMPTY_BUFFER:ns,GUID:Fp,kForOnEventAttribute:Dr,kListener:Up,kStatusCode:Hp,kWebSocket:$,NOOP:Aa}=ve(),{EventTarget:{addEventListener:Wp,removeEventListener:qp}}=Sa(),{format:Gp,parse:jp}=Nr(),{toBuffer:$p}=Yt(),Ta=Symbol("kAborted"),Br=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],zp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,N=class t extends xp{constructor(e,n,s){super(),this._binaryType=ba[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ns,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(s=n,n=[]):n=[n]),ka(this,e,n,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ba.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,s){let r=new Np({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new Op(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[$]=this,i[$]=this,e[$]=this,r.on("conclude",Jp),r.on("drain",Yp),r.on("error",Kp),r.on("message",Xp),r.on("ping",Zp),r.on("pong",eh),i.onerror=th,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ra),e.on("data",rs),e.on("end",Ea),e.on("error",Pa),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[xe.extensionName]&&this._extensions[xe.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xa(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Fr(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ns,n,s)}pong(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=n=void 0):typeof n=="function"&&(s=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Fr(this,e,s);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ns,n,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(s=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Fr(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(r.compress=!1),this._sender.send(e||ns,r,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(N,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(N,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(N,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(N.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(N.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(N.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Dr])return e[Up];return null},set(e){for(let n of this.listeners(t))if(n[Dr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Dr]:!0})}})});N.prototype.addEventListener=Wp;N.prototype.removeEventListener=qp;Ma.exports=N;function ka(t,e,n,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Bp,protocolVersion:Br[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=r.autoPong,t._closeTimeout=r.closeTimeout,!Br.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${Br.join(", ")})`);let i;if(e instanceof Or)i=e;else try{i=new Or(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(t._redirects===0)throw m;ss(t,m);return}let u=o?443:80,c=Mp(16).toString("base64"),d=o?Rp.request:Ep.request,f=new Set,p;if(r.createConnection=r.createConnection||(o?Qp:Vp),r.defaultPort=r.defaultPort||u,r.port=i.port||u,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(p=new xe(r.perMessageDeflate!==!0?r.perMessageDeflate:{},!1,r.maxPayload),r.headers["Sec-WebSocket-Extensions"]=Gp({[xe.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!zp.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let m=r.path.split(":");r.socketPath=m[0],r.path=m[1]}let g;if(r.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?r.socketPath:i.host;let m=s&&s.headers;if(s={...s,headers:{}},m)for(let[h,y]of Object.entries(m))s.headers[h.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?r.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,m||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),g=t._req=d(r),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(r);r.timeout&&g.on("timeout",()=>{Z(t,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[Ta]||(g=t._req=null,ss(t,m))}),g.on("response",m=>{let h=m.headers.location,y=m.statusCode;if(h&&r.followRedirects&&y>=300&&y<400){if(++t._redirects>r.maxRedirects){Z(t,g,"Maximum redirects exceeded");return}g.abort();let T;try{T=new Or(h,e)}catch{let k=new SyntaxError(`Invalid URL: ${h}`);ss(t,k);return}ka(t,T,n,s)}else t.emit("unexpected-response",g,m)||Z(t,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,h,y)=>{if(t.emit("upgrade",m),t.readyState!==N.CONNECTING)return;g=t._req=null;let T=m.headers.upgrade;if(T===void 0||T.toLowerCase()!=="websocket"){Z(t,h,"Invalid Upgrade header");return}let I=Lp("sha1").update(c+Fp).digest("base64");if(m.headers["sec-websocket-accept"]!==I){Z(t,h,"Invalid Sec-WebSocket-Accept header");return}let k=m.headers["sec-websocket-protocol"],A;if(k!==void 0?f.size?f.has(k)||(A="Server sent an invalid subprotocol"):A="Server sent a subprotocol but none was requested":f.size&&(A="Server sent no subprotocol"),A){Z(t,h,A);return}k&&(t._protocol=k);let D=m.headers["sec-websocket-extensions"];if(D!==void 0){if(!p){Z(t,h,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=jp(D)}catch{Z(t,h,"Invalid Sec-WebSocket-Extensions header");return}let X=Object.keys(x);if(X.length!==1||X[0]!==xe.extensionName){Z(t,h,"Server indicated an extension that was not requested");return}try{p.accept(x[xe.extensionName])}catch{Z(t,h,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=p}t.setSocket(h,y,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(g,t):g.end()}function ss(t,e){t._readyState=N.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Vp(t){return t.path=t.socketPath,Ia.connect(t)}function Qp(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ia.isIP(t.host)?"":t.host),Pp.connect(t)}function Z(t,e,n){t._readyState=N.CLOSING;let s=new Error(n);Error.captureStackTrace(s,Z),e.setHeader?(e[Ta]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ss,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Fr(t,e,n){if(e){let s=Dp(e)?e.size:$p(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(n){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,s)}}function Jp(t,e){let n=this[$];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$]!==void 0&&(n._socket.removeListener("data",rs),process.nextTick(Ca,n._socket),t===1005?n.close():n.close(t,e))}function Yp(){let t=this[$];t.isPaused||t._socket.resume()}function Kp(t){let e=this[$];e._socket[$]!==void 0&&(e._socket.removeListener("data",rs),process.nextTick(Ca,e._socket),e.close(t[Hp])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function wa(){this[$].emitClose()}function Xp(t,e){this[$].emit("message",t,e)}function Zp(t){let e=this[$];e._autoPong&&e.pong(t,!this._isServer,Aa),e.emit("ping",t)}function eh(t){this[$].emit("pong",t)}function Ca(t){t.resume()}function th(t){let e=this[$];e.readyState!==N.CLOSED&&(e.readyState===N.OPEN&&(e._readyState=N.CLOSING,xa(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xa(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ra(){let t=this[$];if(this.removeListener("close",Ra),this.removeListener("data",rs),this.removeListener("end",Ea),t._readyState=N.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[$]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",wa),t._receiver.on("finish",wa))}function rs(t){this[$]._receiver.write(t)||this.pause()}function Ea(){let t=this[$];t._readyState=N.CLOSING,t._receiver.end(),this.end()}function Pa(){let t=this[$];this.removeListener("error",Pa),this.on("error",Aa),t&&(t._readyState=N.CLOSING,this.destroy())}});var Da=v((Ub,Oa)=>{"use strict";var Fb=is(),{Duplex:nh}=require("stream");function La(t){t.emit("close")}function sh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Na(t){this.removeListener("error",Na),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function rh(t,e){let n=!0,s=new nh({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||t.pause()}),t.once("error",function(i){s.destroyed||(n=!1,s.destroy(i))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(t.readyState===t.CLOSED){i(r),process.nextTick(La,s);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(r),process.nextTick(La,s)}),n&&t.terminate()},s._final=function(r){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(r)});return}t._socket!==null&&(t._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){r()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(r,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(r,i,o)});return}t.send(r,o)},s.on("end",sh),s.on("error",Na),s}Oa.exports=rh});var Fa=v((Hb,Ba)=>{"use strict";var{tokenChars:ih}=gt();function oh(t){let e=new Set,n=-1,s=-1,r=0;for(r;r<t.length;r++){let o=t.charCodeAt(r);if(s===-1&&ih[o]===1)n===-1&&(n=r);else if(r!==0&&(o===32||o===9))s===-1&&n!==-1&&(s=r);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=t.slice(n,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Ba.exports={parse:oh}});var $a=v((qb,ja)=>{"use strict";var ah=require("events"),os=require("http"),{Duplex:Wb}=require("stream"),{createHash:lh}=require("crypto"),Ua=Nr(),ze=Xt(),ch=Fa(),uh=is(),{CLOSE_TIMEOUT:dh,GUID:fh,kWebSocket:ph}=ve(),hh=/^[+/0-9A-Za-z]{22}==$/,Ha=0,Wa=1,Ga=2,Ur=class extends ah{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:dh,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:uh,...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=os.createServer((s,r)=>{let i=os.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=gh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ha}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===Ga){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(nn,this);return}if(e&&this.once("close",e),this._state!==Wa)if(this._state=Wa,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(nn,this):process.nextTick(nn,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{nn(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,s,r){n.on("error",qa);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ve(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ve(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!hh.test(i)){Ve(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ve(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){sn(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=ch.parse(l)}catch{Ve(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let c=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&c!==void 0){let f=new ze(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Ua.parse(c);p[ze.extensionName]&&(f.accept(p[ze.extensionName]),d[ze.extensionName]=f)}catch{Ve(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,g,m,h)=>{if(!p)return sn(n,g||401,m,h);this.completeUpgrade(d,i,u,e,n,s,r)});return}if(!this.options.verifyClient(f))return sn(n,401)}this.completeUpgrade(d,i,u,e,n,s,r)}completeUpgrade(e,n,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[ph])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ha)return sn(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lh("sha1").update(n+fh).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(s.size){let d=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[ze.extensionName]){let d=e[ze.extensionName].params,f=Ua.format({[ze.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${f}`),c._extensions=e}this.emit("headers",u,r),i.write(u.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",Ua),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(nn,this)})),a(c,r)}};Wa.exports=Br;function hh(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function nn(t){t._state=Ha,t.emit("close")}function Ua(){this.destroy()}function sn(t,e,n,s){n=n||os.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${os.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",qa),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(nn,this)})),a(c,r)}};ja.exports=Ur;function gh(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function nn(t){t._state=Ga,t.emit("close")}function qa(){this.destroy()}function sn(t,e,n,s){n=n||os.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${os.STATUS_CODES[e]}\r
4
4
  `+Object.keys(s).map(r=>`${r}: ${s[r]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function Ve(t,e,n,s,r,i){if(t.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,Ve),t.emit("wsClientError",o,n,e)}else sn(n,s,r,i)}});var Ur=v((Gb,Ga)=>{Ga.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Re=v(Qe=>{var Hr,Sh=[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];Qe.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};Qe.getSymbolTotalCodewords=function(e){return Sh[e]};Qe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Qe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Hr=e};Qe.isKanjiModeEnabled=function(){return typeof Hr<"u"};Qe.toSJIS=function(e){return Hr(e)}});var as=v(re=>{re.L={bit:1};re.M={bit:0};re.Q={bit:3};re.H={bit:2};function _h(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return re.L;case"m":case"medium":return re.M;case"q":case"quartile":return re.Q;case"h":case"high":return re.H;default:throw new Error("Unknown EC Level: "+t)}}re.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};re.from=function(e,n){if(re.isValid(e))return e;try{return _h(e)}catch{return n}}});var za=v((zb,$a)=>{function ja(){this.buffer=[],this.length=0}ja.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++}};$a.exports=ja});var Qa=v((Vb,Va)=>{function rn(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)}rn.prototype.set=function(t,e,n,s){let r=t*this.size+e;this.data[r]=n,s&&(this.reservedBit[r]=!0)};rn.prototype.get=function(t,e){return this.data[t*this.size+e]};rn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};rn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Va.exports=rn});var Ja=v(ls=>{var bh=Re().getSymbolSize;ls.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,s=bh(e),r=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-r;return i.push(6),i.reverse()};ls.getPositions=function(e){let n=[],s=ls.getRowColCoords(e),r=s.length;for(let i=0;i<r;i++)for(let o=0;o<r;o++)i===0&&o===0||i===0&&o===r-1||i===r-1&&o===0||n.push([s[i],s[o]]);return n}});var Xa=v(Ka=>{var wh=Re().getSymbolSize,Ya=7;Ka.getPositions=function(e){let n=wh(e);return[[0,0],[n-Ya,0],[0,n-Ya]]}});var Za=v(E=>{E.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};E.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};E.from=function(e){return E.isValid(e)?parseInt(e,10):void 0};E.getPenaltyN1=function(e){let n=e.size,s=0,r=0,i=0,o=null,a=null;for(let l=0;l<n;l++){r=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?r++:(r>=5&&(s+=Je.N1+(r-5)),o=c,r=1),c=e.get(u,l),c===a?i++:(i>=5&&(s+=Je.N1+(i-5)),a=c,i=1)}r>=5&&(s+=Je.N1+(r-5)),i>=5&&(s+=Je.N1+(i-5))}return s};E.getPenaltyN2=function(e){let n=e.size,s=0;for(let r=0;r<n-1;r++)for(let i=0;i<n-1;i++){let o=e.get(r,i)+e.get(r,i+1)+e.get(r+1,i)+e.get(r+1,i+1);(o===4||o===0)&&s++}return s*Je.N2};E.getPenaltyN3=function(e){let n=e.size,s=0,r=0,i=0;for(let o=0;o<n;o++){r=i=0;for(let a=0;a<n;a++)r=r<<1&2047|e.get(o,a),a>=10&&(r===1488||r===93)&&s++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&s++}return s*Je.N3};E.getPenaltyN4=function(e){let n=0,s=e.data.length;for(let i=0;i<s;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/s/5)-10)*Je.N4};function Ih(t,e,n){switch(t){case E.Patterns.PATTERN000:return(e+n)%2===0;case E.Patterns.PATTERN001:return e%2===0;case E.Patterns.PATTERN010:return n%3===0;case E.Patterns.PATTERN011:return(e+n)%3===0;case E.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case E.Patterns.PATTERN101:return e*n%2+e*n%3===0;case E.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case E.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}E.applyMask=function(e,n){let s=n.size;for(let r=0;r<s;r++)for(let i=0;i<s;i++)n.isReserved(i,r)||n.xor(i,r,Ih(e,i,r))};E.getBestMask=function(e,n){let s=Object.keys(E.Patterns).length,r=0,i=1/0;for(let o=0;o<s;o++){n(o),E.applyMask(o,e);let a=E.getPenaltyN1(e)+E.getPenaltyN2(e)+E.getPenaltyN3(e)+E.getPenaltyN4(e);E.applyMask(o,e),a<i&&(i=a,r=o)}return r}});var qr=v(Wr=>{var Ee=as(),cs=[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],us=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Wr.getBlocksCount=function(e,n){switch(n){case Ee.L:return cs[(e-1)*4+0];case Ee.M:return cs[(e-1)*4+1];case Ee.Q:return cs[(e-1)*4+2];case Ee.H:return cs[(e-1)*4+3];default:return}};Wr.getTotalCodewordsCount=function(e,n){switch(n){case Ee.L:return us[(e-1)*4+0];case Ee.M:return us[(e-1)*4+1];case Ee.Q:return us[(e-1)*4+2];case Ee.H:return us[(e-1)*4+3];default:return}}});var el=v(fs=>{var on=new Uint8Array(512),ds=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)on[n]=e,ds[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)on[n]=on[n-255]})();fs.log=function(e){if(e<1)throw new Error("log("+e+")");return ds[e]};fs.exp=function(e){return on[e]};fs.mul=function(e,n){return e===0||n===0?0:on[ds[e]+ds[n]]}});var tl=v(an=>{var Gr=el();an.mul=function(e,n){let s=new Uint8Array(e.length+n.length-1);for(let r=0;r<e.length;r++)for(let i=0;i<n.length;i++)s[r+i]^=Gr.mul(e[r],n[i]);return s};an.mod=function(e,n){let s=new Uint8Array(e);for(;s.length-n.length>=0;){let r=s[0];for(let o=0;o<n.length;o++)s[o]^=Gr.mul(n[o],r);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s};an.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let s=0;s<e;s++)n=an.mul(n,new Uint8Array([1,Gr.exp(s)]));return n}});var rl=v((e0,sl)=>{var nl=tl();function jr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}jr.prototype.initialize=function(e){this.degree=e,this.genPoly=nl.generateECPolynomial(this.degree)};jr.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let s=nl.mod(n,this.genPoly),r=this.degree-s.length;if(r>0){let i=new Uint8Array(this.degree);return i.set(s,r),i}return s};sl.exports=jr});var $r=v(il=>{il.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var zr=v(we=>{var ol="[0-9]+",Ah="[A-Z $%*+\\-./:]+",ln="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";ln=ln.replace(/u/g,"\\u");var Th="(?:(?![A-Z0-9 $%*+\\-./:]|"+ln+`)(?:.|[\r
8
- ]))+`;we.KANJI=new RegExp(ln,"g");we.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");we.BYTE=new RegExp(Th,"g");we.NUMERIC=new RegExp(ol,"g");we.ALPHANUMERIC=new RegExp(Ah,"g");var Ch=new RegExp("^"+ln+"$"),kh=new RegExp("^"+ol+"$"),xh=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");we.testKanji=function(e){return Ch.test(e)};we.testNumeric=function(e){return kh.test(e)};we.testAlphanumeric=function(e){return xh.test(e)}});var Pe=v(B=>{var Rh=$r(),Vr=zr();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(!Rh.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 Vr.testNumeric(e)?B.NUMERIC:Vr.testAlphanumeric(e)?B.ALPHANUMERIC:Vr.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 Eh(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 Eh(e)}catch{return n}}});var dl=v(Ye=>{var ps=Re(),Ph=qr(),al=as(),Me=Pe(),Qr=$r(),cl=7973,ll=ps.getBCHDigit(cl);function Mh(t,e,n){for(let s=1;s<=40;s++)if(e<=Ye.getCapacity(s,n,t))return s}function ul(t,e){return Me.getCharCountIndicator(t,e)+4}function Lh(t,e){let n=0;return t.forEach(function(s){let r=ul(s.mode,e);n+=r+s.getBitsLength()}),n}function Nh(t,e){for(let n=1;n<=40;n++)if(Lh(t,n)<=Ye.getCapacity(n,e,Me.MIXED))return n}Ye.from=function(e,n){return Qr.isValid(e)?parseInt(e,10):n};Ye.getCapacity=function(e,n,s){if(!Qr.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=Me.BYTE);let r=ps.getSymbolTotalCodewords(e),i=Ph.getTotalCodewordsCount(e,n),o=(r-i)*8;if(s===Me.MIXED)return o;let a=o-ul(s,e);switch(s){case Me.NUMERIC:return Math.floor(a/10*3);case Me.ALPHANUMERIC:return Math.floor(a/11*2);case Me.KANJI:return Math.floor(a/13);case Me.BYTE:default:return Math.floor(a/8)}};Ye.getBestVersionForData=function(e,n){let s,r=al.from(n,al.M);if(Array.isArray(e)){if(e.length>1)return Nh(e,r);if(e.length===0)return 1;s=e[0]}else s=e;return Mh(s.mode,s.getLength(),r)};Ye.getEncodedBits=function(e){if(!Qr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;ps.getBCHDigit(n)-ll>=0;)n^=cl<<ps.getBCHDigit(n)-ll;return e<<12|n}});var gl=v(hl=>{var Jr=Re(),pl=1335,Oh=21522,fl=Jr.getBCHDigit(pl);hl.getEncodedBits=function(e,n){let s=e.bit<<3|n,r=s<<10;for(;Jr.getBCHDigit(r)-fl>=0;)r^=pl<<Jr.getBCHDigit(r)-fl;return(s<<10|r)^Oh}});var yl=v((o0,ml)=>{var Dh=Pe();function _t(t){this.mode=Dh.NUMERIC,this.data=t.toString()}_t.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(e){let n,s,r;for(n=0;n+3<=this.data.length;n+=3)s=this.data.substr(n,3),r=parseInt(s,10),e.put(r,10);let i=this.data.length-n;i>0&&(s=this.data.substr(n),r=parseInt(s,10),e.put(r,i*3+1))};ml.exports=_t});var Sl=v((a0,vl)=>{var Bh=Pe(),Yr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function bt(t){this.mode=Bh.ALPHANUMERIC,this.data=t}bt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let s=Yr.indexOf(this.data[n])*45;s+=Yr.indexOf(this.data[n+1]),e.put(s,11)}this.data.length%2&&e.put(Yr.indexOf(this.data[n]),6)};vl.exports=bt});var bl=v((l0,_l)=>{var Fh=Pe();function wt(t){this.mode=Fh.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}wt.getBitsLength=function(e){return e*8};wt.prototype.getLength=function(){return this.data.length};wt.prototype.getBitsLength=function(){return wt.getBitsLength(this.data.length)};wt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};_l.exports=wt});var Il=v((c0,wl)=>{var Uh=Pe(),Hh=Re();function It(t){this.mode=Uh.KANJI,this.data=t}It.getBitsLength=function(e){return e*13};It.prototype.getLength=function(){return this.data.length};It.prototype.getBitsLength=function(){return It.getBitsLength(this.data.length)};It.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Hh.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)}};wl.exports=It});var Al=v((u0,Kr)=>{"use strict";var cn={single_source_shortest_paths:function(t,e,n){var s={},r={};r[e]=0;var i=cn.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,u=o.cost,c=t[a]||{};for(l in c)c.hasOwnProperty(l)&&(d=c[l],f=u+d,h=r[l],g=typeof r[l]>"u",(g||h>f)&&(r[l]=f,i.push(l,f),s[l]=a))}if(typeof n<"u"&&typeof r[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],s=e,r;s;)n.push(s),r=t[s],s=t[s];return n.reverse(),n},find_path:function(t,e,n){var s=cn.single_source_shortest_paths(t,e,n);return cn.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var e=cn.PriorityQueue,n={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(n[s]=e[s]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Kr<"u"&&(Kr.exports=cn)});var Ml=v(At=>{var k=Pe(),kl=yl(),xl=Sl(),Rl=bl(),El=Il(),un=zr(),hs=Re(),Wh=Al();function Tl(t){return unescape(encodeURIComponent(t)).length}function dn(t,e,n){let s=[],r;for(;(r=t.exec(n))!==null;)s.push({data:r[0],index:r.index,mode:e,length:r[0].length});return s}function Pl(t){let e=dn(un.NUMERIC,k.NUMERIC,t),n=dn(un.ALPHANUMERIC,k.ALPHANUMERIC,t),s,r;return hs.isKanjiModeEnabled()?(s=dn(un.BYTE,k.BYTE,t),r=dn(un.KANJI,k.KANJI,t)):(s=dn(un.BYTE_KANJI,k.BYTE,t),r=[]),e.concat(n,s,r).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Xr(t,e){switch(e){case k.NUMERIC:return kl.getBitsLength(t);case k.ALPHANUMERIC:return xl.getBitsLength(t);case k.KANJI:return El.getBitsLength(t);case k.BYTE:return Rl.getBitsLength(t)}}function qh(t){return t.reduce(function(e,n){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Gh(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];switch(s.mode){case k.NUMERIC:e.push([s,{data:s.data,mode:k.ALPHANUMERIC,length:s.length},{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.ALPHANUMERIC:e.push([s,{data:s.data,mode:k.BYTE,length:s.length}]);break;case k.KANJI:e.push([s,{data:s.data,mode:k.BYTE,length:Tl(s.data)}]);break;case k.BYTE:e.push([{data:s.data,mode:k.BYTE,length:Tl(s.data)}])}}return e}function jh(t,e){let n={},s={start:{}},r=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},s[c]={};for(let d=0;d<r.length;d++){let f=r[d];n[f]&&n[f].node.mode===u.mode?(s[f][c]=Xr(n[f].lastCount+u.length,u.mode)-Xr(n[f].lastCount,u.mode),n[f].lastCount+=u.length):(n[f]&&(n[f].lastCount=u.length),s[f][c]=Xr(u.length,u.mode)+4+k.getCharCountIndicator(u.mode,e))}}r=a}for(let i=0;i<r.length;i++)s[r[i]].end=0;return{map:s,table:n}}function Cl(t,e){let n,s=k.getBestModeForData(t);if(n=k.from(e,s),n!==k.BYTE&&n.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+k.toString(n)+`.
10
- Suggested mode is: `+k.toString(s));switch(n===k.KANJI&&!hs.isKanjiModeEnabled()&&(n=k.BYTE),n){case k.NUMERIC:return new kl(t);case k.ALPHANUMERIC:return new xl(t);case k.KANJI:return new El(t);case k.BYTE:return new Rl(t)}}At.fromArray=function(e){return e.reduce(function(n,s){return typeof s=="string"?n.push(Cl(s,null)):s.data&&n.push(Cl(s.data,s.mode)),n},[])};At.fromString=function(e,n){let s=Pl(e,hs.isKanjiModeEnabled()),r=Gh(s),i=jh(r,n),o=Wh.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return At.fromArray(qh(a))};At.rawSplit=function(e){return At.fromArray(Pl(e,hs.isKanjiModeEnabled()))}});var ri=v(Ll=>{var ms=Re(),Zr=as(),$h=za(),zh=Qa(),Vh=Ja(),Qh=Xa(),ni=Za(),si=qr(),Jh=rl(),gs=dl(),Yh=gl(),Kh=Pe(),ei=Ml();function Xh(t,e){let n=t.size,s=Qh.getPositions(e);for(let r=0;r<s.length;r++){let i=s[r][0],o=s[r][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function Zh(t){let e=t.size;for(let n=8;n<e-8;n++){let s=n%2===0;t.set(n,6,s,!0),t.set(6,n,s,!0)}}function eg(t,e){let n=Vh.getPositions(e);for(let s=0;s<n.length;s++){let r=n[s][0],i=n[s][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(r+o,i+a,!0,!0):t.set(r+o,i+a,!1,!0)}}function tg(t,e){let n=t.size,s=gs.getEncodedBits(e),r,i,o;for(let a=0;a<18;a++)r=Math.floor(a/3),i=a%3+n-8-3,o=(s>>a&1)===1,t.set(r,i,o,!0),t.set(i,r,o,!0)}function ti(t,e,n){let s=t.size,r=Yh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(r>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(s-15+i,8,o,!0),i<8?t.set(8,s-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(s-8,8,1,!0)}function ng(t,e){let n=t.size,s=-1,r=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(r,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(r,a-l,u),i--,i===-1&&(o++,i=7)}if(r+=s,r<0||n<=r){r-=s,s=-s;break}}}function sg(t,e,n){let s=new $h;n.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),Kh.getCharCountIndicator(l.mode,t)),l.write(s)});let r=ms.getSymbolTotalCodewords(t),i=si.getTotalCodewordsCount(t,e),o=(r-i)*8;for(s.getLengthInBits()+4<=o&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let a=(o-s.getLengthInBits())/8;for(let l=0;l<a;l++)s.put(l%2?17:236,8);return rg(s,t,e)}function rg(t,e,n){let s=ms.getSymbolTotalCodewords(e),r=si.getTotalCodewordsCount(e,n),i=s-r,o=si.getBlocksCount(e,n),a=s%o,l=o-a,u=Math.floor(s/o),c=Math.floor(i/o),d=c+1,f=u-c,h=new Jh(f),g=0,m=new Array(o),p=new Array(o),y=0,C=new Uint8Array(t.buffer);for(let R=0;R<o;R++){let X=R<l?c:d;m[R]=C.slice(g,g+X),p[R]=h.encode(m[R]),g+=X,y=Math.max(y,X)}let A=new Uint8Array(s),T=0,I,D;for(I=0;I<y;I++)for(D=0;D<o;D++)I<m[D].length&&(A[T++]=m[D][I]);for(I=0;I<f;I++)for(D=0;D<o;D++)A[T++]=p[D][I];return A}function ig(t,e,n,s){let r;if(Array.isArray(t))r=ei.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=ei.rawSplit(t);u=gs.getBestVersionForData(c,n)}r=ei.fromString(t,u||40)}else throw new Error("Invalid data");let i=gs.getBestVersionForData(r,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
7
+ `+n)}function Ve(t,e,n,s,r,i){if(t.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,Ve),t.emit("wsClientError",o,n,e)}else sn(n,s,r,i)}});var Wr=v((jb,za)=>{za.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Re=v(Qe=>{var qr,_h=[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];Qe.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};Qe.getSymbolTotalCodewords=function(e){return _h[e]};Qe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Qe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');qr=e};Qe.isKanjiModeEnabled=function(){return typeof qr<"u"};Qe.toSJIS=function(e){return qr(e)}});var as=v(re=>{re.L={bit:1};re.M={bit:0};re.Q={bit:3};re.H={bit:2};function bh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return re.L;case"m":case"medium":return re.M;case"q":case"quartile":return re.Q;case"h":case"high":return re.H;default:throw new Error("Unknown EC Level: "+t)}}re.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};re.from=function(e,n){if(re.isValid(e))return e;try{return bh(e)}catch{return n}}});var Ja=v((Vb,Qa)=>{function Va(){this.buffer=[],this.length=0}Va.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Qa.exports=Va});var Ka=v((Qb,Ya)=>{function rn(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)}rn.prototype.set=function(t,e,n,s){let r=t*this.size+e;this.data[r]=n,s&&(this.reservedBit[r]=!0)};rn.prototype.get=function(t,e){return this.data[t*this.size+e]};rn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};rn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ya.exports=rn});var Xa=v(ls=>{var wh=Re().getSymbolSize;ls.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,s=wh(e),r=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-r;return i.push(6),i.reverse()};ls.getPositions=function(e){let n=[],s=ls.getRowColCoords(e),r=s.length;for(let i=0;i<r;i++)for(let o=0;o<r;o++)i===0&&o===0||i===0&&o===r-1||i===r-1&&o===0||n.push([s[i],s[o]]);return n}});var tl=v(el=>{var Ih=Re().getSymbolSize,Za=7;el.getPositions=function(e){let n=Ih(e);return[[0,0],[n-Za,0],[0,n-Za]]}});var nl=v(E=>{E.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};E.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};E.from=function(e){return E.isValid(e)?parseInt(e,10):void 0};E.getPenaltyN1=function(e){let n=e.size,s=0,r=0,i=0,o=null,a=null;for(let l=0;l<n;l++){r=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?r++:(r>=5&&(s+=Je.N1+(r-5)),o=c,r=1),c=e.get(u,l),c===a?i++:(i>=5&&(s+=Je.N1+(i-5)),a=c,i=1)}r>=5&&(s+=Je.N1+(r-5)),i>=5&&(s+=Je.N1+(i-5))}return s};E.getPenaltyN2=function(e){let n=e.size,s=0;for(let r=0;r<n-1;r++)for(let i=0;i<n-1;i++){let o=e.get(r,i)+e.get(r,i+1)+e.get(r+1,i)+e.get(r+1,i+1);(o===4||o===0)&&s++}return s*Je.N2};E.getPenaltyN3=function(e){let n=e.size,s=0,r=0,i=0;for(let o=0;o<n;o++){r=i=0;for(let a=0;a<n;a++)r=r<<1&2047|e.get(o,a),a>=10&&(r===1488||r===93)&&s++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&s++}return s*Je.N3};E.getPenaltyN4=function(e){let n=0,s=e.data.length;for(let i=0;i<s;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/s/5)-10)*Je.N4};function Ah(t,e,n){switch(t){case E.Patterns.PATTERN000:return(e+n)%2===0;case E.Patterns.PATTERN001:return e%2===0;case E.Patterns.PATTERN010:return n%3===0;case E.Patterns.PATTERN011:return(e+n)%3===0;case E.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case E.Patterns.PATTERN101:return e*n%2+e*n%3===0;case E.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case E.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}E.applyMask=function(e,n){let s=n.size;for(let r=0;r<s;r++)for(let i=0;i<s;i++)n.isReserved(i,r)||n.xor(i,r,Ah(e,i,r))};E.getBestMask=function(e,n){let s=Object.keys(E.Patterns).length,r=0,i=1/0;for(let o=0;o<s;o++){n(o),E.applyMask(o,e);let a=E.getPenaltyN1(e)+E.getPenaltyN2(e)+E.getPenaltyN3(e)+E.getPenaltyN4(e);E.applyMask(o,e),a<i&&(i=a,r=o)}return r}});var jr=v(Gr=>{var Ee=as(),cs=[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],us=[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];Gr.getBlocksCount=function(e,n){switch(n){case Ee.L:return cs[(e-1)*4+0];case Ee.M:return cs[(e-1)*4+1];case Ee.Q:return cs[(e-1)*4+2];case Ee.H:return cs[(e-1)*4+3];default:return}};Gr.getTotalCodewordsCount=function(e,n){switch(n){case Ee.L:return us[(e-1)*4+0];case Ee.M:return us[(e-1)*4+1];case Ee.Q:return us[(e-1)*4+2];case Ee.H:return us[(e-1)*4+3];default:return}}});var sl=v(fs=>{var on=new Uint8Array(512),ds=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)on[n]=e,ds[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)on[n]=on[n-255]})();fs.log=function(e){if(e<1)throw new Error("log("+e+")");return ds[e]};fs.exp=function(e){return on[e]};fs.mul=function(e,n){return e===0||n===0?0:on[ds[e]+ds[n]]}});var rl=v(an=>{var $r=sl();an.mul=function(e,n){let s=new Uint8Array(e.length+n.length-1);for(let r=0;r<e.length;r++)for(let i=0;i<n.length;i++)s[r+i]^=$r.mul(e[r],n[i]);return s};an.mod=function(e,n){let s=new Uint8Array(e);for(;s.length-n.length>=0;){let r=s[0];for(let o=0;o<n.length;o++)s[o]^=$r.mul(n[o],r);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s};an.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let s=0;s<e;s++)n=an.mul(n,new Uint8Array([1,$r.exp(s)]));return n}});var al=v((t0,ol)=>{var il=rl();function zr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}zr.prototype.initialize=function(e){this.degree=e,this.genPoly=il.generateECPolynomial(this.degree)};zr.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let s=il.mod(n,this.genPoly),r=this.degree-s.length;if(r>0){let i=new Uint8Array(this.degree);return i.set(s,r),i}return s};ol.exports=zr});var Vr=v(ll=>{ll.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Qr=v(we=>{var cl="[0-9]+",Th="[A-Z $%*+\\-./:]+",ln="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";ln=ln.replace(/u/g,"\\u");var kh="(?:(?![A-Z0-9 $%*+\\-./:]|"+ln+`)(?:.|[\r
8
+ ]))+`;we.KANJI=new RegExp(ln,"g");we.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");we.BYTE=new RegExp(kh,"g");we.NUMERIC=new RegExp(cl,"g");we.ALPHANUMERIC=new RegExp(Th,"g");var Ch=new RegExp("^"+ln+"$"),xh=new RegExp("^"+cl+"$"),Rh=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");we.testKanji=function(e){return Ch.test(e)};we.testNumeric=function(e){return xh.test(e)};we.testAlphanumeric=function(e){return Rh.test(e)}});var Pe=v(B=>{var Eh=Vr(),Jr=Qr();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(!Eh.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 Jr.testNumeric(e)?B.NUMERIC:Jr.testAlphanumeric(e)?B.ALPHANUMERIC:Jr.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 Ph(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 Ph(e)}catch{return n}}});var hl=v(Ye=>{var ps=Re(),Mh=jr(),ul=as(),Me=Pe(),Yr=Vr(),fl=7973,dl=ps.getBCHDigit(fl);function Lh(t,e,n){for(let s=1;s<=40;s++)if(e<=Ye.getCapacity(s,n,t))return s}function pl(t,e){return Me.getCharCountIndicator(t,e)+4}function Nh(t,e){let n=0;return t.forEach(function(s){let r=pl(s.mode,e);n+=r+s.getBitsLength()}),n}function Oh(t,e){for(let n=1;n<=40;n++)if(Nh(t,n)<=Ye.getCapacity(n,e,Me.MIXED))return n}Ye.from=function(e,n){return Yr.isValid(e)?parseInt(e,10):n};Ye.getCapacity=function(e,n,s){if(!Yr.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=Me.BYTE);let r=ps.getSymbolTotalCodewords(e),i=Mh.getTotalCodewordsCount(e,n),o=(r-i)*8;if(s===Me.MIXED)return o;let a=o-pl(s,e);switch(s){case Me.NUMERIC:return Math.floor(a/10*3);case Me.ALPHANUMERIC:return Math.floor(a/11*2);case Me.KANJI:return Math.floor(a/13);case Me.BYTE:default:return Math.floor(a/8)}};Ye.getBestVersionForData=function(e,n){let s,r=ul.from(n,ul.M);if(Array.isArray(e)){if(e.length>1)return Oh(e,r);if(e.length===0)return 1;s=e[0]}else s=e;return Lh(s.mode,s.getLength(),r)};Ye.getEncodedBits=function(e){if(!Yr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;ps.getBCHDigit(n)-dl>=0;)n^=fl<<ps.getBCHDigit(n)-dl;return e<<12|n}});var vl=v(yl=>{var Kr=Re(),ml=1335,Dh=21522,gl=Kr.getBCHDigit(ml);yl.getEncodedBits=function(e,n){let s=e.bit<<3|n,r=s<<10;for(;Kr.getBCHDigit(r)-gl>=0;)r^=ml<<Kr.getBCHDigit(r)-gl;return(s<<10|r)^Dh}});var _l=v((a0,Sl)=>{var Bh=Pe();function _t(t){this.mode=Bh.NUMERIC,this.data=t.toString()}_t.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(e){let n,s,r;for(n=0;n+3<=this.data.length;n+=3)s=this.data.substr(n,3),r=parseInt(s,10),e.put(r,10);let i=this.data.length-n;i>0&&(s=this.data.substr(n),r=parseInt(s,10),e.put(r,i*3+1))};Sl.exports=_t});var wl=v((l0,bl)=>{var Fh=Pe(),Xr=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function bt(t){this.mode=Fh.ALPHANUMERIC,this.data=t}bt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let s=Xr.indexOf(this.data[n])*45;s+=Xr.indexOf(this.data[n+1]),e.put(s,11)}this.data.length%2&&e.put(Xr.indexOf(this.data[n]),6)};bl.exports=bt});var Al=v((c0,Il)=>{var Uh=Pe();function wt(t){this.mode=Uh.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}wt.getBitsLength=function(e){return e*8};wt.prototype.getLength=function(){return this.data.length};wt.prototype.getBitsLength=function(){return wt.getBitsLength(this.data.length)};wt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Il.exports=wt});var kl=v((u0,Tl)=>{var Hh=Pe(),Wh=Re();function It(t){this.mode=Hh.KANJI,this.data=t}It.getBitsLength=function(e){return e*13};It.prototype.getLength=function(){return this.data.length};It.prototype.getBitsLength=function(){return It.getBitsLength(this.data.length)};It.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Wh.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)}};Tl.exports=It});var Cl=v((d0,Zr)=>{"use strict";var cn={single_source_shortest_paths:function(t,e,n){var s={},r={};r[e]=0;var i=cn.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,f,p,g;!i.empty();){o=i.pop(),a=o.value,u=o.cost,c=t[a]||{};for(l in c)c.hasOwnProperty(l)&&(d=c[l],f=u+d,p=r[l],g=typeof r[l]>"u",(g||p>f)&&(r[l]=f,i.push(l,f),s[l]=a))}if(typeof n<"u"&&typeof r[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],s=e,r;s;)n.push(s),r=t[s],s=t[s];return n.reverse(),n},find_path:function(t,e,n){var s=cn.single_source_shortest_paths(t,e,n);return cn.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(t){var e=cn.PriorityQueue,n={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(n[s]=e[s]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Zr<"u"&&(Zr.exports=cn)});var Ol=v(At=>{var C=Pe(),El=_l(),Pl=wl(),Ml=Al(),Ll=kl(),un=Qr(),hs=Re(),qh=Cl();function xl(t){return unescape(encodeURIComponent(t)).length}function dn(t,e,n){let s=[],r;for(;(r=t.exec(n))!==null;)s.push({data:r[0],index:r.index,mode:e,length:r[0].length});return s}function Nl(t){let e=dn(un.NUMERIC,C.NUMERIC,t),n=dn(un.ALPHANUMERIC,C.ALPHANUMERIC,t),s,r;return hs.isKanjiModeEnabled()?(s=dn(un.BYTE,C.BYTE,t),r=dn(un.KANJI,C.KANJI,t)):(s=dn(un.BYTE_KANJI,C.BYTE,t),r=[]),e.concat(n,s,r).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function ei(t,e){switch(e){case C.NUMERIC:return El.getBitsLength(t);case C.ALPHANUMERIC:return Pl.getBitsLength(t);case C.KANJI:return Ll.getBitsLength(t);case C.BYTE:return Ml.getBitsLength(t)}}function Gh(t){return t.reduce(function(e,n){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function jh(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];switch(s.mode){case C.NUMERIC:e.push([s,{data:s.data,mode:C.ALPHANUMERIC,length:s.length},{data:s.data,mode:C.BYTE,length:s.length}]);break;case C.ALPHANUMERIC:e.push([s,{data:s.data,mode:C.BYTE,length:s.length}]);break;case C.KANJI:e.push([s,{data:s.data,mode:C.BYTE,length:xl(s.data)}]);break;case C.BYTE:e.push([{data:s.data,mode:C.BYTE,length:xl(s.data)}])}}return e}function $h(t,e){let n={},s={start:{}},r=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},s[c]={};for(let d=0;d<r.length;d++){let f=r[d];n[f]&&n[f].node.mode===u.mode?(s[f][c]=ei(n[f].lastCount+u.length,u.mode)-ei(n[f].lastCount,u.mode),n[f].lastCount+=u.length):(n[f]&&(n[f].lastCount=u.length),s[f][c]=ei(u.length,u.mode)+4+C.getCharCountIndicator(u.mode,e))}}r=a}for(let i=0;i<r.length;i++)s[r[i]].end=0;return{map:s,table:n}}function Rl(t,e){let n,s=C.getBestModeForData(t);if(n=C.from(e,s),n!==C.BYTE&&n.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+C.toString(n)+`.
10
+ Suggested mode is: `+C.toString(s));switch(n===C.KANJI&&!hs.isKanjiModeEnabled()&&(n=C.BYTE),n){case C.NUMERIC:return new El(t);case C.ALPHANUMERIC:return new Pl(t);case C.KANJI:return new Ll(t);case C.BYTE:return new Ml(t)}}At.fromArray=function(e){return e.reduce(function(n,s){return typeof s=="string"?n.push(Rl(s,null)):s.data&&n.push(Rl(s.data,s.mode)),n},[])};At.fromString=function(e,n){let s=Nl(e,hs.isKanjiModeEnabled()),r=jh(s),i=$h(r,n),o=qh.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return At.fromArray(Gh(a))};At.rawSplit=function(e){return At.fromArray(Nl(e,hs.isKanjiModeEnabled()))}});var oi=v(Dl=>{var ms=Re(),ti=as(),zh=Ja(),Vh=Ka(),Qh=Xa(),Jh=tl(),ri=nl(),ii=jr(),Yh=al(),gs=hl(),Kh=vl(),Xh=Pe(),ni=Ol();function Zh(t,e){let n=t.size,s=Jh.getPositions(e);for(let r=0;r<s.length;r++){let i=s[r][0],o=s[r][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function eg(t){let e=t.size;for(let n=8;n<e-8;n++){let s=n%2===0;t.set(n,6,s,!0),t.set(6,n,s,!0)}}function tg(t,e){let n=Qh.getPositions(e);for(let s=0;s<n.length;s++){let r=n[s][0],i=n[s][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(r+o,i+a,!0,!0):t.set(r+o,i+a,!1,!0)}}function ng(t,e){let n=t.size,s=gs.getEncodedBits(e),r,i,o;for(let a=0;a<18;a++)r=Math.floor(a/3),i=a%3+n-8-3,o=(s>>a&1)===1,t.set(r,i,o,!0),t.set(i,r,o,!0)}function si(t,e,n){let s=t.size,r=Kh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(r>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(s-15+i,8,o,!0),i<8?t.set(8,s-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(s-8,8,1,!0)}function sg(t,e){let n=t.size,s=-1,r=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(r,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(r,a-l,u),i--,i===-1&&(o++,i=7)}if(r+=s,r<0||n<=r){r-=s,s=-s;break}}}function rg(t,e,n){let s=new zh;n.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),Xh.getCharCountIndicator(l.mode,t)),l.write(s)});let r=ms.getSymbolTotalCodewords(t),i=ii.getTotalCodewordsCount(t,e),o=(r-i)*8;for(s.getLengthInBits()+4<=o&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let a=(o-s.getLengthInBits())/8;for(let l=0;l<a;l++)s.put(l%2?17:236,8);return ig(s,t,e)}function ig(t,e,n){let s=ms.getSymbolTotalCodewords(e),r=ii.getTotalCodewordsCount(e,n),i=s-r,o=ii.getBlocksCount(e,n),a=s%o,l=o-a,u=Math.floor(s/o),c=Math.floor(i/o),d=c+1,f=u-c,p=new Yh(f),g=0,m=new Array(o),h=new Array(o),y=0,T=new Uint8Array(t.buffer);for(let x=0;x<o;x++){let X=x<l?c:d;m[x]=T.slice(g,g+X),h[x]=p.encode(m[x]),g+=X,y=Math.max(y,X)}let I=new Uint8Array(s),k=0,A,D;for(A=0;A<y;A++)for(D=0;D<o;D++)A<m[D].length&&(I[k++]=m[D][A]);for(A=0;A<f;A++)for(D=0;D<o;D++)I[k++]=h[D][A];return I}function og(t,e,n,s){let r;if(Array.isArray(t))r=ni.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=ni.rawSplit(t);u=gs.getBestVersionForData(c,n)}r=ni.fromString(t,u||40)}else throw new Error("Invalid data");let i=gs.getBestVersionForData(r,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
12
  Minimum version required to store current data is: `+i+`.
13
- `);let o=sg(e,n,r),a=ms.getSymbolSize(e),l=new zh(a);return Xh(l,e),Zh(l),eg(l,e),ti(l,n,0),e>=7&&tg(l,e),ng(l,o),isNaN(s)&&(s=ni.getBestMask(l,ti.bind(null,l,n))),ni.applyMask(s,l),ti(l,n,s),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:s,segments:r}}Ll.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let s=Zr.M,r,i;return typeof n<"u"&&(s=Zr.from(n.errorCorrectionLevel,Zr.M),r=gs.from(n.version),i=ni.from(n.maskPattern),n.toSJISFunc&&ms.setToSJISFunction(n.toSJISFunc)),ig(e,r,s,i)}});var ii=v((p0,Ol)=>{"use strict";var og=require("util"),Nl=require("stream"),ue=Ol.exports=function(){Nl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};og.inherits(ue,Nl);ue.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};ue.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};ue.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};ue.prototype.destroySoon=ue.prototype.end;ue.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ue.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ue.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};ue.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let r=this._buffers[n++],i=Math.min(r.length,t.length-e);r.copy(s,e,0,i),e+=i,i!==r.length&&(this._buffers[--n]=r.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};ue.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ai=v(oi=>{"use strict";var Le=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];oi.getImagePasses=function(t,e){let n=[],s=t%8,r=e%8,i=(t-s)/8,o=(e-r)/8;for(let a=0;a<Le.length;a++){let l=Le[a],u=i*l.x.length,c=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<s;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<r;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};oi.getInterlaceIterator=function(t){return function(e,n,s){let r=e%Le[s].x.length,i=(e-r)/Le[s].x.length*8+Le[s].x[r],o=n%Le[s].y.length,a=(n-o)/Le[s].y.length*8+Le[s].y[o];return i*4+a*t*4}}});var li=v((g0,Dl)=>{"use strict";Dl.exports=function(e,n,s){let r=e+n-s,i=Math.abs(r-e),o=Math.abs(r-n),a=Math.abs(r-s);return i<=o&&i<=a?e:o<=a?n:s}});var ci=v((m0,Fl)=>{"use strict";var ag=ai(),lg=li();function Bl(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var Tt=Fl.exports=function(t,e){let n=t.width,s=t.height,r=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],r){let a=ag.getImagePasses(n,s);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Bl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Bl(n,i,o),height:s,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};Tt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Tt.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,r=s-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>r?e[i-s]:0;e[i]=o+a}};Tt.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let r=0;r<n;r++){let i=t[1+r],o=s?s[r]:0;e[r]=i+o}};Tt.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=Math.floor((u+l)/2);e[o]=a+c}};Tt.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=o>r&&i?i[o-s]:0,d=lg(u,l,c);e[o]=a+d}};Tt.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],r=s.byteWidth;if(e===0)n=t.slice(1,r+1);else switch(n=Buffer.alloc(r),e){case 1:this._unFilterType1(t,n,r);break;case 2:this._unFilterType2(t,n,r);break;case 3:this._unFilterType3(t,n,r);break;case 4:this._unFilterType4(t,n,r);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Wl=v((y0,Hl)=>{"use strict";var cg=require("util"),Ul=ii(),ug=ci(),dg=Hl.exports=function(t){Ul.call(this);let e=[],n=this;this._filter=new ug(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};cg.inherits(dg,Ul)});var Ct=v((v0,ql)=>{"use strict";ql.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 fi=v((S0,Gl)=>{"use strict";var ui=[];(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;ui[t]=e}})();var di=Gl.exports=function(){this._crc=-1};di.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ui[(this._crc^t[e])&255]^this._crc>>>8;return!0};di.prototype.crc32=function(){return this._crc^-1};di.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ui[(e^t[n])&255]^e>>>8;return e^-1}});var pi=v((_0,jl)=>{"use strict";var q=Ct(),fg=fi(),z=jl.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[q.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[q.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[q.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[q.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[q.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[q.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(){}};z.prototype.start=function(){this.read(q.PNG_SIGNATURE.length,this._parseSignature.bind(this))};z.prototype._parseSignature=function(t){let e=q.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))};z.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let i=4;i<8;i++)s+=String.fromCharCode(t[i]);let r=!!(t[4]&32);if(!this._hasIHDR&&n!==q.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new fg,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!r){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};z.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};z.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};z.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))};z.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};z.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],r=t[9],i=t[10],o=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(r in q.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=r;let l=q.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(r&q.COLORTYPE_PALETTE),color:!!(r&q.COLORTYPE_COLOR),alpha:!!(r&q.COLORTYPE_ALPHA),bpp:l,colorType:r}),this._handleChunkEnd()};z.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};z.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()};z.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};z.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===q.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===q.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===q.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};z.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};z.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/q.GAMMA_DIVISION),this._handleChunkEnd()};z.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};z.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===q.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()};z.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};z.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var hi=v(zl=>{"use strict";var $l=ai(),pg=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],hg=[function(){},function(t,e,n,s){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function gg(t,e){let n=[],s=0;function r(){if(s===t.length)throw new Error("Ran out of data");let i=t[s];s++;let o,a,l,u,c,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[s],s++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:c=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,c);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,u=i>>3&1,c=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)r();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function mg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<o;c++){let d=n(c,u,l);pg[s](e,r,d,i),i+=s}return i}function yg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<o;c++){let d=r.get(s),f=n(c,u,l);hg[s](e,d,f,i)}r.resetAfterLine()}}zl.dataToBitMap=function(t,e){let n=e.width,s=e.height,r=e.depth,i=e.bpp,o=e.interlace,a;r!==8&&(a=gg(t,r));let l;r<=8?l=Buffer.alloc(n*s*4):l=new Uint16Array(n*s*4);let u=Math.pow(2,r)-1,c=0,d,f;if(o)d=$l.getImagePasses(n,s),f=$l.getInterlaceIterator(n,s);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:s}]}for(let h=0;h<d.length;h++)r===8?c=mg(d[h],l,f,i,t,c):yg(d[h],l,f,i,a,u);if(r===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var gi=v((w0,Vl)=>{"use strict";function vg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=r[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function Sg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=!1;if(r.length===1?r[0]===t[i]&&(l=!0):r[0]===t[i]&&r[1]===t[i+1]&&r[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function _g(t,e,n,s,r){let i=255,o=Math.pow(2,r)-1,a=0;for(let l=0;l<s;l++)for(let u=0;u<n;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*i/o+.5);a+=4}}Vl.exports=function(t,e){let n=e.depth,s=e.width,r=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?vg(t,l,s,r,a):(o&&Sg(t,l,s,r,o),n!==8&&(n===16&&(l=Buffer.alloc(s*r*4)),_g(t,l,s,r,n))),l}});var Yl=v((I0,Jl)=>{"use strict";var bg=require("util"),mi=require("zlib"),Ql=ii(),wg=Wl(),Ig=pi(),Ag=hi(),Tg=gi(),ge=Jl.exports=function(t){Ql.call(this),this._parser=new Ig(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()};bg.inherits(ge,Ql);ge.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};ge.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=mi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(n,mi.Z_MIN_CHUNK);this._inflate=mi.createInflate({chunkSize:s});let r=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){r&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){r&&(a.length>r&&(a=a.slice(0,r)),r-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new wg(this._bitmapInfo)};ge.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ge.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ge.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ge.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ge.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ge.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Ag.dataToBitMap(t,this._bitmapInfo);e=Tg(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Xl=v((A0,Kl)=>{"use strict";var ie=Ct();Kl.exports=function(t,e,n,s){let r=[ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let g=(function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&g)return t}let i=s.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ie.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let l=ie.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=s.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,m,p,y=o;switch(s.inputColorType){case ie.COLORTYPE_COLOR_ALPHA:y=i[c+3],g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_COLOR:g=i[c],m=i[c+1],p=i[c+2];break;case ie.COLORTYPE_ALPHA:y=i[c+1],g=i[c],m=g,p=g;break;case ie.COLORTYPE_GRAYSCALE:g=i[c],m=g,p=g;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(r||(y/=o,g=Math.min(Math.max(Math.round((1-y)*f.red+y*g),0),o),m=Math.min(Math.max(Math.round((1-y)*f.green+y*m),0),o),p=Math.min(Math.max(Math.round((1-y)*f.blue+y*p),0),o))),{red:g,green:m,blue:p,alpha:y}}for(let g=0;g<n;g++)for(let m=0;m<e;m++){let p=h(i,c);switch(s.colorType){case ie.COLORTYPE_COLOR_ALPHA:case ie.COLORTYPE_COLOR:s.bitDepth===8?(u[d]=p.red,u[d+1]=p.green,u[d+2]=p.blue,r&&(u[d+3]=p.alpha)):(u.writeUInt16BE(p.red,d),u.writeUInt16BE(p.green,d+2),u.writeUInt16BE(p.blue,d+4),r&&u.writeUInt16BE(p.alpha,d+6));break;case ie.COLORTYPE_ALPHA:case ie.COLORTYPE_GRAYSCALE:{let y=(p.red+p.green+p.blue)/3;s.bitDepth===8?(u[d]=y,r&&(u[d+1]=p.alpha)):(u.writeUInt16BE(y,d),r&&u.writeUInt16BE(p.alpha,d+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}c+=a,d+=l}return u}});var tc=v((T0,ec)=>{"use strict";var Zl=li();function Cg(t,e,n,s,r){for(let i=0;i<n;i++)s[r+i]=t[e+i]}function kg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++)s+=Math.abs(t[i]);return s}function xg(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;s[r+o]=l}}function Rg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=t[e+i]-o;r+=Math.abs(a)}return r}function Eg(t,e,n,s,r){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;s[r+i]=a}}function Pg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++){let o=e>0?t[i-n]:0,a=t[i]-o;s+=Math.abs(a)}return s}function Mg(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=t[e+o]-(a+l>>1);s[r+o]=u}}function Lg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);r+=Math.abs(l)}return r}function Ng(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-Zl(a,l,u);s[r+o]=c}}function Og(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=s?t[e+i-(n+s)]:0,u=t[e+i]-Zl(o,a,l);r+=Math.abs(u)}return r}var Dg={0:Cg,1:xg,2:Eg,3:Mg,4:Ng},Bg={0:kg,1:Rg,2:Pg,3:Lg,4:Og};ec.exports=function(t,e,n,s,r){let i;if(!("filterType"in s)||s.filterType===-1)i=[0,1,2,3,4];else if(typeof s.filterType=="number")i=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(r*=2);let o=e*r,a=0,l=0,u=Buffer.alloc((o+1)*n),c=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=Bg[i[h]](t,l,o,r);g<f&&(c=i[h],f=g)}}u[a]=c,a++,Dg[c](t,l,o,u,a,r),a+=o,l+=o}return u}});var yi=v((C0,nc)=>{"use strict";var V=Ct(),Fg=fi(),Ug=Xl(),Hg=tc(),Wg=require("zlib"),Ne=nc.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||Wg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:V.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:V.COLORTYPE_COLOR_ALPHA,[V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Ne.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ne.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ne.prototype.filterData=function(t,e,n){let s=Ug(t,e,n,this._options),r=V.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Hg(s,e,n,this._options,r)};Ne.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(Fg.crc32(s.slice(4,s.length-4)),s.length-4),s};Ne.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*V.GAMMA_DIVISION),0),this._packChunk(V.TYPE_gAMA,e)};Ne.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(V.TYPE_IHDR,n)};Ne.prototype.packIDAT=function(t){return this._packChunk(V.TYPE_IDAT,t)};Ne.prototype.packIEND=function(){return this._packChunk(V.TYPE_IEND,null)}});var oc=v((k0,ic)=>{"use strict";var qg=require("util"),sc=require("stream"),Gg=Ct(),jg=yi(),rc=ic.exports=function(t){sc.call(this);let e=t||{};this._packer=new jg(e),this._deflate=this._packer.createDeflate(),this.readable=!0};qg.inherits(rc,sc);rc.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(Gg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let r=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(r)}});var fc=v((fn,dc)=>{"use strict";var ac=require("assert").ok,kt=require("zlib"),$g=require("util"),lc=require("buffer").kMaxLength;function Ke(t){if(!(this instanceof Ke))return new Ke(t);t&&t.chunkSize<kt.Z_MIN_CHUNK&&(t.chunkSize=kt.Z_MIN_CHUNK),kt.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 zg(t){return new Ke(t)}function cc(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ke.prototype._processChunk=function(t,e,n){if(typeof n=="function")return kt.Inflate._processChunk.call(this,t,e,n);let s=this,r=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(g){c=g});function d(g,m){if(s._hadError)return;let p=i-m;if(ac(p>=0,"have should not go down"),p>0){let y=s._buffer.slice(s._offset,s._offset+p);if(s._offset+=p,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(m===0||s._offset>=s._chunkSize)&&(i=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),m===0?(a+=r-g,r=g,!0):!1}ac(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,r,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=lc)throw cc(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+lc.toString(16)+" bytes");let h=Buffer.concat(l,u);return cc(this),h};$g.inherits(Ke,kt.Inflate);function Vg(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=kt.Z_FINISH),t._processChunk(e,n)}function uc(t,e){return Vg(new Ke(e),t)}dc.exports=fn=uc;fn.Inflate=Ke;fn.createInflate=zg;fn.inflateSync=uc});var vi=v((x0,hc)=>{"use strict";var pc=hc.exports=function(t){this._buffer=t,this._reads=[]};pc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};pc.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 mc=v(gc=>{"use strict";var Qg=vi(),Jg=ci();gc.process=function(t,e){let n=[],s=new Qg(t);return new Jg(e,{read:s.read.bind(s),write:function(i){n.push(i)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var _c=v((E0,Sc)=>{"use strict";var yc=!0,vc=require("zlib"),Yg=fc();vc.deflateSync||(yc=!1);var Kg=vi(),Xg=mc(),Zg=pi(),em=hi(),tm=gi();Sc.exports=function(t,e){if(!yc)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function s(T){n=T}let r;function i(T){r=T}function o(T){r.transColor=T}function a(T){r.palette=T}function l(){r.alpha=!0}let u;function c(T){u=T}let d=[];function f(T){d.push(T)}let h=new Kg(t);if(new Zg(e,{read:h.read.bind(h),error:s,metadata:i,gamma:c,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let m=Buffer.concat(d);d.length=0;let p;if(r.interlace)p=vc.inflateSync(m);else{let I=((r.width*r.bpp*r.depth+7>>3)+1)*r.height;p=Yg(m,{chunkSize:I,maxLength:I})}if(m=null,!p||!p.length)throw new Error("bad png - invalid inflate data response");let y=Xg.process(p,r);m=null;let C=em.dataToBitMap(y,r);y=null;let A=tm(C,r);return r.data=A,r.gamma=u||0,r}});var Ac=v((P0,Ic)=>{"use strict";var bc=!0,wc=require("zlib");wc.deflateSync||(bc=!1);var nm=Ct(),sm=yi();Ic.exports=function(t,e){if(!bc)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},s=new sm(n),r=[];r.push(Buffer.from(nm.PNG_SIGNATURE)),r.push(s.packIHDR(t.width,t.height)),t.gamma&&r.push(s.packGAMA(t.gamma));let i=s.filterData(t.data,t.width,t.height),o=wc.deflateSync(i,s.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return r.push(s.packIDAT(o)),r.push(s.packIEND()),Buffer.concat(r)}});var Tc=v(Si=>{"use strict";var rm=_c(),im=Ac();Si.read=function(t,e){return rm(t,e||{})};Si.write=function(t,e){return im(t,e)}});var xc=v(kc=>{"use strict";var om=require("util"),Cc=require("stream"),am=Yl(),lm=oc(),cm=Tc(),J=kc.PNG=function(t){Cc.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 am(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 lm(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"))};om.inherits(J,Cc);J.sync=cm;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,s;n=function(r){this.removeListener("error",s),this.data=r,e(null,this)}.bind(this),s=function(r){this.removeListener("parsed",n),e(r,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};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,s,r,i,o,a){if(n|=0,s|=0,r|=0,i|=0,o|=0,a|=0,n>t.width||s>t.height||n+r>t.width||s+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+r>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(s+l)*t.width+n<<2,(s+l)*t.width+n+r<<2)};J.prototype.bitblt=function(t,e,n,s,r,i,o){return J.bitblt(this,t,e,n,s,r,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 s=t.width*e+n<<2;for(let r=0;r<3;r++){let i=t.data[s+r]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[s+r]=Math.round(i*255)}}t.gamma=0}};J.prototype.adjustGamma=function(){J.adjustGamma(this)}});var pn=v(Xe=>{function Rc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(s){return[s,s]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Xe.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,r=e.scale||4;return{width:s,scale:s?4:r,margin:n,color:{dark:Rc(e.color.dark||"#000000ff"),light:Rc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Xe.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Xe.getImageWidth=function(e,n){let s=Xe.getScale(e,n);return Math.floor((e+n.margin*2)*s)};Xe.qrToImageData=function(e,n,s){let r=n.modules.size,i=n.modules.data,o=Xe.getScale(r,s),a=Math.floor((r+s.margin*2)*o),l=s.margin*o,u=[s.color.light,s.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let f=(c*a+d)*4,h=s.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let g=Math.floor((c-l)/o),m=Math.floor((d-l)/o);h=u[i[g*r+m]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Ec=v(me=>{var um=require("fs"),dm=xc().PNG,_i=pn();me.render=function(e,n){let s=_i.getOptions(n),r=s.rendererOpts,i=_i.getImageWidth(e.modules.size,s);r.width=i,r.height=i;let o=new dm(r);return _i.qrToImageData(o.data,e,s),o};me.renderToDataURL=function(e,n,s){typeof s>"u"&&(s=n,n=void 0),me.renderToBuffer(e,n,function(r,i){r&&s(r);let o="data:image/png;base64,";o+=i.toString("base64"),s(null,o)})};me.renderToBuffer=function(e,n,s){typeof s>"u"&&(s=n,n=void 0);let r=me.render(e,n),i=[];r.on("error",s),r.on("data",function(o){i.push(o)}),r.on("end",function(){s(null,Buffer.concat(i))}),r.pack()};me.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=!1,o=(...l)=>{i||(i=!0,r.apply(null,l))},a=um.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,s)};me.renderToFileStream=function(e,n,s){me.render(n,s).pack().pipe(e)}});var Pc=v(ys=>{var fm=pn(),pm={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},hm={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function gm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}ys.render=function(t,e,n){let s=fm.getOptions(e),r=pm;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(r=hm);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+s.margin*2+1).join(r.WW);l=Array(s.margin/2+1).join(l+`
14
- `);let u=Array(s.margin+1).join(r.WW);a+=l;for(let c=0;c<i;c+=2){a+=u;for(let d=0;d<i;d++){let f=o[c*i+d],h=o[(c+1)*i+d];a+=gm(f,h,r)}a+=u+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};ys.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),o=ys.render(n,s);i.writeFile(e,o,r)}});var Lc=v(Mc=>{Mc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(s+3).join(o),u=Array(2).join(o);a+=l+`
13
+ `);let o=rg(e,n,r),a=ms.getSymbolSize(e),l=new Vh(a);return Zh(l,e),eg(l),tg(l,e),si(l,n,0),e>=7&&ng(l,e),sg(l,o),isNaN(s)&&(s=ri.getBestMask(l,si.bind(null,l,n))),ri.applyMask(s,l),si(l,n,s),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:s,segments:r}}Dl.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let s=ti.M,r,i;return typeof n<"u"&&(s=ti.from(n.errorCorrectionLevel,ti.M),r=gs.from(n.version),i=ri.from(n.maskPattern),n.toSJISFunc&&ms.setToSJISFunction(n.toSJISFunc)),og(e,r,s,i)}});var ai=v((h0,Fl)=>{"use strict";var ag=require("util"),Bl=require("stream"),ue=Fl.exports=function(){Bl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ag.inherits(ue,Bl);ue.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};ue.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};ue.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};ue.prototype.destroySoon=ue.prototype.end;ue.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ue.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ue.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};ue.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let r=this._buffers[n++],i=Math.min(r.length,t.length-e);r.copy(s,e,0,i),e+=i,i!==r.length&&(this._buffers[--n]=r.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};ue.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ci=v(li=>{"use strict";var Le=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];li.getImagePasses=function(t,e){let n=[],s=t%8,r=e%8,i=(t-s)/8,o=(e-r)/8;for(let a=0;a<Le.length;a++){let l=Le[a],u=i*l.x.length,c=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<s;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<r;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};li.getInterlaceIterator=function(t){return function(e,n,s){let r=e%Le[s].x.length,i=(e-r)/Le[s].x.length*8+Le[s].x[r],o=n%Le[s].y.length,a=(n-o)/Le[s].y.length*8+Le[s].y[o];return i*4+a*t*4}}});var ui=v((m0,Ul)=>{"use strict";Ul.exports=function(e,n,s){let r=e+n-s,i=Math.abs(r-e),o=Math.abs(r-n),a=Math.abs(r-s);return i<=o&&i<=a?e:o<=a?n:s}});var di=v((y0,Wl)=>{"use strict";var lg=ci(),cg=ui();function Hl(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var Tt=Wl.exports=function(t,e){let n=t.width,s=t.height,r=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],r){let a=lg.getImagePasses(n,s);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Hl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Hl(n,i,o),height:s,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};Tt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Tt.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,r=s-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>r?e[i-s]:0;e[i]=o+a}};Tt.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let r=0;r<n;r++){let i=t[1+r],o=s?s[r]:0;e[r]=i+o}};Tt.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=Math.floor((u+l)/2);e[o]=a+c}};Tt.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,r=s-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>r?e[o-s]:0,c=o>r&&i?i[o-s]:0,d=cg(u,l,c);e[o]=a+d}};Tt.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],r=s.byteWidth;if(e===0)n=t.slice(1,r+1);else switch(n=Buffer.alloc(r),e){case 1:this._unFilterType1(t,n,r);break;case 2:this._unFilterType2(t,n,r);break;case 3:this._unFilterType3(t,n,r);break;case 4:this._unFilterType4(t,n,r);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var jl=v((v0,Gl)=>{"use strict";var ug=require("util"),ql=ai(),dg=di(),fg=Gl.exports=function(t){ql.call(this);let e=[],n=this;this._filter=new dg(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};ug.inherits(fg,ql)});var kt=v((S0,$l)=>{"use strict";$l.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 hi=v((_0,zl)=>{"use strict";var fi=[];(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;fi[t]=e}})();var pi=zl.exports=function(){this._crc=-1};pi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=fi[(this._crc^t[e])&255]^this._crc>>>8;return!0};pi.prototype.crc32=function(){return this._crc^-1};pi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=fi[(e^t[n])&255]^e>>>8;return e^-1}});var gi=v((b0,Vl)=>{"use strict";var q=kt(),pg=hi(),z=Vl.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[q.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[q.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[q.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[q.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[q.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[q.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(){}};z.prototype.start=function(){this.read(q.PNG_SIGNATURE.length,this._parseSignature.bind(this))};z.prototype._parseSignature=function(t){let e=q.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))};z.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let i=4;i<8;i++)s+=String.fromCharCode(t[i]);let r=!!(t[4]&32);if(!this._hasIHDR&&n!==q.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new pg,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!r){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};z.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};z.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};z.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))};z.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};z.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],r=t[9],i=t[10],o=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(r in q.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=r;let l=q.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(r&q.COLORTYPE_PALETTE),color:!!(r&q.COLORTYPE_COLOR),alpha:!!(r&q.COLORTYPE_ALPHA),bpp:l,colorType:r}),this._handleChunkEnd()};z.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};z.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()};z.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};z.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===q.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===q.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===q.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};z.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};z.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/q.GAMMA_DIVISION),this._handleChunkEnd()};z.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};z.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===q.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()};z.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};z.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var mi=v(Jl=>{"use strict";var Ql=ci(),hg=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let r=e[s];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],gg=[function(){},function(t,e,n,s){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function mg(t,e){let n=[],s=0;function r(){if(s===t.length)throw new Error("Ran out of data");let i=t[s];s++;let o,a,l,u,c,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[s],s++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:c=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,c);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,u=i>>3&1,c=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)r();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function yg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++)for(let c=0;c<o;c++){let d=n(c,u,l);hg[s](e,r,d,i),i+=s}return i}function vg(t,e,n,s,r,i){let o=t.width,a=t.height,l=t.index;for(let u=0;u<a;u++){for(let c=0;c<o;c++){let d=r.get(s),f=n(c,u,l);gg[s](e,d,f,i)}r.resetAfterLine()}}Jl.dataToBitMap=function(t,e){let n=e.width,s=e.height,r=e.depth,i=e.bpp,o=e.interlace,a;r!==8&&(a=mg(t,r));let l;r<=8?l=Buffer.alloc(n*s*4):l=new Uint16Array(n*s*4);let u=Math.pow(2,r)-1,c=0,d,f;if(o)d=Ql.getImagePasses(n,s),f=Ql.getInterlaceIterator(n,s);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:s}]}for(let p=0;p<d.length;p++)r===8?c=yg(d[p],l,f,i,t,c):vg(d[p],l,f,i,a,u);if(r===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var yi=v((I0,Yl)=>{"use strict";function Sg(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=r[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function _g(t,e,n,s,r){let i=0;for(let o=0;o<s;o++)for(let a=0;a<n;a++){let l=!1;if(r.length===1?r[0]===t[i]&&(l=!0):r[0]===t[i]&&r[1]===t[i+1]&&r[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function bg(t,e,n,s,r){let i=255,o=Math.pow(2,r)-1,a=0;for(let l=0;l<s;l++)for(let u=0;u<n;u++){for(let c=0;c<4;c++)e[a+c]=Math.floor(t[a+c]*i/o+.5);a+=4}}Yl.exports=function(t,e){let n=e.depth,s=e.width,r=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Sg(t,l,s,r,a):(o&&_g(t,l,s,r,o),n!==8&&(n===16&&(l=Buffer.alloc(s*r*4)),bg(t,l,s,r,n))),l}});var Zl=v((A0,Xl)=>{"use strict";var wg=require("util"),vi=require("zlib"),Kl=ai(),Ig=jl(),Ag=gi(),Tg=mi(),kg=yi(),ge=Xl.exports=function(t){Kl.call(this),this._parser=new Ag(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()};wg.inherits(ge,Kl);ge.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};ge.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=vi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(n,vi.Z_MIN_CHUNK);this._inflate=vi.createInflate({chunkSize:s});let r=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){r&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){r&&(a.length>r&&(a=a.slice(0,r)),r-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ig(this._bitmapInfo)};ge.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ge.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ge.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ge.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ge.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ge.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Tg.dataToBitMap(t,this._bitmapInfo);e=kg(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var tc=v((T0,ec)=>{"use strict";var ie=kt();ec.exports=function(t,e,n,s){let r=[ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let g=(function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&g)return t}let i=s.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ie.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let l=ie.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=s.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function p(){let g,m,h,y=o;switch(s.inputColorType){case ie.COLORTYPE_COLOR_ALPHA:y=i[c+3],g=i[c],m=i[c+1],h=i[c+2];break;case ie.COLORTYPE_COLOR:g=i[c],m=i[c+1],h=i[c+2];break;case ie.COLORTYPE_ALPHA:y=i[c+1],g=i[c],m=g,h=g;break;case ie.COLORTYPE_GRAYSCALE:g=i[c],m=g,h=g;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(r||(y/=o,g=Math.min(Math.max(Math.round((1-y)*f.red+y*g),0),o),m=Math.min(Math.max(Math.round((1-y)*f.green+y*m),0),o),h=Math.min(Math.max(Math.round((1-y)*f.blue+y*h),0),o))),{red:g,green:m,blue:h,alpha:y}}for(let g=0;g<n;g++)for(let m=0;m<e;m++){let h=p(i,c);switch(s.colorType){case ie.COLORTYPE_COLOR_ALPHA:case ie.COLORTYPE_COLOR:s.bitDepth===8?(u[d]=h.red,u[d+1]=h.green,u[d+2]=h.blue,r&&(u[d+3]=h.alpha)):(u.writeUInt16BE(h.red,d),u.writeUInt16BE(h.green,d+2),u.writeUInt16BE(h.blue,d+4),r&&u.writeUInt16BE(h.alpha,d+6));break;case ie.COLORTYPE_ALPHA:case ie.COLORTYPE_GRAYSCALE:{let y=(h.red+h.green+h.blue)/3;s.bitDepth===8?(u[d]=y,r&&(u[d+1]=h.alpha)):(u.writeUInt16BE(y,d),r&&u.writeUInt16BE(h.alpha,d+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}c+=a,d+=l}return u}});var rc=v((k0,sc)=>{"use strict";var nc=ui();function Cg(t,e,n,s,r){for(let i=0;i<n;i++)s[r+i]=t[e+i]}function xg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++)s+=Math.abs(t[i]);return s}function Rg(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;s[r+o]=l}}function Eg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=t[e+i]-o;r+=Math.abs(a)}return r}function Pg(t,e,n,s,r){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;s[r+i]=a}}function Mg(t,e,n){let s=0,r=e+n;for(let i=e;i<r;i++){let o=e>0?t[i-n]:0,a=t[i]-o;s+=Math.abs(a)}return s}function Lg(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=t[e+o]-(a+l>>1);s[r+o]=u}}function Ng(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);r+=Math.abs(l)}return r}function Og(t,e,n,s,r,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-nc(a,l,u);s[r+o]=c}}function Dg(t,e,n,s){let r=0;for(let i=0;i<n;i++){let o=i>=s?t[e+i-s]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=s?t[e+i-(n+s)]:0,u=t[e+i]-nc(o,a,l);r+=Math.abs(u)}return r}var Bg={0:Cg,1:Rg,2:Pg,3:Lg,4:Og},Fg={0:xg,1:Eg,2:Mg,3:Ng,4:Dg};sc.exports=function(t,e,n,s,r){let i;if(!("filterType"in s)||s.filterType===-1)i=[0,1,2,3,4];else if(typeof s.filterType=="number")i=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(r*=2);let o=e*r,a=0,l=0,u=Buffer.alloc((o+1)*n),c=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let g=Fg[i[p]](t,l,o,r);g<f&&(c=i[p],f=g)}}u[a]=c,a++,Bg[c](t,l,o,u,a,r),a+=o,l+=o}return u}});var Si=v((C0,ic)=>{"use strict";var V=kt(),Ug=hi(),Hg=tc(),Wg=rc(),qg=require("zlib"),Ne=ic.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||qg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:V.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:V.COLORTYPE_COLOR_ALPHA,[V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([V.COLORTYPE_GRAYSCALE,V.COLORTYPE_COLOR,V.COLORTYPE_COLOR_ALPHA,V.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Ne.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ne.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ne.prototype.filterData=function(t,e,n){let s=Hg(t,e,n,this._options),r=V.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Wg(s,e,n,this._options,r)};Ne.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(Ug.crc32(s.slice(4,s.length-4)),s.length-4),s};Ne.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*V.GAMMA_DIVISION),0),this._packChunk(V.TYPE_gAMA,e)};Ne.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(V.TYPE_IHDR,n)};Ne.prototype.packIDAT=function(t){return this._packChunk(V.TYPE_IDAT,t)};Ne.prototype.packIEND=function(){return this._packChunk(V.TYPE_IEND,null)}});var cc=v((x0,lc)=>{"use strict";var Gg=require("util"),oc=require("stream"),jg=kt(),$g=Si(),ac=lc.exports=function(t){oc.call(this);let e=t||{};this._packer=new $g(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Gg.inherits(ac,oc);ac.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(jg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let r=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(r)}});var gc=v((fn,hc)=>{"use strict";var uc=require("assert").ok,Ct=require("zlib"),zg=require("util"),dc=require("buffer").kMaxLength;function Ke(t){if(!(this instanceof Ke))return new Ke(t);t&&t.chunkSize<Ct.Z_MIN_CHUNK&&(t.chunkSize=Ct.Z_MIN_CHUNK),Ct.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Vg(t){return new Ke(t)}function fc(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ke.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ct.Inflate._processChunk.call(this,t,e,n);let s=this,r=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(g){c=g});function d(g,m){if(s._hadError)return;let h=i-m;if(uc(h>=0,"have should not go down"),h>0){let y=s._buffer.slice(s._offset,s._offset+h);if(s._offset+=h,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(m===0||s._offset>=s._chunkSize)&&(i=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),m===0?(a+=r-g,r=g,!0):!1}uc(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,r,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=dc)throw fc(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+dc.toString(16)+" bytes");let p=Buffer.concat(l,u);return fc(this),p};zg.inherits(Ke,Ct.Inflate);function Qg(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Ct.Z_FINISH),t._processChunk(e,n)}function pc(t,e){return Qg(new Ke(e),t)}hc.exports=fn=pc;fn.Inflate=Ke;fn.createInflate=Vg;fn.inflateSync=pc});var _i=v((R0,yc)=>{"use strict";var mc=yc.exports=function(t){this._buffer=t,this._reads=[]};mc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};mc.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 Sc=v(vc=>{"use strict";var Jg=_i(),Yg=di();vc.process=function(t,e){let n=[],s=new Jg(t);return new Yg(e,{read:s.read.bind(s),write:function(i){n.push(i)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var Ic=v((P0,wc)=>{"use strict";var _c=!0,bc=require("zlib"),Kg=gc();bc.deflateSync||(_c=!1);var Xg=_i(),Zg=Sc(),em=gi(),tm=mi(),nm=yi();wc.exports=function(t,e){if(!_c)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function s(k){n=k}let r;function i(k){r=k}function o(k){r.transColor=k}function a(k){r.palette=k}function l(){r.alpha=!0}let u;function c(k){u=k}let d=[];function f(k){d.push(k)}let p=new Xg(t);if(new em(e,{read:p.read.bind(p),error:s,metadata:i,gamma:c,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let m=Buffer.concat(d);d.length=0;let h;if(r.interlace)h=bc.inflateSync(m);else{let A=((r.width*r.bpp*r.depth+7>>3)+1)*r.height;h=Kg(m,{chunkSize:A,maxLength:A})}if(m=null,!h||!h.length)throw new Error("bad png - invalid inflate data response");let y=Zg.process(h,r);m=null;let T=tm.dataToBitMap(y,r);y=null;let I=nm(T,r);return r.data=I,r.gamma=u||0,r}});var Cc=v((M0,kc)=>{"use strict";var Ac=!0,Tc=require("zlib");Tc.deflateSync||(Ac=!1);var sm=kt(),rm=Si();kc.exports=function(t,e){if(!Ac)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},s=new rm(n),r=[];r.push(Buffer.from(sm.PNG_SIGNATURE)),r.push(s.packIHDR(t.width,t.height)),t.gamma&&r.push(s.packGAMA(t.gamma));let i=s.filterData(t.data,t.width,t.height),o=Tc.deflateSync(i,s.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return r.push(s.packIDAT(o)),r.push(s.packIEND()),Buffer.concat(r)}});var xc=v(bi=>{"use strict";var im=Ic(),om=Cc();bi.read=function(t,e){return im(t,e||{})};bi.write=function(t,e){return om(t,e)}});var Pc=v(Ec=>{"use strict";var am=require("util"),Rc=require("stream"),lm=Zl(),cm=cc(),um=xc(),J=Ec.PNG=function(t){Rc.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 lm(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 cm(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"))};am.inherits(J,Rc);J.sync=um;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,s;n=function(r){this.removeListener("error",s),this.data=r,e(null,this)}.bind(this),s=function(r){this.removeListener("parsed",n),e(r,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};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,s,r,i,o,a){if(n|=0,s|=0,r|=0,i|=0,o|=0,a|=0,n>t.width||s>t.height||n+r>t.width||s+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+r>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(s+l)*t.width+n<<2,(s+l)*t.width+n+r<<2)};J.prototype.bitblt=function(t,e,n,s,r,i,o){return J.bitblt(this,t,e,n,s,r,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 s=t.width*e+n<<2;for(let r=0;r<3;r++){let i=t.data[s+r]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[s+r]=Math.round(i*255)}}t.gamma=0}};J.prototype.adjustGamma=function(){J.adjustGamma(this)}});var pn=v(Xe=>{function Mc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(s){return[s,s]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Xe.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,r=e.scale||4;return{width:s,scale:s?4:r,margin:n,color:{dark:Mc(e.color.dark||"#000000ff"),light:Mc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Xe.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Xe.getImageWidth=function(e,n){let s=Xe.getScale(e,n);return Math.floor((e+n.margin*2)*s)};Xe.qrToImageData=function(e,n,s){let r=n.modules.size,i=n.modules.data,o=Xe.getScale(r,s),a=Math.floor((r+s.margin*2)*o),l=s.margin*o,u=[s.color.light,s.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let f=(c*a+d)*4,p=s.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let g=Math.floor((c-l)/o),m=Math.floor((d-l)/o);p=u[i[g*r+m]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var Lc=v(me=>{var dm=require("fs"),fm=Pc().PNG,wi=pn();me.render=function(e,n){let s=wi.getOptions(n),r=s.rendererOpts,i=wi.getImageWidth(e.modules.size,s);r.width=i,r.height=i;let o=new fm(r);return wi.qrToImageData(o.data,e,s),o};me.renderToDataURL=function(e,n,s){typeof s>"u"&&(s=n,n=void 0),me.renderToBuffer(e,n,function(r,i){r&&s(r);let o="data:image/png;base64,";o+=i.toString("base64"),s(null,o)})};me.renderToBuffer=function(e,n,s){typeof s>"u"&&(s=n,n=void 0);let r=me.render(e,n),i=[];r.on("error",s),r.on("data",function(o){i.push(o)}),r.on("end",function(){s(null,Buffer.concat(i))}),r.pack()};me.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=!1,o=(...l)=>{i||(i=!0,r.apply(null,l))},a=dm.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,s)};me.renderToFileStream=function(e,n,s){me.render(n,s).pack().pipe(e)}});var Nc=v(ys=>{var pm=pn(),hm={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},gm={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function mm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}ys.render=function(t,e,n){let s=pm.getOptions(e),r=hm;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(r=gm);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+s.margin*2+1).join(r.WW);l=Array(s.margin/2+1).join(l+`
14
+ `);let u=Array(s.margin+1).join(r.WW);a+=l;for(let c=0;c<i;c+=2){a+=u;for(let d=0;d<i;d++){let f=o[c*i+d],p=o[(c+1)*i+d];a+=mm(f,p,r)}a+=u+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};ys.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),o=ys.render(n,s);i.writeFile(e,o,r)}});var Dc=v(Oc=>{Oc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(s+3).join(o),u=Array(2).join(o);a+=l+`
16
16
  `;for(let c=0;c<s;++c){a+=o;for(let d=0;d<s;d++)a+=r[c*s+d]?i:o;a+=u+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var Bc=v(Dc=>{var mm="\x1B[47m",ym="\x1B[40m",bi="\x1B[37m",wi="\x1B[30m",Ze="\x1B[0m",vm=mm+wi,Sm=ym+bi,_m=function(t,e,n){return{"00":Ze+" "+t,"01":Ze+e+"\u2584"+t,"02":Ze+n+"\u2584"+t,10:Ze+e+"\u2580"+t,11:" ",12:"\u2584",20:Ze+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Nc=function(t,e,n,s){let r=e+1;if(n>=r||s>=r||s<-1||n<-1)return"0";if(n>=e||s>=e||s<0||n<0)return"1";let i=s*e+n;return t[i]?"2":"1"},Oc=function(t,e,n,s){return Nc(t,e,n,s)+Nc(t,e,n,s+1)};Dc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Sm:vm,u=_m(o,i?wi:bi,i?bi:wi),c=Ze+`
19
- `+o,d=o;for(let f=-1;f<s+1;f+=2){for(let h=-1;h<s;h++)d+=u[Oc(r,s,h,f)];d+=u[Oc(r,s,s,f)]+c}return d+=Ze,typeof n=="function"&&n(null,d),d}});var Uc=v(Fc=>{var bm=Lc(),wm=Bc();Fc.render=function(t,e,n){return e&&e.small?wm.render(t,e,n):bm.render(t,e,n)}});var Ai=v(Wc=>{var Im=pn();function Hc(t,e){let n=t.a/255,s=e+'="'+t.hex+'"';return n<1?s+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':s}function Ii(t,e,n){let s=t+e;return typeof n<"u"&&(s+=" "+n),s}function Am(t,e,n){let s="",r=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(s+=i?Ii("M",l+n,.5+u+n):Ii("m",r,0),r=0,i=!1),l+1<e&&t[a+1]||(s+=Ii("h",o),o=0)):r++}return s}Wc.render=function(e,n,s){let r=Im.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+r.margin*2,l=r.color.light.a?"<path "+Hc(r.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+Hc(r.color.dark,"stroke")+' d="'+Am(o,i,r.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(r.width?'width="'+r.width+'" height="'+r.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
- `;return typeof s=="function"&&s(null,f),f}});var qc=v(vs=>{var Tm=Ai();vs.render=Tm.render;vs.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+vs.render(n,s);i.writeFile(e,a,r)}});var Gc=v(Ss=>{var Ti=pn();function Cm(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 km(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ss.render=function(e,n,s){let r=s,i=n;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),n||(i=km()),r=Ti.getOptions(r);let o=Ti.getImageWidth(e.modules.size,r),a=i.getContext("2d"),l=a.createImageData(o,o);return Ti.qrToImageData(l.data,e,r),Cm(a,i,o),a.putImageData(l,0,0),i};Ss.renderToDataURL=function(e,n,s){let r=s;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),r||(r={});let i=Ss.render(e,n,r),o=r.type||"image/png",a=r.rendererOpts||{};return i.toDataURL(o,a.quality)}});var $c=v(hn=>{var xm=Ur(),Ci=ri(),jc=Gc(),Rm=Ai();function ki(t,e,n,s,r){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!xm())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(r=n,n=e,e=s=void 0):o===3&&(e.getContext&&typeof r>"u"?(r=s,s=void 0):(r=s,s=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=s=void 0):o===2&&!e.getContext&&(s=n,n=e,e=void 0),new Promise(function(l,u){try{let c=Ci.create(n,s);l(t(c,e,s))}catch(c){u(c)}})}try{let l=Ci.create(n,s);r(null,t(l,e,s))}catch(l){r(l)}}hn.create=Ci.create;hn.toCanvas=ki.bind(null,jc.render);hn.toDataURL=ki.bind(null,jc.renderToDataURL);hn.toString=ki.bind(null,function(t,e,n){return Rm.render(t,n)})});var Jc=v(Oe=>{var zc=Ur(),xi=ri(),Em=Ec(),Vc=Pc(),Pm=Uc(),Qc=qc();function gn(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(zc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Mm(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function _s(t){switch(t){case"svg":return Qc;case"txt":case"utf8":return Vc;case"png":case"image/png":default:return Em}}function Lm(t){switch(t){case"svg":return Qc;case"terminal":return Pm;case"utf8":default:return Vc}}function mn(t,e,n){if(!n.cb)return new Promise(function(s,r){try{let i=xi.create(e,n.opts);return t(i,n.opts,function(o,a){return o?r(o):s(a)})}catch(i){r(i)}});try{let s=xi.create(e,n.opts);return t(s,n.opts,n.cb)}catch(s){n.cb(s)}}Oe.create=xi.create;Oe.toCanvas=$c().toCanvas;Oe.toString=function(e,n,s){let r=gn(e,n,s),i=r.opts?r.opts.type:void 0,o=Lm(i);return mn(o.render,e,r)};Oe.toDataURL=function(e,n,s){let r=gn(e,n,s),i=_s(r.opts.type);return mn(i.renderToDataURL,e,r)};Oe.toBuffer=function(e,n,s){let r=gn(e,n,s),i=_s(r.opts.type);return mn(i.renderToBuffer,e,r)};Oe.toFile=function(e,n,s,r){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!zc())throw new Error("Too few arguments provided");let i=gn(n,s,r),o=i.opts.type||Mm(e),l=_s(o).renderToFile.bind(null,e);return mn(l,n,i)};Oe.toFileStream=function(e,n,s){if(arguments.length<2)throw new Error("Too few arguments provided");let r=gn(n,s,e.emit.bind(e,"error")),o=_s("png").renderToFileStream.bind(null,e);mn(o,n,r)}});var Kc=v(($0,Yc)=>{Yc.exports=Jc()});var Bf=require("http");var gh=ft(La(),1),mh=ft(kr(),1),yh=ft(Er(),1),vh=ft(is(),1),Fr=ft(qa(),1);var Ff=require("child_process"),qe=require("fs"),le=require("fs/promises"),Uf=require("crypto"),Jt=require("path"),Hf=require("os"),Do=ft(Kc(),1);var et=require("child_process"),Et=require("fs"),P=require("path"),bn=require("os");var Ts=require("fs");var Xc=require("os"),Q=require("path"),Ie=(0,Q.join)((0,Xc.homedir)(),".vibelet"),xt=(0,Q.join)(Ie,"logs"),bs=(0,Q.join)(Ie,"data"),Nm=(0,Q.join)(Ie,"runtime"),z0=(0,Q.join)(Nm,"current"),Zc=(0,Q.join)(Ie,"identity.json"),eu=(0,Q.join)(Ie,"pairings.json"),tu=(0,Q.join)(bs,"push-subscriptions.json"),ws=(0,Q.join)(bs,"sessions.json"),De=(0,Q.join)(bs,"audit.jsonl"),Ri=(0,Q.join)(bs,"uploads"),yn=(0,Q.join)(xt,"daemon.stdout.log"),vn=(0,Q.join)(xt,"daemon.stderr.log"),nu=(0,Q.join)(Ie,"update-check.json"),Ei=(0,Q.join)(Ie,"pairing-qr.png");var Is={stdout:!1,stderr:!1};function su(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Om(t){return!t.destroyed&&t.writable!==!1}function ru(t,e){if(Is[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Om(n))return Is[t]=!0,!1;try{return n.write(e,s=>{su(s)&&(Is[t]=!0)}),!0}catch(s){return su(s)&&(Is[t]=!0),!1}}function Rt(t){return ru("stdout",t)}function As(t){return ru("stderr",t)}var iu={debug:10,info:20,warn:30,error:40},Dm=process.env.VIBE_LOG_LEVEL||"info";function Bm(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Fm(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var au=!Bm()&&!Fm();if(au)try{(0,Ts.mkdirSync)(xt,{recursive:!0})}catch{}function ou(t,e,n){if(iu[t]<iu[Dm])return;let s={level:t,ts:new Date().toISOString(),msg:n,...e},r=JSON.stringify(s);if(t==="error"||t==="warn"?As(r+`
18
+ `,typeof n=="function"&&n(null,a),a}});var Hc=v(Uc=>{var ym="\x1B[47m",vm="\x1B[40m",Ii="\x1B[37m",Ai="\x1B[30m",Ze="\x1B[0m",Sm=ym+Ai,_m=vm+Ii,bm=function(t,e,n){return{"00":Ze+" "+t,"01":Ze+e+"\u2584"+t,"02":Ze+n+"\u2584"+t,10:Ze+e+"\u2580"+t,11:" ",12:"\u2584",20:Ze+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Bc=function(t,e,n,s){let r=e+1;if(n>=r||s>=r||s<-1||n<-1)return"0";if(n>=e||s>=e||s<0||n<0)return"1";let i=s*e+n;return t[i]?"2":"1"},Fc=function(t,e,n,s){return Bc(t,e,n,s)+Bc(t,e,n,s+1)};Uc.render=function(t,e,n){let s=t.modules.size,r=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?_m:Sm,u=bm(o,i?Ai:Ii,i?Ii:Ai),c=Ze+`
19
+ `+o,d=o;for(let f=-1;f<s+1;f+=2){for(let p=-1;p<s;p++)d+=u[Fc(r,s,p,f)];d+=u[Fc(r,s,s,f)]+c}return d+=Ze,typeof n=="function"&&n(null,d),d}});var qc=v(Wc=>{var wm=Dc(),Im=Hc();Wc.render=function(t,e,n){return e&&e.small?Im.render(t,e,n):wm.render(t,e,n)}});var ki=v(jc=>{var Am=pn();function Gc(t,e){let n=t.a/255,s=e+'="'+t.hex+'"';return n<1?s+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':s}function Ti(t,e,n){let s=t+e;return typeof n<"u"&&(s+=" "+n),s}function Tm(t,e,n){let s="",r=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(s+=i?Ti("M",l+n,.5+u+n):Ti("m",r,0),r=0,i=!1),l+1<e&&t[a+1]||(s+=Ti("h",o),o=0)):r++}return s}jc.render=function(e,n,s){let r=Am.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+r.margin*2,l=r.color.light.a?"<path "+Gc(r.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+Gc(r.color.dark,"stroke")+' d="'+Tm(o,i,r.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(r.width?'width="'+r.width+'" height="'+r.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
+ `;return typeof s=="function"&&s(null,f),f}});var $c=v(vs=>{var km=ki();vs.render=km.render;vs.renderToFile=function(e,n,s,r){typeof r>"u"&&(r=s,s=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+vs.render(n,s);i.writeFile(e,a,r)}});var zc=v(Ss=>{var Ci=pn();function Cm(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 xm(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ss.render=function(e,n,s){let r=s,i=n;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),n||(i=xm()),r=Ci.getOptions(r);let o=Ci.getImageWidth(e.modules.size,r),a=i.getContext("2d"),l=a.createImageData(o,o);return Ci.qrToImageData(l.data,e,r),Cm(a,i,o),a.putImageData(l,0,0),i};Ss.renderToDataURL=function(e,n,s){let r=s;typeof r>"u"&&(!n||!n.getContext)&&(r=n,n=void 0),r||(r={});let i=Ss.render(e,n,r),o=r.type||"image/png",a=r.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Qc=v(hn=>{var Rm=Wr(),xi=oi(),Vc=zc(),Em=ki();function Ri(t,e,n,s,r){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Rm())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(r=n,n=e,e=s=void 0):o===3&&(e.getContext&&typeof r>"u"?(r=s,s=void 0):(r=s,s=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=s=void 0):o===2&&!e.getContext&&(s=n,n=e,e=void 0),new Promise(function(l,u){try{let c=xi.create(n,s);l(t(c,e,s))}catch(c){u(c)}})}try{let l=xi.create(n,s);r(null,t(l,e,s))}catch(l){r(l)}}hn.create=xi.create;hn.toCanvas=Ri.bind(null,Vc.render);hn.toDataURL=Ri.bind(null,Vc.renderToDataURL);hn.toString=Ri.bind(null,function(t,e,n){return Em.render(t,n)})});var Xc=v(Oe=>{var Jc=Wr(),Ei=oi(),Pm=Lc(),Yc=Nc(),Mm=qc(),Kc=$c();function gn(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(Jc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Lm(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function _s(t){switch(t){case"svg":return Kc;case"txt":case"utf8":return Yc;case"png":case"image/png":default:return Pm}}function Nm(t){switch(t){case"svg":return Kc;case"terminal":return Mm;case"utf8":default:return Yc}}function mn(t,e,n){if(!n.cb)return new Promise(function(s,r){try{let i=Ei.create(e,n.opts);return t(i,n.opts,function(o,a){return o?r(o):s(a)})}catch(i){r(i)}});try{let s=Ei.create(e,n.opts);return t(s,n.opts,n.cb)}catch(s){n.cb(s)}}Oe.create=Ei.create;Oe.toCanvas=Qc().toCanvas;Oe.toString=function(e,n,s){let r=gn(e,n,s),i=r.opts?r.opts.type:void 0,o=Nm(i);return mn(o.render,e,r)};Oe.toDataURL=function(e,n,s){let r=gn(e,n,s),i=_s(r.opts.type);return mn(i.renderToDataURL,e,r)};Oe.toBuffer=function(e,n,s){let r=gn(e,n,s),i=_s(r.opts.type);return mn(i.renderToBuffer,e,r)};Oe.toFile=function(e,n,s,r){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Jc())throw new Error("Too few arguments provided");let i=gn(n,s,r),o=i.opts.type||Lm(e),l=_s(o).renderToFile.bind(null,e);return mn(l,n,i)};Oe.toFileStream=function(e,n,s){if(arguments.length<2)throw new Error("Too few arguments provided");let r=gn(n,s,e.emit.bind(e,"error")),o=_s("png").renderToFileStream.bind(null,e);mn(o,n,r)}});var eu=v((z0,Zc)=>{Zc.exports=Xc()});var Ff=require("http");var mh=ft(Da(),1),yh=ft(Rr(),1),vh=ft(Mr(),1),Sh=ft(is(),1),Hr=ft($a(),1);var Uf=require("child_process"),qe=require("fs"),le=require("fs/promises"),Hf=require("crypto"),Jt=require("path"),Wf=require("os"),Fo=ft(eu(),1);var et=require("child_process"),Et=require("fs"),P=require("path"),bn=require("os");var Ts=require("fs");var tu=require("os"),Q=require("path"),Ie=(0,Q.join)((0,tu.homedir)(),".vibelet"),xt=(0,Q.join)(Ie,"logs"),bs=(0,Q.join)(Ie,"data"),Om=(0,Q.join)(Ie,"runtime"),V0=(0,Q.join)(Om,"current"),nu=(0,Q.join)(Ie,"identity.json"),su=(0,Q.join)(Ie,"pairings.json"),ru=(0,Q.join)(bs,"push-subscriptions.json"),ws=(0,Q.join)(bs,"sessions.json"),De=(0,Q.join)(bs,"audit.jsonl"),Pi=(0,Q.join)(bs,"uploads"),yn=(0,Q.join)(xt,"daemon.stdout.log"),vn=(0,Q.join)(xt,"daemon.stderr.log"),iu=(0,Q.join)(Ie,"update-check.json"),Mi=(0,Q.join)(Ie,"pairing-qr.png");var Is={stdout:!1,stderr:!1};function ou(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Dm(t){return!t.destroyed&&t.writable!==!1}function au(t,e){if(Is[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Dm(n))return Is[t]=!0,!1;try{return n.write(e,s=>{ou(s)&&(Is[t]=!0)}),!0}catch(s){return ou(s)&&(Is[t]=!0),!1}}function Rt(t){return au("stdout",t)}function As(t){return au("stderr",t)}var lu={debug:10,info:20,warn:30,error:40},Bm=process.env.VIBE_LOG_LEVEL||"info";function Fm(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Um(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var uu=!Fm()&&!Um();if(uu)try{(0,Ts.mkdirSync)(xt,{recursive:!0})}catch{}function cu(t,e,n){if(lu[t]<lu[Bm])return;let s={level:t,ts:new Date().toISOString(),msg:n,...e},r=JSON.stringify(s);if(t==="error"||t==="warn"?As(r+`
21
21
  `):Rt(r+`
22
- `),au){let i=t==="error"||t==="warn"?vn:yn;try{(0,Ts.appendFileSync)(i,r+`
23
- `)}catch{}}}function lu(t={}){function e(n,s,r){typeof s=="string"?ou(n,t,s):ou(n,{...t,...s},r)}return{debug:(n,s)=>e("debug",n,s),info:(n,s)=>e("info",n,s),warn:(n,s)=>e("warn",n,s),error:(n,s)=>e("error",n,s),child:n=>lu({...t,...n})}}var L=lu({module:"daemon"});var Um=["fnm_multishells"],Hm=6e4,Be=process.platform==="win32",Wm=300*1e3,qm=900*1e3,Gm=L.child({module:"config"});function oe(t){return Um.some(e=>t.includes(e))}function jm(t){if(!t||!oe(t))return t;try{let e=(0,P.join)((0,Et.realpathSync)((0,P.dirname)(t)),(0,P.basename)(t));if((0,Et.existsSync)(e)&&!oe(e))return e}catch{}return t}function $m(t){if(!t||!oe(t))return t;try{let e=(0,Et.realpathSync)(t);if(e&&!oe(e))return e}catch{}return t}function Mi(){return Be?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var Sn=null;function du(){if(Sn&&Sn.PATH&&!oe(Sn.PATH))return Sn;for(let t of Mi())try{let e=(0,et.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let s of e.split(`
24
- `)){let r=s.indexOf("=");r>0&&(n[s.slice(0,r)]=s.slice(r+1))}return n.PATH&&!oe(n.PATH)&&(Sn=n),n}catch{}return{}}function zm(t=du()){let e=(0,bn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Be?(0,P.join)(e,"pnpm"):(0,P.join)(e,"Library","pnpm")),s=t.PATH||process.env.PATH||"",r=Be?[(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n,(0,P.join)(e,"AppData","Roaming","npm"),(0,P.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n],i=s.split(P.delimiter).filter(Boolean).map($m),o=new Set(i);for(let a of r)o.has(a)||(i.push(a),o.add(a));return i.join(P.delimiter)}function Pi(t,e){let n=process.env[t];if(!n)return e;let s=Number(n);return Number.isFinite(s)&&s>0?Math.floor(s):e}function Cs(t,e){let n=process.env[t];if(n==null||n==="")return e;let s=Number(n);return Number.isFinite(s)&&s>=0?Math.floor(s):e}function tt(){let t=du(),e={};for(let[n,s]of Object.entries(process.env))typeof s=="string"&&(e[n]=s);for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e.PATH=zm(t),e.HOME||(e.HOME=(0,bn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Li(t){if(Be)try{let n=(0,et.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(r=>r.endsWith(".exe"))??n[0]}catch{return}}function _n(t,e=3e3){try{return(0,et.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:tt(),...Be?{shell:!0}:{}}).trim()||null}catch{return null}}function Vm(t){for(let e of Mi())try{let n=(0,et.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Qm(){let t=(0,bn.homedir)();return[(0,P.join)(t,".local","bin","claude"),(0,P.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,P.join)(t,".npm-global","bin","claude")]}function Jm(){if(Be){let t=Li("claude");return t&&_n(t)?t:void 0}for(let t of Qm())if(_n(t))return t;try{let t=(0,et.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:tt()}).trim();if(t&&!t.includes("cmux")&&_n(t))return t}catch{}}function Ym(){let t=(0,bn.homedir)(),e=[process.env.PNPM_HOME,(0,P.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,P.join)(t,".npm-global","bin","codex"),(0,P.join)(t,".local","bin","codex"),...e.map(n=>(0,P.join)(n,"codex"))]}function Km(){if(Be){let r=Li("codex");return r&&_n(r)?r:void 0}let t=r=>{let i=jm(r);return _n(i)?i:void 0},e;for(let r of Ym()){let i=t(r);if(i){if(!oe(i))return i;e=i}}try{let r=(0,et.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:tt()}).trim(),i=r?t(r):void 0;if(i){if(!oe(i))return i;e=e??i}}catch{}let n=Vm("codex"),s=n?t(n):void 0;if(s){if(!oe(s))return s;e=e??s}return e}function fu(t,e){let n=null,s=0;return()=>{let r=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[r])return process.env[r];let i=Date.now();if(!n||i-s>Hm||!(0,Et.existsSync)(n)||oe(n)){let o=t();n=o??e,s=i,Gm.info({name:e,path:n,transient:oe(n),isBare:o==null},"binary resolved")}return n}}var Xm=fu(Jm,"claude"),Zm=fu(Km,"codex");function ey(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--")&&n+1<e.length){let r=s.slice(2);t[r]=e[++n]}}return t}var cu=ey(),ks=Cs("VIBE_TURN_STALL_TIMEOUT_MS",Wm),uu=Cs("VIBE_TURN_STALL_HARD_TIMEOUT_MS",Math.max(qm,ks*3)),ty=ks<=0||uu===0?0:Math.max(uu,ks);function ny(t,e){if(Be)return{command:Li(t)??t,args:e};let n=Mi()[0]??"/bin/zsh",s=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",s,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:cu.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:cu["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Cs("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:ks,turnStallHardTimeoutMs:ty,auditMaxBytes:Pi("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Pi("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Pi("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Cs("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",reviewMock:process.env.VIBE_REVIEW_MOCK==="1",get claudePath(){return Xm()},get codexPath(){return Zm()},isTransientPath:oe,execViaLoginShell:ny,buildSanitizedEnv:tt};var Ao=require("crypto"),ff=require("fs/promises");var ku=require("child_process"),Ms=require("fs");var xs=require("fs"),gu=require("path");var Y=require("fs");function sy(t,e,n,s){let r=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,r,s??i))}function wn(t,e){if(!(0,Y.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let s=(0,Y.statSync)(t).size,r=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||s+r<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:s,afterBytes:s,reclaimedBytes:0};let i=sy(s,e.maxBytes,r,e.retainBytes),o=(0,Y.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,Y.readSync)(o,l,0,i,s-i);let u=0;if(s>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,Y.ftruncateSync)(o,0),a.length>0&&(0,Y.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:s,afterBytes:a.length,reclaimedBytes:s-a.length}}finally{(0,Y.closeSync)(o)}}function pu(t){let e=[wn(t.auditPath,{maxBytes:t.auditMaxBytes}),wn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),wn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,s)=>n+s.reclaimedBytes,0)}}var hu=!1,ry=new Set(["ts","event","source","appEvent","level"]);function iy(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function oy(t={}){let e={};for(let[n,s]of Object.entries(t))ry.has(n)||(e[n]=s);return e}function ay(t,e,n={},s){return{ts:s??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...oy(n)}}function ly(){hu||((0,xs.mkdirSync)((0,gu.dirname)(De),{recursive:!0}),hu=!0)}var Ni=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,s={},r){this.write(ay(e,n,s,r))}write(e){if(!iy()){ly();try{let n=JSON.stringify(e)+`
25
- `;wn(De,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,xs.appendFileSync)(De,n)}catch{}}}},_=new Ni;var Fe=require("fs"),mu=require("os"),In=require("path"),yu=require("crypto"),Oi="claude-hook:",An="x-vibelet-claude-hook-secret",Tn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function cy(t,e){return`#!/usr/bin/env node
22
+ `),uu){let i=t==="error"||t==="warn"?vn:yn;try{(0,Ts.appendFileSync)(i,r+`
23
+ `)}catch{}}}function du(t={}){function e(n,s,r){typeof s=="string"?cu(n,t,s):cu(n,{...t,...s},r)}return{debug:(n,s)=>e("debug",n,s),info:(n,s)=>e("info",n,s),warn:(n,s)=>e("warn",n,s),error:(n,s)=>e("error",n,s),child:n=>du({...t,...n})}}var L=du({module:"daemon"});var Hm=["fnm_multishells"],Wm=6e4,Be=process.platform==="win32",qm=300*1e3,Gm=900*1e3,jm=L.child({module:"config"});function oe(t){return Hm.some(e=>t.includes(e))}function $m(t){if(!t||!oe(t))return t;try{let e=(0,P.join)((0,Et.realpathSync)((0,P.dirname)(t)),(0,P.basename)(t));if((0,Et.existsSync)(e)&&!oe(e))return e}catch{}return t}function zm(t){if(!t||!oe(t))return t;try{let e=(0,Et.realpathSync)(t);if(e&&!oe(e))return e}catch{}return t}function Ni(){return Be?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var Sn=null;function hu(){if(Sn&&Sn.PATH&&!oe(Sn.PATH))return Sn;for(let t of Ni())try{let e=(0,et.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let s of e.split(`
24
+ `)){let r=s.indexOf("=");r>0&&(n[s.slice(0,r)]=s.slice(r+1))}return n.PATH&&!oe(n.PATH)&&(Sn=n),n}catch{}return{}}function Vm(t=hu()){let e=(0,bn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Be?(0,P.join)(e,"pnpm"):(0,P.join)(e,"Library","pnpm")),s=t.PATH||process.env.PATH||"",r=Be?[(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n,(0,P.join)(e,"AppData","Roaming","npm"),(0,P.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,P.join)(e,".npm-global","bin"),(0,P.join)(e,".local","bin"),(0,P.join)(e,".claude","bin"),n],i=s.split(P.delimiter).filter(Boolean).map(zm),o=new Set(i);for(let a of r)o.has(a)||(i.push(a),o.add(a));return i.join(P.delimiter)}function Li(t,e){let n=process.env[t];if(!n)return e;let s=Number(n);return Number.isFinite(s)&&s>0?Math.floor(s):e}function ks(t,e){let n=process.env[t];if(n==null||n==="")return e;let s=Number(n);return Number.isFinite(s)&&s>=0?Math.floor(s):e}function tt(){let t=hu(),e={};for(let[n,s]of Object.entries(process.env))typeof s=="string"&&(e[n]=s);for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e.PATH=Vm(t),e.HOME||(e.HOME=(0,bn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Oi(t){if(Be)try{let n=(0,et.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(r=>r.endsWith(".exe"))??n[0]}catch{return}}function _n(t,e=3e3){try{return(0,et.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:tt(),...Be?{shell:!0}:{}}).trim()||null}catch{return null}}function Qm(t){for(let e of Ni())try{let n=(0,et.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Jm(){let t=(0,bn.homedir)();return[(0,P.join)(t,".local","bin","claude"),(0,P.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,P.join)(t,".npm-global","bin","claude")]}function Ym(){if(Be){let t=Oi("claude");return t&&_n(t)?t:void 0}for(let t of Jm())if(_n(t))return t;try{let t=(0,et.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:tt()}).trim();if(t&&!t.includes("cmux")&&_n(t))return t}catch{}}function Km(){let t=(0,bn.homedir)(),e=[process.env.PNPM_HOME,(0,P.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,P.join)(t,".npm-global","bin","codex"),(0,P.join)(t,".local","bin","codex"),...e.map(n=>(0,P.join)(n,"codex"))]}function Xm(){if(Be){let r=Oi("codex");return r&&_n(r)?r:void 0}let t=r=>{let i=$m(r);return _n(i)?i:void 0},e;for(let r of Km()){let i=t(r);if(i){if(!oe(i))return i;e=i}}try{let r=(0,et.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:tt()}).trim(),i=r?t(r):void 0;if(i){if(!oe(i))return i;e=e??i}}catch{}let n=Qm("codex"),s=n?t(n):void 0;if(s){if(!oe(s))return s;e=e??s}return e}function gu(t,e){let n=null,s=0;return()=>{let r=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[r])return process.env[r];let i=Date.now();if(!n||i-s>Wm||!(0,Et.existsSync)(n)||oe(n)){let o=t();n=o??e,s=i,jm.info({name:e,path:n,transient:oe(n),isBare:o==null},"binary resolved")}return n}}var Zm=gu(Ym,"claude"),ey=gu(Xm,"codex");function ty(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let s=e[n];if(s.startsWith("--")&&n+1<e.length){let r=s.slice(2);t[r]=e[++n]}}return t}var fu=ty(),Cs=ks("VIBE_TURN_STALL_TIMEOUT_MS",qm),pu=ks("VIBE_TURN_STALL_HARD_TIMEOUT_MS",Math.max(Gm,Cs*3)),ny=Cs<=0||pu===0?0:Math.max(pu,Cs);function sy(t,e){if(Be)return{command:Oi(t)??t,args:e};let n=Ni()[0]??"/bin/zsh",s=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",s,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:fu.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:fu["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:ks("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Cs,turnStallHardTimeoutMs:ny,auditMaxBytes:Li("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Li("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Li("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:ks("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",reviewMock:process.env.VIBE_REVIEW_MOCK==="1",get claudePath(){return Zm()},get codexPath(){return ey()},isTransientPath:oe,execViaLoginShell:sy,buildSanitizedEnv:tt};var ko=require("crypto"),pf=require("fs/promises");var Eu=require("child_process"),Ms=require("fs");var xs=require("fs"),vu=require("path");var Y=require("fs");function ry(t,e,n,s){let r=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,r,s??i))}function wn(t,e){if(!(0,Y.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let s=(0,Y.statSync)(t).size,r=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||s+r<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:s,afterBytes:s,reclaimedBytes:0};let i=ry(s,e.maxBytes,r,e.retainBytes),o=(0,Y.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,Y.readSync)(o,l,0,i,s-i);let u=0;if(s>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,Y.ftruncateSync)(o,0),a.length>0&&(0,Y.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:s,afterBytes:a.length,reclaimedBytes:s-a.length}}finally{(0,Y.closeSync)(o)}}function mu(t){let e=[wn(t.auditPath,{maxBytes:t.auditMaxBytes}),wn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),wn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,s)=>n+s.reclaimedBytes,0)}}var yu=!1,iy=new Set(["ts","event","source","appEvent","level"]);function oy(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function ay(t={}){let e={};for(let[n,s]of Object.entries(t))iy.has(n)||(e[n]=s);return e}function ly(t,e,n={},s){return{ts:s??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...ay(n)}}function cy(){yu||((0,xs.mkdirSync)((0,vu.dirname)(De),{recursive:!0}),yu=!0)}var Di=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,s={},r){this.write(ly(e,n,s,r))}write(e){if(!oy()){cy();try{let n=JSON.stringify(e)+`
25
+ `;wn(De,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,xs.appendFileSync)(De,n)}catch{}}}},_=new Di;var Fe=require("fs"),Su=require("os"),In=require("path"),_u=require("crypto"),Bi="claude-hook:",An="x-vibelet-claude-hook-secret",Tn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function uy(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 uy(t,e){return`#!/usr/bin/env node
46
+ `}function dy(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
48
  const fallback = ${JSON.stringify(JSON.stringify(Tn))};
49
49
  const chunks = [];
@@ -79,48 +79,48 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function vu(t,e){let n=(0,In.join)((0,mu.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,yu.randomUUID)()}`);(0,Fe.mkdirSync)(n,{recursive:!0});let s=(0,In.join)(n,"settings.json"),r=(0,In.join)(n,"session_hook_forwarder.cjs"),i=(0,In.join)(n,"permission_hook_forwarder.cjs");return(0,Fe.writeFileSync)(r,cy(t,e),"utf8"),(0,Fe.writeFileSync)(i,uy(t,e),"utf8"),(0,Fe.writeFileSync)(s,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(r)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:s,sessionScriptPath:r,permissionScriptPath:i}}function Rs(t){if(t)try{(0,Fe.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Su=require("os"),nt=require("path"),_u=require("fs/promises"),dy=new Set([".c",".cc",".cpp",".cs",".css",".dart",".elm",".ex",".exs",".fish",".go",".h",".hpp",".hrl",".java",".js",".jsx",".kt",".kts",".less",".lua",".m",".mm",".mjs",".php",".pl",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sql",".swift",".ts",".tsx",".vue",".xml",".yaml",".yml",".zsh"]),fy=5e3,bu="Generated file: ",wu=`Generated files:
83
- `;function Pt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Cn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Di(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s?.[1]&&(e=s[1]),e}function st(t,e){let n=Di(t);return n?n.startsWith("~/")?(0,nt.resolve)((0,Su.homedir)(),n.slice(2)):(0,nt.isAbsolute)(n)?n:e?(0,nt.resolve)(e,n):n:""}function py(t){return dy.has((0,nt.extname)(Di(t)).toLowerCase())}function Mt(t){let e=Di(t);return e?!py(e):!1}function Ae(t){let e=[...new Set(t.map(n=>st(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${bu}${e[0]}`:`${wu}${e.join(`
84
- `)}`}function Iu(t){return typeof t!="string"?!1:t.startsWith(bu)||t.startsWith(wu)}function hy(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),s=new Set;for(let r of n){let i=Pt(r[1]);if(!i)continue;let o=st(i,e);!o||!Mt(o)||s.add(o)}return[...s]}function gy(t){let e=Pt(t);return e?e.toLowerCase():""}function my(t,e){let n=Pt(t?.file_path)??Pt(t?.path);if(!n)return null;let s=st(n,e);return s&&Mt(s)?s:null}function Es(t,e,n){return gy(t)!=="write"?null:my(e,n)}function yy(t){let e=t.toLowerCase();return e.includes("updated successfully")||e.includes("updated. all occurrences were successfully replaced")||e.includes("all occurrences were successfully replaced")||e.includes("successfully replaced")}function vy(t){return/^\d+\t/m.test(t)}function Ps(t,e){let n=typeof e=="string"?e.trim():"";if(n&&yy(n))return!1;let s=Cn(t);if(s?.type==="update"||s?.type==="replace"||s&&(Object.hasOwn(s,"oldString")||Object.hasOwn(s,"structuredPatch")||Object.hasOwn(s,"originalFile")||Object.hasOwn(s,"replaceAll")))return!1;if(typeof Cn(s?.file)?.filePath=="string"||typeof s?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||vy(n))return!0}return!1}function Bi(t,e){let n=Cn(t);if(!n)return[];let s=new Set;if(n.type==="event_msg"){let r=Cn(n.payload);if(r?.type==="image_generation_end"){let i=Pt(r.saved_path);if(i){let o=st(i,e?.cwd);o&&Mt(o)&&s.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let r=Cn(n.payload);if(r?.type==="function_call"&&r.name==="apply_patch"){let i=Pt(r.arguments);if(i)for(let o of hy(i,e?.cwd))s.add(o)}}return[...s]}async function Au(t,e){let n=[...new Set(t.map(r=>st(r)).filter(Boolean))],s=[];for(let r of n)if(Mt(r))try{let i=await(0,_u.stat)(r);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+fy<e)continue;s.push(r)}catch{}return s}var ee=L.child({module:"claude"}),xu="claude-permission-denial:",Sy=/\u001B\[[0-?]*[ -/]*[@-~]/g;function _y(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Fi(t){_y()&&As(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
- `)}function by(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
86
- `):""}function wy(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Iy(t){if(typeof t=="string")return t;let e=by(t);return e||(wy(t)?"":JSON.stringify(t))}function Ay(t){return/requested permissions|haven't granted/i.test(t)}function Tu(t){return t.replace(Sy,"").replace(/\s+/g," ").trim()}function Ty(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Cy(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 ky(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Cu(t){let e=Tu(t.resultText??""),n=(t.stderrLines??[]).map(Tu).filter(Boolean).slice(-3),s=[e,...n].find(i=>!!i&&Cy(i));if(s)return ky(s);let r=[e,...n].find(i=>!!i&&!Ty(i));return r?t.exitCode!=null&&r!==e?`Claude exited with code ${t.exitCode}: ${r}`:r:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Ls(t){return t.startsWith(xu)}var kn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;toolCallContext=new Map;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,s){return this.cwd=e,this.approvalMode=s,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ee.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let s=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&s.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&s.push("--resume",this.sessionId),Rs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=vu(this.hookPort,this.hookSecret),s.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&s.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&s.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&s.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ee.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Fi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.toolCallContext.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=s;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",s);o=c.command,a=c.args}else o=i;this.proc=(0,ku.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}});let u=this.proc;u.on("error",c=>{if(this.proc!==u)return;let d=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Ms.existsSync)(this.cwd)&&(d=`Working directory does not exist: ${this.cwd}`),ee.error({sessionId:this.sessionId,error:d,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:d}),this.handler?.({type:"error",sessionId:this.sessionId,message:d})}),this.buffer="",u.stdout.on("data",c=>{if(this.proc!==u)return;this.buffer+=c.toString();let d=this.buffer.split(`
87
- `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{ee.warn({sessionId:this.sessionId,linePreview:f.slice(0,100)},"failed to parse stdout line")}}),u.stderr.on("data",c=>{if(this.proc!==u)return;let d=c.toString().trim();d&&(ee.debug({sessionId:this.sessionId,stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),u.on("exit",(c,d)=>{if(this.proc!==u){ee.debug({sessionId:this.sessionId,exitCode:c,signal:d},"stale proc exit ignored, current proc was replaced");return}ee.info({sessionId:this.sessionId,exitCode:c,signal:d},"process exited");let f=this.interrupted;this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),f&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ee.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Cu({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ee.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ee.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let s=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(s+`
88
- `),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Es(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ms.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Iy(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ms.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Ps(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&Ay(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Fi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Cu({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${xu}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Fi("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Mu=require("child_process"),Lu=require("fs");var Ui=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Ui;var Ru=require("node:fs"),Hi=require("node:path"),xy="@vibelet/cli";function Ry(t){try{let e=JSON.parse((0,Ru.readFileSync)(t,"utf8"));if(e.name===xy&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Ey(){return"1.2.7"}var Lt=Ey();var x=L.child({module:"codex"});function Py(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 My(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function F(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function M(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Wi(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ly=new Set(["aborted","interrupted","cancelled","canceled","failed"]);function Ny(t){let e=M(t);return e?e.toLowerCase():null}function Oy(t){try{let e=JSON.parse(t),n=F(F(e)?.error)?.message;if(typeof n=="string"&&n.trim())return n}catch{}return t}function Dy(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function qi(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function Gi(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Nu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Ou(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function By(t){if(!Array.isArray(t))return null;for(let e of t){let n=F(e);if(!n)continue;let s=M(n.id),r=Array.isArray(n.options)?n.options.map(l=>F(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Nu(l))??i[0],a=i.find(l=>Ou(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Fy(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>F(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>F(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(r=>Nu(r)),s=e.some(r=>Ou(r));return n&&s}function Eu(t){let e=Dy(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=M(t.server),s=M(t.tool)??M(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:F(t.arguments)??F(t.input)??{}}:null}return null}function Uy(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>F(o)?.kind==="create"))return null;let i=st(n,e);return Mt(i)?i:null}function Hy(t){if(!Array.isArray(t))return"";for(let e of t){let n=F(e);if(!n)continue;let s=M(n.question)??M(n.header);if(s)return s}return""}function Wy(t){let e=F(t);if(!e)return;let n=Wi(e.input_tokens??e.inputTokens)??0,s=Wi(e.output_tokens??e.outputTokens)??0,r=Wi(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function Pu(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 xn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=r,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Mu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Lu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),x.error({error:d,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
89
- `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{x.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(x.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let l=b.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Lt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=Pu(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let s=Pu(this.approvalMode,this.cwd||process.cwd());this.latestTurnUsage=void 0,this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:s.approvalPolicy,sandboxPolicy:s.sandboxPolicy,...n?{model:n}:{}}).then(r=>{x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let s=this.approvalRequests.get(e),r=s?.rpcId??Number(e);if(!Number.isFinite(r))return!1;let i;if(!s)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(s.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[s.questionId]:{answers:[n?s.approveLabel:s.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
90
- `),!0}restorePendingApproval(e){let n=My(e);n&&this.approvalRequests.set(e.requestId,n)}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let s=++this.rpcId,r=b.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(s,{resolve:a=>{r(),i(a)},reject:a=>{r(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(s),r(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:s,params:n})+`
91
- `),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),x.error({method:e,rpcId:s,threadId:this.threadId},"RPC timeout"),r(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
82
+ `}function bu(t,e){let n=(0,In.join)((0,Su.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,_u.randomUUID)()}`);(0,Fe.mkdirSync)(n,{recursive:!0});let s=(0,In.join)(n,"settings.json"),r=(0,In.join)(n,"session_hook_forwarder.cjs"),i=(0,In.join)(n,"permission_hook_forwarder.cjs");return(0,Fe.writeFileSync)(r,uy(t,e),"utf8"),(0,Fe.writeFileSync)(i,dy(t,e),"utf8"),(0,Fe.writeFileSync)(s,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(r)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:s,sessionScriptPath:r,permissionScriptPath:i}}function Rs(t){if(t)try{(0,Fe.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var wu=require("os"),nt=require("path"),Iu=require("fs/promises"),fy=new Set([".c",".cc",".cpp",".cs",".css",".dart",".elm",".ex",".exs",".fish",".go",".h",".hpp",".hrl",".java",".js",".jsx",".kt",".kts",".less",".lua",".m",".mm",".mjs",".php",".pl",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sql",".swift",".ts",".tsx",".vue",".xml",".yaml",".yml",".zsh"]),py=5e3,Au="Generated file: ",Tu=`Generated files:
83
+ `;function Pt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function kn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Fi(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s?.[1]&&(e=s[1]),e}function st(t,e){let n=Fi(t);return n?n.startsWith("~/")?(0,nt.resolve)((0,wu.homedir)(),n.slice(2)):(0,nt.isAbsolute)(n)?n:e?(0,nt.resolve)(e,n):n:""}function hy(t){return fy.has((0,nt.extname)(Fi(t)).toLowerCase())}function Mt(t){let e=Fi(t);return e?!hy(e):!1}function Ae(t){let e=[...new Set(t.map(n=>st(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${Au}${e[0]}`:`${Tu}${e.join(`
84
+ `)}`}function ku(t){return typeof t!="string"?!1:t.startsWith(Au)||t.startsWith(Tu)}function gy(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),s=new Set;for(let r of n){let i=Pt(r[1]);if(!i)continue;let o=st(i,e);!o||!Mt(o)||s.add(o)}return[...s]}function my(t){let e=Pt(t);return e?e.toLowerCase():""}function yy(t,e){let n=Pt(t?.file_path)??Pt(t?.path);if(!n)return null;let s=st(n,e);return s&&Mt(s)?s:null}function Es(t,e,n){return my(t)!=="write"?null:yy(e,n)}function vy(t){let e=t.toLowerCase();return e.includes("updated successfully")||e.includes("updated. all occurrences were successfully replaced")||e.includes("all occurrences were successfully replaced")||e.includes("successfully replaced")}function Sy(t){return/^\d+\t/m.test(t)}function Ps(t,e){let n=typeof e=="string"?e.trim():"";if(n&&vy(n))return!1;let s=kn(t);if(s?.type==="update"||s?.type==="replace"||s&&(Object.hasOwn(s,"oldString")||Object.hasOwn(s,"structuredPatch")||Object.hasOwn(s,"originalFile")||Object.hasOwn(s,"replaceAll")))return!1;if(typeof kn(s?.file)?.filePath=="string"||typeof s?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||Sy(n))return!0}return!1}function Ui(t,e){let n=kn(t);if(!n)return[];let s=new Set;if(n.type==="event_msg"){let r=kn(n.payload);if(r?.type==="image_generation_end"){let i=Pt(r.saved_path);if(i){let o=st(i,e?.cwd);o&&Mt(o)&&s.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let r=kn(n.payload);if(r?.type==="function_call"&&r.name==="apply_patch"){let i=Pt(r.arguments);if(i)for(let o of gy(i,e?.cwd))s.add(o)}}return[...s]}async function Cu(t,e){let n=[...new Set(t.map(r=>st(r)).filter(Boolean))],s=[];for(let r of n)if(Mt(r))try{let i=await(0,Iu.stat)(r);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+py<e)continue;s.push(r)}catch{}return s}var ee=L.child({module:"claude"}),Pu="claude-permission-denial:",_y=/\u001B\[[0-?]*[ -/]*[@-~]/g;function by(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Hi(t){by()&&As(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
+ `)}function wy(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
86
+ `):""}function Iy(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Ay(t){if(typeof t=="string")return t;let e=wy(t);return e||(Iy(t)?"":JSON.stringify(t))}function Ty(t){return/requested permissions|haven't granted/i.test(t)}function xu(t){return t.replace(_y,"").replace(/\s+/g," ").trim()}function ky(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Cy(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 xy(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Ru(t){let e=xu(t.resultText??""),n=(t.stderrLines??[]).map(xu).filter(Boolean).slice(-3),s=[e,...n].find(i=>!!i&&Cy(i));if(s)return xy(s);let r=[e,...n].find(i=>!!i&&!ky(i));return r?t.exitCode!=null&&r!==e?`Claude exited with code ${t.exitCode}: ${r}`:r:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Ls(t){return t.startsWith(Pu)}var Cn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;toolCallContext=new Map;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,s){return this.cwd=e,this.approvalMode=s,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ee.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let s=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&s.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&s.push("--resume",this.sessionId),Rs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=bu(this.hookPort,this.hookSecret),s.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&s.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&s.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&s.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ee.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Hi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.toolCallContext.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=s;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",s);o=c.command,a=c.args}else o=i;this.proc=(0,Eu.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}});let u=this.proc;u.on("error",c=>{if(this.proc!==u)return;let d=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Ms.existsSync)(this.cwd)&&(d=`Working directory does not exist: ${this.cwd}`),ee.error({sessionId:this.sessionId,error:d,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:d}),this.handler?.({type:"error",sessionId:this.sessionId,message:d})}),this.buffer="",u.stdout.on("data",c=>{if(this.proc!==u)return;this.buffer+=c.toString();let d=this.buffer.split(`
87
+ `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{ee.warn({sessionId:this.sessionId,linePreview:f.slice(0,100)},"failed to parse stdout line")}}),u.stderr.on("data",c=>{if(this.proc!==u)return;let d=c.toString().trim();d&&(ee.debug({sessionId:this.sessionId,stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),u.on("exit",(c,d)=>{if(this.proc!==u){ee.debug({sessionId:this.sessionId,exitCode:c,signal:d},"stale proc exit ignored, current proc was replaced");return}ee.info({sessionId:this.sessionId,exitCode:c,signal:d},"process exited");let f=this.interrupted;this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),f&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ee.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Ru({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ee.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ee.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let s=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(s+`
88
+ `),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Es(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ms.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Ay(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ms.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Ps(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&Ty(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Hi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Ru({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Pu}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Hi("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Ou=require("child_process"),Du=require("fs");var Wi=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Wi;var Mu=require("node:fs"),qi=require("node:path"),Ry="@vibelet/cli";function Ey(t){try{let e=JSON.parse((0,Mu.readFileSync)(t,"utf8"));if(e.name===Ry&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Py(){return"1.2.9"}var Lt=Py();var R=L.child({module:"codex"});function My(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 Ly(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function F(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function M(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Gi(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ny=new Set(["aborted","interrupted","cancelled","canceled","failed"]);function Oy(t){let e=M(t);return e?e.toLowerCase():null}function Dy(t){try{let e=JSON.parse(t),n=F(F(e)?.error)?.message;if(typeof n=="string"&&n.trim())return n}catch{}return t}function By(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function ji(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function $i(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Bu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Fu(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Fy(t){if(!Array.isArray(t))return null;for(let e of t){let n=F(e);if(!n)continue;let s=M(n.id),r=Array.isArray(n.options)?n.options.map(l=>F(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Bu(l))??i[0],a=i.find(l=>Fu(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Uy(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>F(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>F(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(r=>Bu(r)),s=e.some(r=>Fu(r));return n&&s}function Lu(t){let e=By(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:$i(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:$i(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=M(t.server),s=M(t.tool)??M(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:F(t.arguments)??F(t.input)??{}}:null}return null}function Hy(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>F(o)?.kind==="create"))return null;let i=st(n,e);return Mt(i)?i:null}function Wy(t){if(!Array.isArray(t))return"";for(let e of t){let n=F(e);if(!n)continue;let s=M(n.question)??M(n.header);if(s)return s}return""}function qy(t){let e=F(t);if(!e)return;let n=Gi(e.input_tokens??e.inputTokens)??0,s=Gi(e.output_tokens??e.outputTokens)??0,r=Gi(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function Nu(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 xn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,R.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=r,R.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Ou.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Du.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),R.error({error:d,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
89
+ `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{R.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(R.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{R.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&R.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let l=b.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Lt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=Nu(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,R.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",R.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let s=Nu(this.approvalMode,this.cwd||process.cwd());this.latestTurnUsage=void 0,this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,R.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:s.approvalPolicy,sandboxPolicy:s.sandboxPolicy,...n?{model:n}:{}}).then(r=>{R.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,R.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let s=this.approvalRequests.get(e),r=s?.rpcId??Number(e);if(!Number.isFinite(r))return!1;let i;if(!s)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(s.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[s.questionId]:{answers:[n?s.approveLabel:s.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return R.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
90
+ `),!0}restorePendingApproval(e){let n=Ly(e);n&&this.approvalRequests.set(e.requestId,n)}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,R.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let s=++this.rpcId,r=b.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(s,{resolve:a=>{r(),i(a)},reject:a=>{r(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(s),r(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:s,params:n})+`
91
+ `),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),R.error({method:e,rpcId:s,threadId:this.threadId},"RPC timeout"),r(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
92
92
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
93
- `)}resolveToolContext(e){let n=F(e?.item)??e??null,s=qi(n);if(!s)return null;let r=n?Eu(n):null;if(r)return this.toolContextByCallId.set(s,r),{callId:s,toolContext:r};let i=this.toolContextByCallId.get(s);return i?{callId:s,toolContext:i}:null}createFallbackInput(e,n){return e?Gi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,s){if(this.approvalRequests.set(e,n),_.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){x.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:s,approvalContext:Py(n)})}handleServerRequest(e,n,s){let r=String(n),i=this.resolveToolContext(s);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(r,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(r,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=s?.questions;if(!Fy(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=By(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(r,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","questions"])},Hy(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(r,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(r,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/permissions/requestApproval"){x.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}x.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(x.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let r=this.pending.get(e.id);this.pending.delete(e.id),e.error?r.reject(new Error(e.error.message??"RPC error")):r.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,s=F(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,s??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(s??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let r=s?.text??s?.delta??s?.content??"";r&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:r}):r||x.debug({paramsKeys:Object.keys(s??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":s?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:s.itemId??"",output:String(s.output)});break;case"item/started":{let r=F(s?.item),i=qi(r),o=r?Eu(r):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let r=F(s?.item)??s,i=qi(r),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Uy(o.input,this.cwd);if(a){let l=Ae([a]);l&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:i,output:l})}}i&&this.toolContextByCallId.delete(i);break}case"thread/tokenUsage/updated":{let r=F(s?.tokenUsage),i=F(r?.last);if(!i)break;this.latestTurnUsage=Wy({...i,modelContextWindow:r?.modelContextWindow});break}case"error":{let r=F(s?.error),i=M(r?.message)??"Codex error",o=Oy(i);this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0,x.error({threadId:this.threadId,message:o},"codex error notification"),_.emit("driver.error",{agent:"codex",sessionId:this.threadId,error:o}),this.handler?.({type:"error",sessionId:this.threadId,message:o});break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=M(s?.reason)??M(F(s?.turn)?.reason);x.info({threadId:this.threadId,reason:r},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...r?{reason:r}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let r=F(s?.turn),i=Ny(r?.status),o=this.latestTurnUsage;if(this.latestTurnUsage=void 0,i&&Ly.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...o?{usage:o}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),_.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:o}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:o});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var Bu=require("crypto"),Du=["Received. This is the hosted Vibelet review demo environment.","The app is connected to a public review backend and can send and receive assistant messages.","For review purposes, this backend returns deterministic demo responses without requiring a local computer on the same Wi-Fi network."].join(" ");function qy(t){let e=t.replace(/\s+/g," ").trim();return e?e.length>120?`${e.slice(0,117)}...`:e:""}var Ns=class{sessionId="";messageHandler=null;exitHandler=null;pendingTimer=null;responding=!1;stopped=!1;async start(e,n){return this.stopped=!1,this.sessionId=n||`review-${(0,Bu.randomUUID)()}`,this.sessionId}sendPrompt(e){if(this.stopped||!this.sessionId)return;this.clearPendingTimer(),this.responding=!0;let n=qy(e),s=n?`${Du}
93
+ `)}resolveToolContext(e){let n=F(e?.item)??e??null,s=ji(n);if(!s)return null;let r=n?Lu(n):null;if(r)return this.toolContextByCallId.set(s,r),{callId:s,toolContext:r};let i=this.toolContextByCallId.get(s);return i?{callId:s,toolContext:i}:null}createFallbackInput(e,n){return e?$i(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,s){if(this.approvalRequests.set(e,n),_.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){R.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:s,approvalContext:My(n)})}handleServerRequest(e,n,s){let r=String(n),i=this.resolveToolContext(s);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(r,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(r,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","reason","description"])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=s?.questions;if(!Uy(o)){R.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Fy(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(r,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,["itemId","questions"])},Wy(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(r,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(r,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(s,[])},M(s?.reason)??M(s?.description)??"");return}if(e==="item/permissions/requestApproval"){R.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}R.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(R.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let r=this.pending.get(e.id);this.pending.delete(e.id),e.error?r.reject(new Error(e.error.message??"RPC error")):r.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,s=F(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,s??void 0);return}switch(n&&R.debug({method:n,paramsPreview:JSON.stringify(s??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let r=s?.text??s?.delta??s?.content??"";r&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:r}):r||R.debug({paramsKeys:Object.keys(s??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":s?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:s.itemId??"",output:String(s.output)});break;case"item/started":{let r=F(s?.item),i=ji(r),o=r?Lu(r):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let r=F(s?.item)??s,i=ji(r),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Hy(o.input,this.cwd);if(a){let l=Ae([a]);l&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:i,output:l})}}i&&this.toolContextByCallId.delete(i);break}case"thread/tokenUsage/updated":{let r=F(s?.tokenUsage),i=F(r?.last);if(!i)break;this.latestTurnUsage=qy({...i,modelContextWindow:r?.modelContextWindow});break}case"error":{let r=F(s?.error),i=M(r?.message)??"Codex error",o=Dy(i);this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0,R.error({threadId:this.threadId,message:o},"codex error notification"),_.emit("driver.error",{agent:"codex",sessionId:this.threadId,error:o}),this.handler?.({type:"error",sessionId:this.threadId,message:o});break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=M(s?.reason)??M(F(s?.turn)?.reason);R.info({threadId:this.threadId,reason:r},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...r?{reason:r}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let r=F(s?.turn),i=Oy(r?.status),o=this.latestTurnUsage;if(this.latestTurnUsage=void 0,i&&Ny.has(i)){R.info({threadId:this.threadId,status:i},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...o?{usage:o}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}R.info({threadId:this.threadId,status:i??"completed"},"turn completed"),_.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:o}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:o});break}default:n&&R.debug({method:n},"unhandled notification");break}}};var Hu=require("crypto"),Uu=["Received. This is the hosted Vibelet review demo environment.","The app is connected to a public review backend and can send and receive assistant messages.","For review purposes, this backend returns deterministic demo responses without requiring a local computer on the same Wi-Fi network."].join(" ");function Gy(t){let e=t.replace(/\s+/g," ").trim();return e?e.length>120?`${e.slice(0,117)}...`:e:""}var Ns=class{sessionId="";messageHandler=null;exitHandler=null;pendingTimer=null;responding=!1;stopped=!1;async start(e,n){return this.stopped=!1,this.sessionId=n||`review-${(0,Hu.randomUUID)()}`,this.sessionId}sendPrompt(e){if(this.stopped||!this.sessionId)return;this.clearPendingTimer(),this.responding=!0;let n=Gy(e),s=n?`${Uu}
94
94
 
95
- Your message was received: "${n}"`:Du;this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!(this.stopped||!this.sessionId)&&(this.emit({type:"text.delta",sessionId:this.sessionId,content:s}),this.responding=!1,this.emit({type:"session.done",sessionId:this.sessionId,usage:{inputTokens:Math.max(1,Math.ceil(e.length/4)),outputTokens:Math.max(1,Math.ceil(s.length/4))}}))},25)}respondApproval(){return!1}getRespondingLivenessHint(){return this.responding?"alive":"unknown"}interrupt(){!this.responding||!this.sessionId||(this.clearPendingTimer(),this.responding=!1,this.emit({type:"session.interrupted",sessionId:this.sessionId}))}stop(){this.clearPendingTimer(),this.responding=!1,this.stopped=!0,this.exitHandler?.(0)}setApprovalMode(){}onMessage(e){this.messageHandler=e}onExit(e){this.exitHandler=e}emit(e){this.messageHandler?.(e)}clearPendingTimer(){this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null)}};var O=require("fs/promises"),lo=require("fs"),co=require("readline"),U=require("path"),ye=require("os");var Gy=new Set(["New session","Resumed session","Untitled session"]),jy=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function $y(t){return t.replace(/\s+/g," ").trim()}function Os(t){return typeof t!="string"?void 0:$y(t)||void 0}function Fu(t){let e=Os(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 Nt(t){let e=Os(t);return!e||Gy.has(e)||Fu(e)}function zy(t){for(let e of t.replace(/\r/g,"").split(`
96
- `)){let n=Os(e);if(n&&!Vy(n)&&!Qy(n))return n}}function Vy(t){return jy.some(e=>t.startsWith(e))}function Qy(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Jy(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let s=t[e+1];if(!s||/\s/.test(s))return e+1}}return-1}function ji(t,e=80){if(typeof t!="string")return;let n=zy(t);if(!n)return;let s=Jy(n),i=(s>0?n.slice(0,s):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Fu(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function rt(t,e){for(let n of t){let s=Os(n);if(!(!s||Nt(s)))return s}return ji(e)}var Wu=require("child_process"),qu=require("util");var Gu=(0,qu.promisify)(Wu.execFile),ju=5e3,Yy=2500,Ky=3e3,$u=8,Ds=new Map,$i=new Map,Uu=null;function Xy(t){let e=Ds.get(t);return e?Date.now()>e.expiresAt?(Ds.delete(t),null):e.value??void 0:null}function Zy(t,e){if(e===void 0){Ds.delete(t);return}Ds.set(t,{value:e,expiresAt:Date.now()+ju})}async function ev(t){if(!t)return;if(Uu)return Uu(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:s}=await Gu("git",["-C",t,...n],{env:tt(),timeout:Yy,maxBuffer:65536}),r=s.trim();if(r&&r!=="HEAD")return r}catch{}}async function tv(t){let e=Xy(t);if(e!==null)return e;let n=$i.get(t);if(n)return n;let s=ev(t).then(r=>(Zy(t,r),r)).finally(()=>{$i.delete(t)});return $i.set(t,s),s}async function zu(t,e,n){if(t.length===0)return;let s=Math.max(1,Math.min(e,t.length)),r=0;await Promise.all(Array.from({length:s},async()=>{for(;;){let i=r;if(r+=1,i>=t.length)return;await n(t[i])}}))}async function Vu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await zu(e,$u,async s=>{n.set(s,await tv(s))}),n}var Vi=new Map,zi=new Map,Hu=null;function nv(t,e){if(e===void 0){Vi.delete(t);return}Vi.set(t,{value:e,expiresAt:Date.now()+ju})}async function sv(t){if(t){if(Hu)return Hu(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await Gu("git",["-C",t,"diff","HEAD","--shortstat"],{env:tt(),timeout:Ky,maxBuffer:65536}),s=n.trim();if(!s)return;let r=s.match(/(\d+) insertion/),i=s.match(/(\d+) deletion/),o=r?Number(r[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function rv(t){let e=Vi.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=zi.get(t);if(n)return n;let s=sv(t).then(r=>(nv(t,r),r)).finally(()=>{zi.delete(t)});return zi.set(t,s),s}async function Qu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await zu(e,$u,async s=>{n.set(s,await rv(s))}),n}var Yu=require("child_process"),Us=require("fs/promises"),it=require("path"),Ku=require("os"),Xu=require("util");var iv=(0,Xu.promisify)(Yu.execFile),Fs=L.child({module:"process-scanner"}),Zu=5e3,ov=1500,av=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,lv=500,cv=15e3,En=null,Rn=null;function Hs(){En=null}var uv=new Set(["sh","bash","zsh","fish"]),dv=new Set(["env","nohup","timeout","gtimeout"]),fv=new Set(["node","nodejs","bun","tsx"]),pv=new Set(["-e","--eval","-p","--print"]),hv=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function gv(t){return t.replace(/^['"]|['"]$/g,"")}function ed(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(gv)}function Ju(t){let e=(0,it.basename)(t);return e==="claude"||e==="codex"?e:null}function mv(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=td(ed(e.trim()),!0);if(n)return n}return null}function td(t,e=!1){let n=0;for(;n<t.length;){let s=t[n],r=(0,it.basename)(s);if(dv.has(r)){if(n+=1,r==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(r==="timeout"||r==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(uv.has(r)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?mv(l):null}}return null}if(fv.has(r)){let o=n+1;for(;o<t.length;){let l=t[o];if(pv.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,hv.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=Ju(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=Ju(s);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Qi(t,e=!1){return td(ed(t),e)}function Ws(t){let e=Qi(t);return e?{agent:e.agent,args:e.args}:null}function nd(t){return av.test(t)&&Qi(t)!==null}function yv(t,e){let n=Ws(e);if(!n||n.agent!==t)return null;let{args:s}=n;if(t==="claude"){for(let r=0;r<s.length;r+=1){let i=s[r];if((i==="--resume"||i==="--session-id")&&s[r+1]&&!s[r+1].startsWith("-"))return s[r+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(s[0]!=="resume")return null;for(let r=1;r<s.length;r+=1){let i=s[r];if(!i.startsWith("-"))return i}return null}function vv(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],s=t[e+1],r=n==="--permission-mode"?s:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(r==="plan")return"plan";if(r==="acceptEdits")return"acceptEdits";if(r==="default")return"normal"}}function Sv(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function _v(t,e){let n=Ws(e);if(!(!n||n.agent!==t))return t==="claude"?vv(n.args):Sv(n.args)}function Bs(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function bv(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function wv(t,e){let n=Qi(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(s=>s.startsWith("--listen=")))}function Iv(t){let e=[...new Set(t.sessionFiles)].filter(i=>bv(t.agent,i)),n=yv(t.agent,t.command),s=_v(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...s?{approvalMode:s}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let r=Ot(t.agent,e[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",...s?{approvalMode:s}:{},sessionFilePath:e[0]}:null}function Av(t,e){let n=t,s=e;(Bs(e.confidence)>Bs(t.confidence)||Bs(e.confidence)===Bs(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,s=t);let r=n.approvalMode??s.approvalMode;return{...n,cwd:n.cwd||s.cwd,...r?{approvalMode:r}:{},title:n.title??s.title,sessionFilePath:n.sessionFilePath??s.sessionFilePath,isResponding:n.isResponding??s.isResponding}}function Ji(t){let e=new Map;for(let n of t){let s=`${n.agent}:${n.sessionId}`,r=e.get(s);e.set(s,r?Av(r,n):n)}return[...e.values()]}function Tv(t){try{return process.kill(t,0),!0}catch{return!1}}async function qs(t,e,n=ov){try{let{stdout:s}=await iv(t,e,{maxBuffer:8388608,timeout:n});return s}catch(s){let r=typeof s=="object"&&s!==null?{code:"code"in s?s.code:void 0,signal:"signal"in s?s.signal:void 0,killed:"killed"in s?s.killed:void 0}:{},i=String(s);return i.includes("ESRCH")||i.includes("No such process")?Fs.debug({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command skipped \u2014 process exited"):Fs.warn({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command failed"),""}}async function Cv(t){if(!t.sessionFilePath)return t;let e=await ot(t.sessionFilePath,t.agent);if(!e)return null;let n=await Ki(t.sessionFilePath,t.agent),s=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...s?{approvalMode:s}:{},title:t.title??e.title,isResponding:n.isResponding}}async function kv(t){return process.platform==="win32"?"":(await qs("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
97
- `).find(s=>s.startsWith("n"))?.slice(1).trim()??""}async function xv(t){if(process.platform==="win32")return[];let n=(await qs("lsof",["-p",String(t),"-Fn"])).split(`
98
- `).filter(s=>s.startsWith("n")).map(s=>s.slice(1).trim()).filter(s=>s.endsWith(".jsonl")?s.includes("/.claude/projects/")||s.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Rv(t){return t.split(`
99
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let s=Number(n[1]),r=n[2];if(!nd(r))return null;let i=Ws(r);return!Number.isFinite(s)||!i?null:{pid:s,command:r,agent:i.agent}}).filter(e=>!!e)}async function Ev(){let t=await qs("ps",["-axo","pid=,command="],Zu);return Rv(t)}async function Pv(){return(await qs("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],Zu)).split(`
100
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let s=Number(n[n.length-1]),r=n.slice(1,n.length-1).join(",");if(!Number.isFinite(s)||s===0||!nd(r))return null;let i=Ws(r);return i?{pid:s,command:r,agent:i.agent}:null}).filter(e=>!!e)}async function Mv(){return process.platform==="win32"?Pv():Ev()}async function Lv(t){let e=b.startTimer("process.scan.pgrep_ms"),n=await Mv();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let s=n.filter(o=>Tv(o.pid));t&&(t.aliveProcesses=s.length);let r=b.startTimer("process.scan.lsof_ms"),i=await Promise.all(s.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await kv(o.pid),sessionFiles:await xv(o.pid)})));return t&&(t.lsofMs+=r()),t&&(t.snapshots=i.length),i}function Nv(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Ov(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,it.join)((0,Ku.homedir)(),".claude","projects",Nv(e)),r=(await(0,Us.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(r.length===0)return null;let i=null;if(await Promise.all(r.map(async l=>{let u=await(0,Us.stat)((0,it.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,it.join)(n,i.name),a=Ot(t,o);return a?{sessionId:a,filePath:o}:null}return rd(e)}catch{return null}}async function Dv(){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=b.startTimer("process.scan.total_ms"),n=await Lv(t),s=[],r=[];for(let c of n){let d=Iv(c);if(d){s.push(d);continue}wv(c.agent,c.command)&&r.push(c)}t.directCandidates=s.length,t.fallbackLookups=r.length;let i=b.startTimer("process.scan.fallback_ms"),o=await Promise.all(r.map(async c=>{let d=await Ov(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=b.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...s,...o.filter(c=>c!==null)].map(c=>Cv(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Ji(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=lv||t.fallbackLookups>0)&&Fs.info({durationMs:t.totalMs,pgrepMs:t.pgrepMs,lsofMs:t.lsofMs,fallbackMs:t.fallbackMs,hydrateMs:t.hydrateMs,matchedProcesses:t.matchedProcesses,aliveProcesses:t.aliveProcesses,snapshots:t.snapshots,directCandidates:t.directCandidates,fallbackLookups:t.fallbackLookups,fallbackHits:t.fallbackHits,hydratedCandidates:t.hydratedCandidates,sessions:u.length},"process running sessions scanned"),En={value:u,expiresAt:Date.now()+cv},u}async function Yi(){return En&&Date.now()<En.expiresAt?En.value:Rn||(Rn=Dv().finally(()=>{Rn=null}),Rn)}async function sd(t){try{return(await Yi()).some(n=>n.sessionId===t)}catch(e){return Fs.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var ad=require("fs"),Ue=require("fs/promises"),Zi=require("os"),Mn=require("path");var Pn=L.child({module:"activity-watcher"}),Bv=12e4,Fv=5e3,Uv=6e4,id=5;function Hv(){return(0,Mn.join)((0,Zi.homedir)(),".claude","projects")}function Wv(){return(0,Mn.join)((0,Zi.homedir)(),".codex","sessions")}async function od(t){try{return await(0,Ue.realpath)(t)}catch{return t}}function Gs(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 od(e?.claudeDir??Hv()),s=await od(e?.codexDir??Wv());if(this.roots.set(n,"claude"),this.roots.set(s,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",s)]),this.updateGauges(),e?.usePolling){let r=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},r);a.unref?.(),this.pollTimers.push(a)}}else for(let[r,i]of this.roots)this.startNativeWatch(r,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(r=>{Pn.warn({error:String(r)},"activity watcher rescan failed")})},Uv),this.rescanTimer.unref?.(),Pn.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let s=(0,ad.watch)(e,{recursive:!0,persistent:!0},(r,i)=>{if(!i)return;let o=(0,Mn.join)(e,i.toString());Gs(o,n)&&this.resolveFsEvent(n,o)});s.on("error",r=>{Pn.warn({error:String(r),root:e},"activity watcher error")}),this.watchers.push(s)}catch(s){Pn.warn({error:String(s),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let s=await(0,Ue.stat)(n).catch(()=>null);if(!s){this.handleUnlink(n);return}s.isFile()&&await this.handleFsChange(n,s.mtimeMs)}async pollScan(e,n){let s=await this.walkSessionFiles(n,id),r=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of s){if(!Gs(o,e))continue;r.add(o);let l=this.filePathIndex.get(o);if(l){let c=this.entries.get(l);if(!c||a<=c.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(r.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,s]of this.roots)if(e===n||e.startsWith(`${n}/`))return s;return null}listActive(e=Bv){let n=Date.now(),s=n-e,r=n-Fv,i=[];for(let o of this.entries.values())o.lastActivityMs<s||i.push({...o,isResponding:o.lastActivityMs>=r});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let s=await this.walkSessionFiles(n,id);await Promise.all(s.map(async({filePath:r,mtimeMs:i})=>{Gs(r,e)&&await this.ingestPath(e,r,i,i)}))}async walkSessionFiles(e,n){let s=[],r=async(i,o)=>{if(o>n)return;let a=await(0,Ue.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,Mn.join)(i,l.name);if(l.isDirectory()){await r(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,Ue.stat)(u).catch(()=>null);c&&s.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await r(e,0),s}async handleFsChange(e,n){let s=this.identifyAgent(e);if(!s||!Gs(e,s))return;let r=Date.now(),i=n??r;await this.ingestPath(s,e,r,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,s,r){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,s,r);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await ot(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,s),c.mtimeMs=Math.max(c.mtimeMs,r),c.filePath!==n&&(this.filePathIndex.delete(c.filePath),c.filePath=n),this.filePathIndex.set(n,u);return}this.entries.set(u,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:s,mtimeMs:r}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,s){let r=this.entries.get(e);if(!r)return!1;let i=Math.max(r.lastActivityMs,n),o=Math.max(r.mtimeMs,s);return i===r.lastActivityMs&&o===r.mtimeMs?!1:(r.lastActivityMs=i,r.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[s,r]of this.entries)e.push((async()=>{let i=await(0,Ue.stat)(r.filePath).catch(()=>null);return i?i.mtimeMs>r.mtimeMs?this.touchEntry(s,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(r.filePath),this.entries.delete(s),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){Pn.warn({error:String(n)},"activity listener failed")}}updateGauges(){b.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()}},Dt=new Xi;var He=L.child({module:"inventory"}),fd=6e3,qv=3e4,Gv=1e4;function jv(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function $v(){return Dt.listActive().map(jv)}var pd={listScannedSessions:Dn,listWatcherSessions:$v,scanRunningSessions:Yi,searchSessionContent:bd},de=zv(),Nn=null,js=0,zs=0,$s=0,eo=0,to=new Set;function zv(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Vv(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,branch:t.branch,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode,lastUsage:t.lastUsage,interruptReason:t.interruptReason,stallWarning:t.stallWarning})}function Qv(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 ld(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Vv).sort(),runningSessions:t.runningSessions.map(Qv).sort()})}function hd(){for(let t of to)try{t()}catch(e){He.warn({error:String(e)},"session inventory backfill listener failed")}}function Ln(){b.gauge("session.inventory.external_cached_sessions",de.scannedSessions.length),b.gauge("session.inventory.external_running_sessions",de.runningSessions.length),b.gauge("session.inventory.backfill_inflight",Nn?1:0)}function gd(t){return to.add(t),()=>{to.delete(t)}}function md(){return{cachedSessions:de.scannedSessions.length,runningSessions:de.runningSessions.length,cacheAgeMs:de.refreshedAt?Math.max(0,Date.now()-de.refreshedAt):void 0,backfillInFlight:!!Nn,lastBackfillDurationMs:$s||void 0,lastBackfillCompletedAt:zs?new Date(zs).toISOString():void 0,lastBackfillAppliedAt:eo?new Date(eo).toISOString():void 0}}Ln();function yd(){return Dt.onActivity(()=>{_d(pd,fd)})}var Bt={daemonActive:3,externalRunning:2,idle:1},cd={high:3,medium:2,low:1};function vd(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Jv(t,e){let n=t.runtime.needsAttention?1:0,s=e.runtime.needsAttention?1:0,r=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return s-n||i-r||Bt[e.runtime.state]-Bt[t.runtime.state]||vd(t,e)}function Yv(t,e){return Bt[e.state]>Bt[t.state]?e:Bt[e.state]<Bt[t.state]?t:cd[e.confidence]>cd[t.confidence]?e:t}function Kv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Xv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Zv(t,e){return e?t?!(Nt(e)&&!Nt(t)):!0:!1}function no(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function eS(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...no(),...t.interruptReason||t.stallWarning?{needsAttention:!0}:{}},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function tS(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 nS(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||!!t.interruptReason||!!t.stallWarning||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function sS(t,e){for(let n of e){let s=`${n.agent}:${n.sessionId}`,r=t.get(s);if(!r){t.set(s,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Zv(r.title,n.title)?n.title:r.title,o=n.cwd||r.cwd,a=n.branch??r.branch,l=Yv(r.runtime,n.runtime),u=r.sources.slice();for(let h of n.sources)u.includes(h)||u.push(h);let c=n.sources.includes("process"),d=r.sources.includes("process")&&!r.sources.includes("daemon"),f=c?r.lastActivityAt:d?n.lastActivityAt:Xv(r.lastActivityAt,n.lastActivityAt);t.set(s,{...r,cwd:o,model:n.model??r.model,branch:a,title:i,createdAt:Kv(r.createdAt,n.createdAt),lastActivityAt:f,sources:u,runtime:l,managed:r.managed||n.managed,approvalMode:n.approvalMode??r.approvalMode,observedApprovalMode:n.observedApprovalMode??r.observedApprovalMode,lastUsage:n.lastUsage??r.lastUsage,interruptReason:n.interruptReason??r.interruptReason,stallWarning:n.stallWarning??r.stallWarning})}}function rS(...t){let e=new Map;for(let n of t)sS(e,n);return[...e.values()]}function iS(t,e,n,s,r,i,o){let a=s?.toLowerCase(),l=o&&o>0?o:0,u=t.filter(c=>{if(e&&c.agent!==e||n&&c.cwd!==n)return!1;if(l>0&&c.runtime.state==="idle"){let d=Date.parse(c.lastActivityAt);if(Number.isFinite(d)&&d<l)return!1}if(a){let d=(c.title??"").toLowerCase(),f=i?.[c.sessionId]?.toLowerCase()??"",h=d.includes(a)||(f?f.includes(a):!1),g=r?.has(c.sessionId)??!1;if(!h&&!g)return!1}return!0});return(s||l>0)&&He.info({total:t.length,filtered:u.length,search:s,contentMatchIds:r?.size??0,sinceMs:l||void 0},"filter applied"),u}function oS(t,e){if(!e)return 0;let n=0,s=t.length;for(;n<s;){let r=n+s>>1,i=t[r];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?s=r:n=r+1}if(n>0){let r=t[n-1];if(r.lastActivityAt===e.lastActivityAt&&r.sessionId===e.sessionId)return n}return 0}function ud(t,e,n,s,r,i,o,a,l){let u=i?1/0:Math.max(1,e||50),c=rS(t.sessionRecords.map(eS),t.scannedSessions,t.runningSessions.map(A=>tS(A,t.scannedAt)),t.activeSessions.map(nS)),d=t.deletedSessionIds?.size?c.filter(A=>!t.deletedSessionIds?.has(A.sessionId)):c,f=iS(d,s,r,i,o,a,l),h=f.filter(A=>A.runtime.state!=="idle"||A.managed).sort(Jv),g=f.filter(A=>A.runtime.state==="idle"&&!A.managed).sort(vd),m=oS(g,n),p=g.slice(m,m+u),C=m+p.length<g.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...h,...p],nextCursor:C}}async function dd(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,s]=await Promise.all([Vu(e),Qu(e)]),r=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=s.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(r=!0,{...o,branch:a,diffStat:l})});return r?{...t,sessions:i}:t}function On(t,e,n,s,r,i){return new Promise(o=>{let a=Date.now(),l=!1,u=!1,c=null,d=f=>{l||(l=!0,c&&(clearTimeout(c),c=null),o(f))};c=setTimeout(()=>{if(l)return;let f=Array.isArray(r)&&r.length>0;He.warn({source:t,timeoutMs:s,durationMs:Date.now()-a,partial:f?r.length:0},f?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u=!0,d(f?r:n)},s),typeof c=="object"&&"unref"in c&&c.unref(),e().then(f=>{let h=u;if(d(f),h&&i)try{i(f)}catch(g){He.warn({source:t,error:String(g)},"inventory source late-result handler failed")}}).catch(f=>{l||He.warn({source:t,error:String(f)},"session inventory source failed, using fallback"),d(n)})})}function aS(t=Date.now()){return de.refreshedAt===0||t-de.refreshedAt>=Gv}async function Sd(t,e){let[n,s]=await Promise.all([On("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),On("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Ji([...n,...s])}async function lS(t,e){let n=new Date().toISOString(),s=[],[r,i]=await Promise.all([On("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,s),[],e,s),Sd(t,e)]);return{scannedSessions:r,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function _d(t,e){if(Nn)return;let n=js,s=b.startTimer("session.inventory.backfill_latency_ms");Nn=lS(t,e).then(r=>{if(n!==js)return;let i=ld(de);de=r;let o=ld(r),a=s();$s=a,zs=Date.now(),Ln(),i!==o&&(eo=Date.now(),b.increment("session.inventory.backfill_applied"),He.info({durationMs:a,scanned:r.scannedSessions.length,running:r.runningSessions.length},"session inventory external backfill applied"),hd())}).catch(r=>{n===js&&($s=s(),zs=Date.now(),Ln(),He.warn({error:String(r),durationMs:$s},"session inventory external backfill failed"))}).finally(()=>{n===js&&(Nn=null,Ln())}),Ln()}async function Vs(t){let e={...pd,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??fd),s=t.sourceTimeoutMs!==void 0?n:qv;if(!t.search){let f=b.startTimer("session.inventory.fast_path_latency_ms");aS()&&_d(e,n);let h=de,g=ud({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:h.scannedSessions,runningSessions:h.runningSessions,scannedAt:h.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles,t.sinceMs);if(t.skipGitMetadata)return f(),g;let m=await dd(g);return f(),m}let r=[],i=new Date().toISOString(),o=t.search,a=t.sinceMs,[l,u,c]=await Promise.all([On("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),Sd(e,n),On("scanner.search_content",()=>e.searchSessionContent(o,t.agent,a),void 0,s,void 0,f=>{f&&f.size>0&&hd()})]);He.info({search:t.search,sinceMs:a&&a>0?a:void 0,contentMatches:c?.size??0,scanned:l.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let d=ud({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:l,runningSessions:u,scannedAt:i,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,o,c,t.customTitles,a);return t.skipGitMetadata?d:dd(d)}var Te=L.child({module:"scanner"});function uo(t){let e=new Map;return{get(n){let s=e.get(n);if(s){if(Date.now()>s.expiresAt){e.delete(n);return}return s.value}},set(n,s){e.set(n,{value:s,expiresAt:Date.now()+t})},clear(){e.clear()}}}var fo=3e4,oo=uo(fo),ao=uo(fo),Js=uo(fo),so=new Map,ro=new Map,Qs=null,at=24;function Xs(){oo.clear(),ao.clear(),Js.clear()}function Rd(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function lt(t,e,n){if(t.length===0)return[];let s=Math.max(1,Math.min(e,t.length)),r=new Array(t.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;r[o]=await n(t[o],o)}})),r}async function Ed(t){let e=await lt(t,at,async n=>{let s=await(0,O.stat)(n).catch(()=>null);return{path:n,mtimeMs:s?.mtimeMs??0}});return e.sort((n,s)=>s.mtimeMs-n.mtimeMs),e}async function cS(){let t=(0,U.join)((0,ye.homedir)(),".claude","projects"),e=[],n=await(0,O.readdir)(t,{withFileTypes:!0}).catch(()=>[]);for(let s of n){if(!s.isDirectory())continue;let r=(0,U.join)(t,s.name),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i)o.endsWith(".jsonl")&&e.push((0,U.join)(r,o))}return e}async function uS(){let t=(0,U.join)((0,ye.homedir)(),".codex","sessions"),e=[],n=await(0,O.readdir)(t).catch(()=>[]);for(let s of n){let r=(0,U.join)(t,s),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i){let a=(0,U.join)(r,o),l=await(0,O.readdir)(a).catch(()=>[]);for(let u of l){let c=(0,U.join)(a,u),d=await(0,O.readdir)(c).catch(()=>[]);for(let f of d)f.endsWith(".jsonl")&&e.push((0,U.join)(c,f))}}}return e}async function po(){let t=await uS();return Ed(t)}function dS(t){let e=`codex-latest:${(0,ye.homedir)()}`,n=new Map;for(let s of t)n.has(s.cwd)||n.set(s.cwd,s.match);Js.set(e,n)}function*Pd(t,e){let n=0,s=0;for(;n<t.length&&s<e;){let r=t.indexOf(`
101
- `,n);r===-1&&(r=t.length);let i=t.substring(n,r);n=r+1,!(i.length===0||i.trim().length===0)&&(yield i,s+=1)}}var io=512*1024,wd=256*1024;async function Md(t,e){if(e<=io)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Buffer.alloc(io),{bytesRead:r}=await n.read(s,0,io,0);return s.toString("utf-8",0,r)}finally{await n.close()}}async function Ld(t,e){if(e<=wd)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Math.max(0,e-wd),r=Buffer.alloc(e-s),{bytesRead:i}=await n.read(r,0,r.length,s);return r.toString("utf-8",0,i)}finally{await n.close()}}function Id(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function fS(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,s=typeof n?.type=="string"?n.type:"",r=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&s==="danger-full-access")return"autoApprove";if(e==="on-request"&&s==="workspace-write")return r?.length?"normal":"plan"}function pS(t){return t?.type==="permission-mode"?Id(t.permissionMode):Id(t?.permissionMode)}function hS(t){if(t?.type==="turn_context")return fS(t.payload)}function gS(t){if(t?.type!=="event_msg"||t.payload?.type!=="token_count")return;let e=t.payload.info;if(!e||typeof e!="object")return;let n=e.last_token_usage;if(!n||typeof n!="object")return;let s=Number(n.input_tokens),r=Number(n.output_tokens);if(!Number.isFinite(s)||!Number.isFinite(r))return;let i=Number(e.model_context_window);return{inputTokens:s,outputTokens:r,...Number.isFinite(i)&&i>0?{contextWindowTokens:i}:{}}}async function mS(t,e){let n,s,r=await Ld(t,e);for(let i of r.split(`
102
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=hS(o);a&&(n=a);let l=gS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function Ad(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.input_tokens??e.inputTokens),s=Number(e.output_tokens??e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.cache_creation_input_tokens??e.cacheCreationInputTokens),i=Number(e.cache_read_input_tokens??e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(r)?{cacheCreationInputTokens:r}:{},...Number.isFinite(i)?{cacheReadInputTokens:i}:{}}}function yS(t){return t?.type==="assistant"?Ad(t.message?.usage??t.usage):Ad(t?.toolUseResult?.usage)}async function Nd(t,e){let n,s,r=await Ld(t,e);for(let i of r.split(`
103
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=pS(o);a&&(n=a);let l=yS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function ho(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 Od(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?ho(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Zs(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 vS=/^\[Attached image: ([^\n]+)\]$/gm;function SS(t){let e=[],n=new Set;for(let s of t.matchAll(vS)){let r=s[1]?.trim();!r||n.has(r)||(n.add(r),e.push(r))}return e}function _S(t){if(t.role!=="user")return t;let e=[...t.images??[],...SS(t.content)].filter((n,s,r)=>n&&r.indexOf(n)===s);return e.length?{...t,images:e}:t}var bS=["<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 wS(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?bS.some(s=>n.startsWith(s)):!1}function er(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Zs(t.message.content);return wS(t,e)?"":e}function IS(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function AS(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(s=>!s||typeof s!="object"?"":typeof s.text=="string"?s.text:typeof s.content=="string"?s.content:"").filter(Boolean).join(`
95
+ Your message was received: "${n}"`:Uu;this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,!(this.stopped||!this.sessionId)&&(this.emit({type:"text.delta",sessionId:this.sessionId,content:s}),this.responding=!1,this.emit({type:"session.done",sessionId:this.sessionId,usage:{inputTokens:Math.max(1,Math.ceil(e.length/4)),outputTokens:Math.max(1,Math.ceil(s.length/4))}}))},25)}respondApproval(){return!1}getRespondingLivenessHint(){return this.responding?"alive":"unknown"}interrupt(){!this.responding||!this.sessionId||(this.clearPendingTimer(),this.responding=!1,this.emit({type:"session.interrupted",sessionId:this.sessionId}))}stop(){this.clearPendingTimer(),this.responding=!1,this.stopped=!0,this.exitHandler?.(0)}setApprovalMode(){}onMessage(e){this.messageHandler=e}onExit(e){this.exitHandler=e}emit(e){this.messageHandler?.(e)}clearPendingTimer(){this.pendingTimer&&(clearTimeout(this.pendingTimer),this.pendingTimer=null)}};var O=require("fs/promises"),uo=require("fs"),fo=require("readline"),U=require("path"),ye=require("os");var jy=new Set(["New session","Resumed session","Untitled session"]),$y=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function zy(t){return t.replace(/\s+/g," ").trim()}function Os(t){return typeof t!="string"?void 0:zy(t)||void 0}function Wu(t){let e=Os(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 Nt(t){let e=Os(t);return!e||jy.has(e)||Wu(e)}function Vy(t){for(let e of t.replace(/\r/g,"").split(`
96
+ `)){let n=Os(e);if(n&&!Qy(n)&&!Jy(n))return n}}function Qy(t){return $y.some(e=>t.startsWith(e))}function Jy(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Yy(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let s=t[e+1];if(!s||/\s/.test(s))return e+1}}return-1}function zi(t,e=80){if(typeof t!="string")return;let n=Vy(t);if(!n)return;let s=Yy(n),i=(s>0?n.slice(0,s):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Wu(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function rt(t,e){for(let n of t){let s=Os(n);if(!(!s||Nt(s)))return s}return zi(e)}var ju=require("child_process"),$u=require("util");var zu=(0,$u.promisify)(ju.execFile),Vu=5e3,Ky=2500,Xy=3e3,Qu=8,Ds=new Map,Vi=new Map,qu=null;function Zy(t){let e=Ds.get(t);return e?Date.now()>e.expiresAt?(Ds.delete(t),null):e.value??void 0:null}function ev(t,e){if(e===void 0){Ds.delete(t);return}Ds.set(t,{value:e,expiresAt:Date.now()+Vu})}async function tv(t){if(!t)return;if(qu)return qu(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:s}=await zu("git",["-C",t,...n],{env:tt(),timeout:Ky,maxBuffer:65536}),r=s.trim();if(r&&r!=="HEAD")return r}catch{}}async function nv(t){let e=Zy(t);if(e!==null)return e;let n=Vi.get(t);if(n)return n;let s=tv(t).then(r=>(ev(t,r),r)).finally(()=>{Vi.delete(t)});return Vi.set(t,s),s}async function Ju(t,e,n){if(t.length===0)return;let s=Math.max(1,Math.min(e,t.length)),r=0;await Promise.all(Array.from({length:s},async()=>{for(;;){let i=r;if(r+=1,i>=t.length)return;await n(t[i])}}))}async function Bs(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Ju(e,Qu,async s=>{n.set(s,await nv(s))}),n}var Ji=new Map,Qi=new Map,Gu=null;function sv(t,e){if(e===void 0){Ji.delete(t);return}Ji.set(t,{value:e,expiresAt:Date.now()+Vu})}async function rv(t){if(t){if(Gu)return Gu(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await zu("git",["-C",t,"diff","HEAD","--shortstat"],{env:tt(),timeout:Xy,maxBuffer:65536}),s=n.trim();if(!s)return;let r=s.match(/(\d+) insertion/),i=s.match(/(\d+) deletion/),o=r?Number(r[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function iv(t){let e=Ji.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=Qi.get(t);if(n)return n;let s=rv(t).then(r=>(sv(t,r),r)).finally(()=>{Qi.delete(t)});return Qi.set(t,s),s}async function Fs(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Ju(e,Qu,async s=>{n.set(s,await iv(s))}),n}var Ku=require("child_process"),Ws=require("fs/promises"),it=require("path"),Xu=require("os"),Zu=require("util");var ov=(0,Zu.promisify)(Ku.execFile),Hs=L.child({module:"process-scanner"}),ed=5e3,av=1500,lv=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,cv=500,uv=15e3,En=null,Rn=null;function qs(){En=null}var dv=new Set(["sh","bash","zsh","fish"]),fv=new Set(["env","nohup","timeout","gtimeout"]),pv=new Set(["node","nodejs","bun","tsx"]),hv=new Set(["-e","--eval","-p","--print"]),gv=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function mv(t){return t.replace(/^['"]|['"]$/g,"")}function td(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(mv)}function Yu(t){let e=(0,it.basename)(t);return e==="claude"||e==="codex"?e:null}function yv(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=nd(td(e.trim()),!0);if(n)return n}return null}function nd(t,e=!1){let n=0;for(;n<t.length;){let s=t[n],r=(0,it.basename)(s);if(fv.has(r)){if(n+=1,r==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(r==="timeout"||r==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(dv.has(r)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?yv(l):null}}return null}if(pv.has(r)){let o=n+1;for(;o<t.length;){let l=t[o];if(hv.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,gv.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=Yu(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=Yu(s);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Yi(t,e=!1){return nd(td(t),e)}function Gs(t){let e=Yi(t);return e?{agent:e.agent,args:e.args}:null}function sd(t){return lv.test(t)&&Yi(t)!==null}function vv(t,e){let n=Gs(e);if(!n||n.agent!==t)return null;let{args:s}=n;if(t==="claude"){for(let r=0;r<s.length;r+=1){let i=s[r];if((i==="--resume"||i==="--session-id")&&s[r+1]&&!s[r+1].startsWith("-"))return s[r+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(s[0]!=="resume")return null;for(let r=1;r<s.length;r+=1){let i=s[r];if(!i.startsWith("-"))return i}return null}function Sv(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],s=t[e+1],r=n==="--permission-mode"?s:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(r==="plan")return"plan";if(r==="acceptEdits")return"acceptEdits";if(r==="default")return"normal"}}function _v(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function bv(t,e){let n=Gs(e);if(!(!n||n.agent!==t))return t==="claude"?Sv(n.args):_v(n.args)}function Us(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function wv(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Iv(t,e){let n=Yi(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(s=>s.startsWith("--listen=")))}function Av(t){let e=[...new Set(t.sessionFiles)].filter(i=>wv(t.agent,i)),n=vv(t.agent,t.command),s=bv(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...s?{approvalMode:s}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let r=Ot(t.agent,e[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",...s?{approvalMode:s}:{},sessionFilePath:e[0]}:null}function Tv(t,e){let n=t,s=e;(Us(e.confidence)>Us(t.confidence)||Us(e.confidence)===Us(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,s=t);let r=n.approvalMode??s.approvalMode;return{...n,cwd:n.cwd||s.cwd,...r?{approvalMode:r}:{},title:n.title??s.title,sessionFilePath:n.sessionFilePath??s.sessionFilePath,isResponding:n.isResponding??s.isResponding}}function Ki(t){let e=new Map;for(let n of t){let s=`${n.agent}:${n.sessionId}`,r=e.get(s);e.set(s,r?Tv(r,n):n)}return[...e.values()]}function kv(t){try{return process.kill(t,0),!0}catch{return!1}}async function js(t,e,n=av){try{let{stdout:s}=await ov(t,e,{maxBuffer:8388608,timeout:n});return s}catch(s){let r=typeof s=="object"&&s!==null?{code:"code"in s?s.code:void 0,signal:"signal"in s?s.signal:void 0,killed:"killed"in s?s.killed:void 0}:{},i=String(s);return i.includes("ESRCH")||i.includes("No such process")?Hs.debug({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command skipped \u2014 process exited"):Hs.warn({file:t,args:e,timeoutMs:n,error:i,...r},"process scan command failed"),""}}async function Cv(t){if(!t.sessionFilePath)return t;let e=await ot(t.sessionFilePath,t.agent);if(!e)return null;let n=await Zi(t.sessionFilePath,t.agent),s=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...s?{approvalMode:s}:{},title:t.title??e.title,isResponding:n.isResponding}}async function xv(t){return process.platform==="win32"?"":(await js("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
97
+ `).find(s=>s.startsWith("n"))?.slice(1).trim()??""}async function Rv(t){if(process.platform==="win32")return[];let n=(await js("lsof",["-p",String(t),"-Fn"])).split(`
98
+ `).filter(s=>s.startsWith("n")).map(s=>s.slice(1).trim()).filter(s=>s.endsWith(".jsonl")?s.includes("/.claude/projects/")||s.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Ev(t){return t.split(`
99
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let s=Number(n[1]),r=n[2];if(!sd(r))return null;let i=Gs(r);return!Number.isFinite(s)||!i?null:{pid:s,command:r,agent:i.agent}}).filter(e=>!!e)}async function Pv(){let t=await js("ps",["-axo","pid=,command="],ed);return Ev(t)}async function Mv(){return(await js("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],ed)).split(`
100
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let s=Number(n[n.length-1]),r=n.slice(1,n.length-1).join(",");if(!Number.isFinite(s)||s===0||!sd(r))return null;let i=Gs(r);return i?{pid:s,command:r,agent:i.agent}:null}).filter(e=>!!e)}async function Lv(){return process.platform==="win32"?Mv():Pv()}async function Nv(t){let e=b.startTimer("process.scan.pgrep_ms"),n=await Lv();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let s=n.filter(o=>kv(o.pid));t&&(t.aliveProcesses=s.length);let r=b.startTimer("process.scan.lsof_ms"),i=await Promise.all(s.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await xv(o.pid),sessionFiles:await Rv(o.pid)})));return t&&(t.lsofMs+=r()),t&&(t.snapshots=i.length),i}function Ov(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Dv(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,it.join)((0,Xu.homedir)(),".claude","projects",Ov(e)),r=(await(0,Ws.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(r.length===0)return null;let i=null;if(await Promise.all(r.map(async l=>{let u=await(0,Ws.stat)((0,it.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,it.join)(n,i.name),a=Ot(t,o);return a?{sessionId:a,filePath:o}:null}return id(e)}catch{return null}}async function Bv(){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=b.startTimer("process.scan.total_ms"),n=await Nv(t),s=[],r=[];for(let c of n){let d=Av(c);if(d){s.push(d);continue}Iv(c.agent,c.command)&&r.push(c)}t.directCandidates=s.length,t.fallbackLookups=r.length;let i=b.startTimer("process.scan.fallback_ms"),o=await Promise.all(r.map(async c=>{let d=await Dv(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=b.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...s,...o.filter(c=>c!==null)].map(c=>Cv(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Ki(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=cv||t.fallbackLookups>0)&&Hs.info({durationMs:t.totalMs,pgrepMs:t.pgrepMs,lsofMs:t.lsofMs,fallbackMs:t.fallbackMs,hydrateMs:t.hydrateMs,matchedProcesses:t.matchedProcesses,aliveProcesses:t.aliveProcesses,snapshots:t.snapshots,directCandidates:t.directCandidates,fallbackLookups:t.fallbackLookups,fallbackHits:t.fallbackHits,hydratedCandidates:t.hydratedCandidates,sessions:u.length},"process running sessions scanned"),En={value:u,expiresAt:Date.now()+uv},u}async function Xi(){return En&&Date.now()<En.expiresAt?En.value:Rn||(Rn=Bv().finally(()=>{Rn=null}),Rn)}async function rd(t){try{return(await Xi()).some(n=>n.sessionId===t)}catch(e){return Hs.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var ld=require("fs"),Ue=require("fs/promises"),to=require("os"),Mn=require("path");var Pn=L.child({module:"activity-watcher"}),Fv=12e4,Uv=5e3,Hv=6e4,od=5;function Wv(){return(0,Mn.join)((0,to.homedir)(),".claude","projects")}function qv(){return(0,Mn.join)((0,to.homedir)(),".codex","sessions")}async function ad(t){try{return await(0,Ue.realpath)(t)}catch{return t}}function $s(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var eo=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 ad(e?.claudeDir??Wv()),s=await ad(e?.codexDir??qv());if(this.roots.set(n,"claude"),this.roots.set(s,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",s)]),this.updateGauges(),e?.usePolling){let r=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},r);a.unref?.(),this.pollTimers.push(a)}}else for(let[r,i]of this.roots)this.startNativeWatch(r,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(r=>{Pn.warn({error:String(r)},"activity watcher rescan failed")})},Hv),this.rescanTimer.unref?.(),Pn.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let s=(0,ld.watch)(e,{recursive:!0,persistent:!0},(r,i)=>{if(!i)return;let o=(0,Mn.join)(e,i.toString());$s(o,n)&&this.resolveFsEvent(n,o)});s.on("error",r=>{Pn.warn({error:String(r),root:e},"activity watcher error")}),this.watchers.push(s)}catch(s){Pn.warn({error:String(s),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let s=await(0,Ue.stat)(n).catch(()=>null);if(!s){this.handleUnlink(n);return}s.isFile()&&await this.handleFsChange(n,s.mtimeMs)}async pollScan(e,n){let s=await this.walkSessionFiles(n,od),r=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of s){if(!$s(o,e))continue;r.add(o);let l=this.filePathIndex.get(o);if(l){let c=this.entries.get(l);if(!c||a<=c.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(r.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,s]of this.roots)if(e===n||e.startsWith(`${n}/`))return s;return null}listActive(e=Fv){let n=Date.now(),s=n-e,r=n-Uv,i=[];for(let o of this.entries.values())o.lastActivityMs<s||i.push({...o,isResponding:o.lastActivityMs>=r});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let s=await this.walkSessionFiles(n,od);await Promise.all(s.map(async({filePath:r,mtimeMs:i})=>{$s(r,e)&&await this.ingestPath(e,r,i,i)}))}async walkSessionFiles(e,n){let s=[],r=async(i,o)=>{if(o>n)return;let a=await(0,Ue.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,Mn.join)(i,l.name);if(l.isDirectory()){await r(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,Ue.stat)(u).catch(()=>null);c&&s.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await r(e,0),s}async handleFsChange(e,n){let s=this.identifyAgent(e);if(!s||!$s(e,s))return;let r=Date.now(),i=n??r;await this.ingestPath(s,e,r,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,s,r){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,s,r);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await ot(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,s),c.mtimeMs=Math.max(c.mtimeMs,r),c.filePath!==n&&(this.filePathIndex.delete(c.filePath),c.filePath=n),this.filePathIndex.set(n,u);return}this.entries.set(u,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:s,mtimeMs:r}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,s){let r=this.entries.get(e);if(!r)return!1;let i=Math.max(r.lastActivityMs,n),o=Math.max(r.mtimeMs,s);return i===r.lastActivityMs&&o===r.mtimeMs?!1:(r.lastActivityMs=i,r.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[s,r]of this.entries)e.push((async()=>{let i=await(0,Ue.stat)(r.filePath).catch(()=>null);return i?i.mtimeMs>r.mtimeMs?this.touchEntry(s,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(r.filePath),this.entries.delete(s),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){Pn.warn({error:String(n)},"activity listener failed")}}updateGauges(){b.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()}},Dt=new eo;var He=L.child({module:"inventory"}),pd=6e3,Gv=3e4,jv=1e4;function $v(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function zv(){return Dt.listActive().map($v)}var hd={listScannedSessions:Dn,listWatcherSessions:zv,scanRunningSessions:Xi,searchSessionContent:wd},de=Vv(),Nn=null,zs=0,Qs=0,Vs=0,no=0,so=new Set;function Vv(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Qv(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,branch:t.branch,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode,lastUsage:t.lastUsage,interruptReason:t.interruptReason,stallWarning:t.stallWarning})}function Jv(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 cd(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Qv).sort(),runningSessions:t.runningSessions.map(Jv).sort()})}function gd(){for(let t of so)try{t()}catch(e){He.warn({error:String(e)},"session inventory backfill listener failed")}}function Ln(){b.gauge("session.inventory.external_cached_sessions",de.scannedSessions.length),b.gauge("session.inventory.external_running_sessions",de.runningSessions.length),b.gauge("session.inventory.backfill_inflight",Nn?1:0)}function md(t){return so.add(t),()=>{so.delete(t)}}function yd(){return{cachedSessions:de.scannedSessions.length,runningSessions:de.runningSessions.length,cacheAgeMs:de.refreshedAt?Math.max(0,Date.now()-de.refreshedAt):void 0,backfillInFlight:!!Nn,lastBackfillDurationMs:Vs||void 0,lastBackfillCompletedAt:Qs?new Date(Qs).toISOString():void 0,lastBackfillAppliedAt:no?new Date(no).toISOString():void 0}}Ln();function vd(){return Dt.onActivity(()=>{bd(hd,pd)})}var Bt={daemonActive:3,externalRunning:2,idle:1},ud={high:3,medium:2,low:1};function Sd(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Yv(t,e){let n=t.runtime.needsAttention?1:0,s=e.runtime.needsAttention?1:0,r=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return s-n||i-r||Bt[e.runtime.state]-Bt[t.runtime.state]||Sd(t,e)}function Kv(t,e){return Bt[e.state]>Bt[t.state]?e:Bt[e.state]<Bt[t.state]?t:ud[e.confidence]>ud[t.confidence]?e:t}function Xv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Zv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function eS(t,e){return e?t?!(Nt(e)&&!Nt(t)):!0:!1}function ro(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function tS(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...ro(),...t.interruptReason||t.stallWarning?{needsAttention:!0}:{}},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function nS(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 sS(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,model:t.model,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||!!t.interruptReason||!!t.stallWarning||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode,lastUsage:t.lastUsage,...t.interruptReason?{interruptReason:t.interruptReason}:{},...t.stallWarning?{stallWarning:t.stallWarning}:{}}}function rS(t,e){for(let n of e){let s=`${n.agent}:${n.sessionId}`,r=t.get(s);if(!r){t.set(s,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=eS(r.title,n.title)?n.title:r.title,o=n.cwd||r.cwd,a=n.branch??r.branch,l=Kv(r.runtime,n.runtime),u=r.sources.slice();for(let p of n.sources)u.includes(p)||u.push(p);let c=n.sources.includes("process"),d=r.sources.includes("process")&&!r.sources.includes("daemon"),f=c?r.lastActivityAt:d?n.lastActivityAt:Zv(r.lastActivityAt,n.lastActivityAt);t.set(s,{...r,cwd:o,model:n.model??r.model,branch:a,title:i,createdAt:Xv(r.createdAt,n.createdAt),lastActivityAt:f,sources:u,runtime:l,managed:r.managed||n.managed,approvalMode:n.approvalMode??r.approvalMode,observedApprovalMode:n.observedApprovalMode??r.observedApprovalMode,lastUsage:n.lastUsage??r.lastUsage,interruptReason:n.interruptReason??r.interruptReason,stallWarning:n.stallWarning??r.stallWarning})}}function iS(...t){let e=new Map;for(let n of t)rS(e,n);return[...e.values()]}function oS(t,e,n,s,r,i,o){let a=s?.toLowerCase(),l=o&&o>0?o:0,u=t.filter(c=>{if(e&&c.agent!==e||n&&c.cwd!==n)return!1;if(l>0&&c.runtime.state==="idle"){let d=Date.parse(c.lastActivityAt);if(Number.isFinite(d)&&d<l)return!1}if(a){let d=(c.title??"").toLowerCase(),f=i?.[c.sessionId]?.toLowerCase()??"",p=d.includes(a)||(f?f.includes(a):!1),g=r?.has(c.sessionId)??!1;if(!p&&!g)return!1}return!0});return(s||l>0)&&He.info({total:t.length,filtered:u.length,search:s,contentMatchIds:r?.size??0,sinceMs:l||void 0},"filter applied"),u}function aS(t,e){if(!e)return 0;let n=0,s=t.length;for(;n<s;){let r=n+s>>1,i=t[r];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?s=r:n=r+1}if(n>0){let r=t[n-1];if(r.lastActivityAt===e.lastActivityAt&&r.sessionId===e.sessionId)return n}return 0}function dd(t,e,n,s,r,i,o,a,l){let u=i?1/0:Math.max(1,e||50),c=iS(t.sessionRecords.map(tS),t.scannedSessions,t.runningSessions.map(I=>nS(I,t.scannedAt)),t.activeSessions.map(sS)),d=t.deletedSessionIds?.size?c.filter(I=>!t.deletedSessionIds?.has(I.sessionId)):c,f=oS(d,s,r,i,o,a,l),p=f.filter(I=>I.runtime.state!=="idle"||I.managed).sort(Yv),g=f.filter(I=>I.runtime.state==="idle"&&!I.managed).sort(Sd),m=aS(g,n),h=g.slice(m,m+u),T=m+h.length<g.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...p,...h],nextCursor:T}}async function fd(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,s]=await Promise.all([Bs(e),Fs(e)]),r=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=s.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(r=!0,{...o,branch:a,diffStat:l})});return r?{...t,sessions:i}:t}function On(t,e,n,s,r,i){return new Promise(o=>{let a=Date.now(),l=!1,u=!1,c=null,d=f=>{l||(l=!0,c&&(clearTimeout(c),c=null),o(f))};c=setTimeout(()=>{if(l)return;let f=Array.isArray(r)&&r.length>0;He.warn({source:t,timeoutMs:s,durationMs:Date.now()-a,partial:f?r.length:0},f?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u=!0,d(f?r:n)},s),typeof c=="object"&&"unref"in c&&c.unref(),e().then(f=>{let p=u;if(d(f),p&&i)try{i(f)}catch(g){He.warn({source:t,error:String(g)},"inventory source late-result handler failed")}}).catch(f=>{l||He.warn({source:t,error:String(f)},"session inventory source failed, using fallback"),d(n)})})}function lS(t=Date.now()){return de.refreshedAt===0||t-de.refreshedAt>=jv}async function _d(t,e){let[n,s]=await Promise.all([On("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),On("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Ki([...n,...s])}async function cS(t,e){let n=new Date().toISOString(),s=[],[r,i]=await Promise.all([On("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,s),[],e,s),_d(t,e)]);return{scannedSessions:r,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function bd(t,e){if(Nn)return;let n=zs,s=b.startTimer("session.inventory.backfill_latency_ms");Nn=cS(t,e).then(r=>{if(n!==zs)return;let i=cd(de);de=r;let o=cd(r),a=s();Vs=a,Qs=Date.now(),Ln(),i!==o&&(no=Date.now(),b.increment("session.inventory.backfill_applied"),He.info({durationMs:a,scanned:r.scannedSessions.length,running:r.runningSessions.length},"session inventory external backfill applied"),gd())}).catch(r=>{n===zs&&(Vs=s(),Qs=Date.now(),Ln(),He.warn({error:String(r),durationMs:Vs},"session inventory external backfill failed"))}).finally(()=>{n===zs&&(Nn=null,Ln())}),Ln()}async function Js(t){let e={...hd,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??pd),s=t.sourceTimeoutMs!==void 0?n:Gv;if(!t.search){let f=b.startTimer("session.inventory.fast_path_latency_ms");lS()&&bd(e,n);let p=de,g=dd({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:p.scannedSessions,runningSessions:p.runningSessions,scannedAt:p.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles,t.sinceMs);if(t.skipGitMetadata)return f(),g;let m=await fd(g);return f(),m}let r=[],i=new Date().toISOString(),o=t.search,a=t.sinceMs,[l,u,c]=await Promise.all([On("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),_d(e,n),On("scanner.search_content",()=>e.searchSessionContent(o,t.agent,a),void 0,s,void 0,f=>{f&&f.size>0&&gd()})]);He.info({search:t.search,sinceMs:a&&a>0?a:void 0,contentMatches:c?.size??0,scanned:l.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let d=dd({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:l,runningSessions:u,scannedAt:i,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,o,c,t.customTitles,a);return t.skipGitMetadata?d:fd(d)}var Te=L.child({module:"scanner"});function po(t){let e=new Map;return{get(n){let s=e.get(n);if(s){if(Date.now()>s.expiresAt){e.delete(n);return}return s.value}},set(n,s){e.set(n,{value:s,expiresAt:Date.now()+t})},clear(){e.clear()}}}var ho=3e4,lo=po(ho),co=po(ho),Ks=po(ho),io=new Map,oo=new Map,Ys=null,at=24;function er(){lo.clear(),co.clear(),Ks.clear()}function Ed(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function lt(t,e,n){if(t.length===0)return[];let s=Math.max(1,Math.min(e,t.length)),r=new Array(t.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;r[o]=await n(t[o],o)}})),r}async function Pd(t){let e=await lt(t,at,async n=>{let s=await(0,O.stat)(n).catch(()=>null);return{path:n,mtimeMs:s?.mtimeMs??0}});return e.sort((n,s)=>s.mtimeMs-n.mtimeMs),e}async function uS(){let t=(0,U.join)((0,ye.homedir)(),".claude","projects"),e=[],n=await(0,O.readdir)(t,{withFileTypes:!0}).catch(()=>[]);for(let s of n){if(!s.isDirectory())continue;let r=(0,U.join)(t,s.name),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i)o.endsWith(".jsonl")&&e.push((0,U.join)(r,o))}return e}async function dS(){let t=(0,U.join)((0,ye.homedir)(),".codex","sessions"),e=[],n=await(0,O.readdir)(t).catch(()=>[]);for(let s of n){let r=(0,U.join)(t,s),i=await(0,O.readdir)(r).catch(()=>[]);for(let o of i){let a=(0,U.join)(r,o),l=await(0,O.readdir)(a).catch(()=>[]);for(let u of l){let c=(0,U.join)(a,u),d=await(0,O.readdir)(c).catch(()=>[]);for(let f of d)f.endsWith(".jsonl")&&e.push((0,U.join)(c,f))}}}return e}async function go(){let t=await dS();return Pd(t)}function fS(t){let e=`codex-latest:${(0,ye.homedir)()}`,n=new Map;for(let s of t)n.has(s.cwd)||n.set(s.cwd,s.match);Ks.set(e,n)}function*Md(t,e){let n=0,s=0;for(;n<t.length&&s<e;){let r=t.indexOf(`
101
+ `,n);r===-1&&(r=t.length);let i=t.substring(n,r);n=r+1,!(i.length===0||i.trim().length===0)&&(yield i,s+=1)}}var ao=512*1024,Id=256*1024;async function Ld(t,e){if(e<=ao)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Buffer.alloc(ao),{bytesRead:r}=await n.read(s,0,ao,0);return s.toString("utf-8",0,r)}finally{await n.close()}}async function Nd(t,e){if(e<=Id)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let s=Math.max(0,e-Id),r=Buffer.alloc(e-s),{bytesRead:i}=await n.read(r,0,r.length,s);return r.toString("utf-8",0,i)}finally{await n.close()}}function Ad(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function pS(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,s=typeof n?.type=="string"?n.type:"",r=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&s==="danger-full-access")return"autoApprove";if(e==="on-request"&&s==="workspace-write")return r?.length?"normal":"plan"}function hS(t){return t?.type==="permission-mode"?Ad(t.permissionMode):Ad(t?.permissionMode)}function gS(t){if(t?.type==="turn_context")return pS(t.payload)}function mS(t){if(t?.type!=="event_msg"||t.payload?.type!=="token_count")return;let e=t.payload.info;if(!e||typeof e!="object")return;let n=e.last_token_usage;if(!n||typeof n!="object")return;let s=Number(n.input_tokens),r=Number(n.output_tokens);if(!Number.isFinite(s)||!Number.isFinite(r))return;let i=Number(e.model_context_window);return{inputTokens:s,outputTokens:r,...Number.isFinite(i)&&i>0?{contextWindowTokens:i}:{}}}async function yS(t,e){let n,s,r=await Nd(t,e);for(let i of r.split(`
102
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=gS(o);a&&(n=a);let l=mS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function Td(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.input_tokens??e.inputTokens),s=Number(e.output_tokens??e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.cache_creation_input_tokens??e.cacheCreationInputTokens),i=Number(e.cache_read_input_tokens??e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(r)?{cacheCreationInputTokens:r}:{},...Number.isFinite(i)?{cacheReadInputTokens:i}:{}}}function vS(t){return t?.type==="assistant"?Td(t.message?.usage??t.usage):Td(t?.toolUseResult?.usage)}async function Od(t,e){let n,s,r=await Nd(t,e);for(let i of r.split(`
103
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=hS(o);a&&(n=a);let l=vS(o);l&&(s=l)}return{approvalMode:n,lastUsage:s}}function mo(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 Dd(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?mo(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function tr(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 SS=/^\[Attached image: ([^\n]+)\]$/gm;function _S(t){let e=[],n=new Set;for(let s of t.matchAll(SS)){let r=s[1]?.trim();!r||n.has(r)||(n.add(r),e.push(r))}return e}function bS(t){if(t.role!=="user")return t;let e=[...t.images??[],..._S(t.content)].filter((n,s,r)=>n&&r.indexOf(n)===s);return e.length?{...t,images:e}:t}var wS=["<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 IS(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?wS.some(s=>n.startsWith(s)):!1}function nr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=tr(t.message.content);return IS(t,e)?"":e}function AS(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function TS(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(s=>!s||typeof s!="object"?"":typeof s.text=="string"?s.text:typeof s.content=="string"?s.content:"").filter(Boolean).join(`
104
104
  `):""}).filter(Boolean).join(`
105
- `):""}function TS(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
106
- `):""}function Td(t){if(typeof t=="string")return t;let e=TS(t);return e||(Array.isArray(t)&&t.length>0&&t.every(s=>s&&typeof s=="object"&&s.type==="tool_reference")?"":JSON.stringify(t))}var CS=/Claude requested permissions to (?:edit|write to) (.+?) which is a sensitive file\.?$/i;function kS(t){let n=t.match(CS)?.[1]?.trim();return n||null}function xS(t){return{role:"assistant",type:"info",historyKey:`claude-sensitive-file:${t}`,content:`Vibelet \u63D0\u793A\uFF1AClaude \u628A ${t} \u89C6\u4E3A\u654F\u611F\u8DEF\u5F84\u3002\u8FD9\u7C7B\u6279\u51C6\u65E0\u6CD5\u4ECE\u5DF2\u6709\u4F1A\u8BDD\u8BB0\u5F55\u91CC\u8865\u56DE\u5230 Vibelet\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u8FD9\u6B21\u4FEE\u6539\u5E76\u5728 Claude \u4E2D\u660E\u786E\u6279\u51C6\uFF1B\u5982\u679C\u5E0C\u671B\u5728 Vibelet \u91CC\u770B\u5230\u5BA1\u6279\u5F39\u7A97\uFF0C\u8BF7\u4ECE Vibelet \u542F\u52A8\u6216\u7EE7\u7EED\u8FD9\u4E2A\u4F1A\u8BDD\u3002`}}function RS(t){let e=AS(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 Dd(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Ys(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,lastUsage:t.lastUsage,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:no()}}function Ot(t,e){let n=(0,U.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 ES(t,e){let n=await Md(t,e),s=Pd(n,64),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(!r&&typeof d.cwd=="string"&&(r=d.cwd),!i&&typeof d.sessionId=="string"&&(i=d.sessionId),o||(o=rt([d.customTitle,d.summary])),!l){let f=er(d),h=rt([],f);h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await Nd(t,e);return{sessionId:i||Ot("claude",t)||(0,U.basename)(t,".jsonl"),cwd:r,title:o??l??rt([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function PS(t,e){let n=await Md(t,e),s=Pd(n,96),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(r||(r=d.payload?.cwd??d.cwd??""),i||(i=d.payload?.id??d.id??""),o||(o=rt([d.payload?.title,d.title])),!l){let f=Od(d),h=f&&!Dd(f)?rt([],f):void 0;h&&(a=f,l=h)}if(r&&(o||l))break}if(!r)return null;let u=await mS(t,e);return{sessionId:i||Ot("codex",t)||(0,U.basename)(t,".jsonl"),cwd:r,title:o??l??rt([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function ot(t,e){let n=await(0,O.stat)(t).catch(()=>null);if(!n)return null;try{let s=n.size;if(e==="claude"){let i=await ES(t,s);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,lastUsage:i.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let r=await PS(t,s);return r?{sessionId:r.sessionId,agent:e,cwd:r.cwd,title:r.title,approvalMode:r.approvalMode,lastUsage:r.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Cd(t,e){let n=(0,U.join)((0,ye.homedir)(),".claude","projects");try{let s;t?s=[Rd(t)]:s=(await(0,O.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let r=[];for(let l of s){let u=(0,U.join)(n,l),c=await(0,O.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&r.push((0,U.join)(u,d))}let i=await lt(r,at,async l=>{let u=await(0,O.stat)(l).catch(()=>null);return{path:l,mtimeMs:u?.mtimeMs??0}});return i.sort((l,u)=>u.mtimeMs-l.mtimeMs),(await lt(i,at,async l=>{let u=await ot(l.path,"claude");return u&&e&&e.push(Ys(u)),u})).filter(l=>l!==null).map(l=>Ys(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(s){return Te.warn({error:String(s)},"failed to list claude sessions"),[]}}async function kd(t,e){try{let n=await po(),s=await lt(n,at,async i=>{let o=await ot(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Ys(o)),o});return dS(s.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),s.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Ys(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Te.warn({error:String(n)},"failed to list codex sessions"),[]}}async function rd(t){if(!t)return null;let e=`codex-latest:${(0,ye.homedir)()}`,n=Js.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Qs||(Qs=(async()=>{let i=await po(),o=await lt(i,at,async l=>{let u=await ot(l.path,"codex");return u?{cwd:u.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:u.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return Js.set(e,a),a})().finally(()=>{Qs=null}));let r=(await Qs).get(t);return r?{sessionId:r.sessionId,filePath:r.path}:null}async function Dn(t,e,n){let r=`list:${(0,ye.homedir)()}:${t??"all"}:${e??""}`,i=oo.get(r);if(i)return i;let o=so.get(r);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Cd(e,n);else if(t==="codex")l=await kd(e,n);else{let[u,c]=await Promise.all([Cd(e,n),kd(e,n)]);l=[...u,...c].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return oo.set(r,l),l})();return so.set(r,a),a.finally(()=>so.delete(r)),a}async function bd(t,e,n){let r=`search:${(0,ye.homedir)()}:${t}:${e??"all"}:${n??"all"}`,i=ao.get(r);if(i)return i;let o=ro.get(r);if(o)return o;let a=(async()=>{let l=new Set,u=t.toLowerCase(),c=n??0;function d(g){if(c<=0)return g;let m=g.findIndex(p=>p.mtimeMs<c);return m===-1?g:g.slice(0,m)}async function f(){try{let g=await cS(),m=d(await Ed(g)),p=await lt(m,at,y=>xd(y.path,u,"claude"));for(let y of p)y&&l.add(y)}catch(g){Te.warn({error:String(g)},"failed to search claude files")}}async function h(){try{let g=d(await po()),m=await lt(g,at,p=>xd(p.path,u,"codex"));for(let p of m)p&&l.add(p)}catch(g){Te.warn({error:String(g)},"failed to search codex files")}}return e==="claude"?await f():e==="codex"?await h():await Promise.all([f(),h()]),ao.set(r,l),l})();return ro.set(r,a),a.finally(()=>ro.delete(r)),a}async function xd(t,e,n){let s=(0,lo.createReadStream)(t,{encoding:"utf-8"}),r=(0,co.createInterface)({input:s,crlfDelay:1/0}),i=n==="claude"?MS:LS,o="",a=!1;try{for await(let l of r){if(!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof u.sessionId=="string"&&(o=u.sessionId):o=u.payload?.id??u.id??""),!a){let c=i(u);c&&c.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{r.close(),s.destroy()}return a?o||Ot(n,t):null}function MS(t){return t?.type==="user"&&t.message?.role==="user"?er(t):t?.type==="assistant"&&t.message?.role==="assistant"?Zs(t.message.content):""}function LS(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return ho(t.payload.content)}let e=Od(t);return e||""}async function Ks(t,e){let n=(0,lo.createReadStream)(t,{encoding:"utf-8"}),s=(0,co.createInterface)({input:n,crlfDelay:1/0});try{for await(let r of s){if(!r.trim())continue;let i;try{i=JSON.parse(r)}catch{continue}if(e(i))break}}finally{s.close(),n.destroy()}}async function go(t,e){let n=(0,U.join)((0,ye.homedir)(),".claude","projects"),s=e?Rd(e):null,r=await(0,O.readdir)(n).catch(()=>[]),i=s?[s,...r.filter(o=>o!==s)]:r;for(let o of i){let a=(0,U.join)(n,o,`${t}.jsonl`);if((await(0,O.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Bd(t,e){let n=await go(t,e);if(!n)return;let s=await(0,O.stat)(n).catch(()=>null);return s?.isFile()?(await Nd(n,s.size)).lastUsage:void 0}async function mo(t,e,n){if(e==="claude")return go(t,n);let s=(0,U.join)((0,ye.homedir)(),".codex","sessions");return Ud(s,t)}function NS(t){if(t?.type==="user"&&t.message?.role==="user")return IS(t.message.content)?{kind:"toolResult",...RS(t)?{interrupted:!0}:{}}:er(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Zs(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 OS(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 Ki(t,e){if(e!=="claude")return{};let n=null;try{await Ks(t,s=>{let r=NS(s);r&&(n=r)})}catch(s){return s.code!=="ENOENT"&&Te.warn({filePath:t,error:String(s)},"failed to read session runtime hints"),{}}return OS(n)}async function yo(t,e,n){let s=await mo(t,e,n);return s?Ki(s,e):{}}function DS(t){if(typeof t?.timestamp!="string")return null;let e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}async function Fd(t,e,n,s){if(e!=="codex"||!s||s<=0)return[];let r=await mo(t,e,n);if(!r)return[];let i=[];try{await Ks(r,l=>{let u=DS(l);u!=null&&u<s||i.push(...Bi(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Te.warn({filePath:r,error:String(l)},"failed to read generated file notices"),[]}let o=await Au(i,s),a=Ae(o);return a?[a]:[]}async function Bn(t,e,n){let s=[],r=(i,o)=>{let a=_S(i);if(o?.coalesceConsecutiveAssistant&&a.role==="assistant"){let l=s[s.length-1];if(l?.role==="assistant"&&l.type!=="info"&&a.type!=="info"&&!Iu(l.content)){s[s.length-1]=a;return}}s.push(a)};if(e==="claude")try{let i=await go(t,n);if(i){let o=new Map;await Ks(i,a=>{if(a.type==="assistant"&&a.message?.role==="assistant"&&Array.isArray(a.message.content))for(let l of a.message.content){if(!l||typeof l!="object"||l.type!=="tool_use"||typeof l.id!="string")continue;let u=Es(typeof l.name=="string"?l.name:null,l.input&&typeof l.input=="object"?l.input:null,n);u&&o.set(l.id,u)}if(a.type==="user"&&a.message?.role==="user"){if(Array.isArray(a.message.content))for(let u of a.message.content){if(!u||typeof u!="object"||u.type!=="tool_result")continue;if(u.is_error===!0){let g=Td(u.content),m=kS(g);m&&r(xS(m));continue}let c=typeof u.tool_use_id=="string"?u.tool_use_id:"",d=c?o.get(c):void 0;if(!d)continue;let f=Td(u.content);if(!Ps(a.toolUseResult,f))continue;let h=Ae([d]);h&&r({role:"assistant",content:h})}let l=er(a);l&&r({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=Zs(a.message.content);l&&r({role:"assistant",content:l})}})}}catch(i){Te.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await mo(t,e,n);i&&await Ks(i,o=>{let a=Bi(o,{cwd:n,includePatchCalls:!0}),l=Ae(a);if(l&&r({role:"assistant",content:l}),o.type!=="response_item"||o.payload?.type!=="message")return;let u=o.payload.role;if(u!=="user"&&u!=="assistant")return;let c=ho(o.payload.content);c&&(u==="user"&&Dd(c)||r({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Te.warn({error:String(i)},"failed to read codex session history")}return s}async function Ud(t,e){try{let n=await(0,O.readdir)(t,{withFileTypes:!0});for(let s of n){let r=(0,U.join)(t,s.name);if(s.isDirectory()){let i=await Ud(r,e);if(i)return i}else if(s.name.includes(e)&&s.name.endsWith(".jsonl"))return r}}catch(n){Te.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Ft=require("fs"),Gd=require("path");var BS=500,Hd=200;function Wd(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Hd?e:e.slice(-Hd)}function FS(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 US(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 HS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof n!="string"||n.length===0||typeof s!="string"||s.length===0||n===s||(e[n]=s);return e}function WS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",s=typeof e.toolName=="string"?e.toolName:"",r=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!s||!r)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:s,input:i,description:r,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:s,input:i,description:r}}function qS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"&&e.kind!=="daemon_shutdown"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.softThresholdMs=="number"&&Number.isFinite(e.softThresholdMs)&&(n.softThresholdMs=e.softThresholdMs),typeof e.stopThresholdMs=="number"&&Number.isFinite(e.stopThresholdMs)&&(n.stopThresholdMs=e.stopThresholdMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),typeof e.shutdownReason=="string"&&e.shutdownReason&&(n.shutdownReason=e.shutdownReason),n}function GS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.content!="string"||typeof e.enqueuedAt!="string"||!e.enqueuedAt)return;let n={content:e.content,enqueuedAt:e.enqueuedAt};if(typeof e.clientMessageId=="string"&&e.clientMessageId&&(n.clientMessageId=e.clientMessageId),typeof e.model=="string"&&e.model&&(n.model=e.model),Array.isArray(e.images)){let s=e.images.filter(r=>typeof r=="string"&&r.length>0);s.length>0&&(n.images=s)}return n}function jS(t){if(!Array.isArray(t))return;let e=[];for(let n of t){let s=GS(n);s&&e.push(s)}return e.length>0?e:void 0}function $S(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={at:e.at,humanText:e.humanText};return typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.hardTimeoutMs=="number"&&Number.isFinite(e.hardTimeoutMs)&&(n.hardTimeoutMs=e.hardTimeoutMs),n}function zS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.inputTokens),s=Number(e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.contextWindowTokens),i=Number(e.cacheCreationInputTokens),o=Number(e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(i)&&i>=0?{cacheCreationInputTokens:i}:{},...Number.isFinite(o)&&o>=0?{cacheReadInputTokens:o}:{},...Number.isFinite(r)&&r>0?{contextWindowTokens:r}:{}}}function qd(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Wd(t.acceptedClientMessageIds),interruptedClientMessageIds:Wd(t.interruptedClientMessageIds),pendingApproval:WS(t.pendingApproval),lastUsage:zS(t.lastUsage),interruptReason:qS(t.interruptReason),stallWarning:$S(t.stallWarning),pendingQueue:jS(t.pendingQueue)}}var VS=new Set(["records","deletedSessionIds","sessionAliases","archivedSessionIds"]);function QS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))VS.has(n)||(e[n]=s);return e}function JS(t){if(Array.isArray(t))return{records:t.map(qd),deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(qd):[],deletedSessionIds:FS(e.deletedSessionIds),sessionAliases:HS(e.sessionAliases),archivedSessionIds:US(e.archivedSessionIds)}}return{records:[],deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]}}var tr=class{records;deletedSessionIds;sessionAliases;archivedSessionIds;unknownFields={};debounceTimer=null;constructor(){let e=this.readRawFromDisk(),n=JS(e);this.records=n.records,this.deletedSessionIds=new Set(n.deletedSessionIds),this.sessionAliases=new Map(Object.entries(n.sessionAliases)),this.archivedSessionIds=new Set(n.archivedSessionIds),this.unknownFields=QS(e)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,s=new Set;for(;!s.has(n);){s.add(n);let r=this.sessionAliases.get(n);if(!r||r===n)break;n=r}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(s=>s.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}isArchived(e){let n=this.resolveSessionId(e);return this.archivedSessionIds.has(e)||this.archivedSessionIds.has(n)}getArchivedSessionIds(){return[...this.archivedSessionIds]}setArchived(e,n){let s=this.resolveSessionId(e),r=this.archivedSessionIds.has(e)||this.archivedSessionIds.has(s);return n&&!r?(this.archivedSessionIds.add(s),this.scheduleSave(),!0):!n&&r?(this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(s),this.scheduleSave(),!0):!1}replaceArchivedSessionIds(e){let n=new Set;for(let s of e)typeof s!="string"||s.length===0||n.add(this.resolveSessionId(s));return this.archivedSessionIds=n,this.scheduleSave(),[...this.archivedSessionIds]}mergeArchivedSessionIds(e){for(let n of e)typeof n!="string"||n.length===0||this.archivedSessionIds.add(this.resolveSessionId(n));return this.scheduleSave(),[...this.archivedSessionIds]}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(s=>s.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let s=this.resolveSessionId(n);if(!s||e===s){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,s),this.archivedSessionIds.delete(e)&&this.archivedSessionIds.add(s),this.scheduleSave()}forget(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.delete(e),this.scheduleSave()}remove(e){let n=this.resolveSessionId(e);this.records=this.records.filter(r=>r.sessionId!==e&&r.sessionId!==n);let s=[];for(let[r,i]of this.sessionAliases)(r===e||r===n||i===n)&&(this.sessionAliases.delete(r),s.push(r));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let r of s)this.deletedSessionIds.add(r);this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(n);for(let r of s)this.archivedSessionIds.delete(r);this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},BS)}readRawFromDisk(){try{let e=(0,Ft.readFileSync)(ws,"utf-8");return JSON.parse(e)}catch{return null}}saveToDisk(){(0,Ft.mkdirSync)((0,Gd.dirname)(ws),{recursive:!0}),(0,Ft.writeFileSync)(ws,JSON.stringify({...this.unknownFields,records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases),archivedSessionIds:[...this.archivedSessionIds]},null,2))}};var Ut=require("path"),nr=require("os");function vo(t){return t=t.replace(/^~/,"~"),t==="~"?(0,nr.homedir)():t.startsWith("~/")||t.startsWith("~\\")?(0,Ut.join)((0,nr.homedir)(),t.slice(2)):t}function jd(t){let e=(t??"").trim();return e?vo(e):(0,nr.homedir)()}function YS(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s&&(e=s[1]??e),e}function So(t,e){let n=vo(YS(t));if(!n||(0,Ut.isAbsolute)(n))return n;let s=vo(e??"");return s?(0,Ut.resolve)(s,n):n}var $d={approvalRequestV1:"vibelet.approvalRequest.v1"};var Ht=require("fs"),zd=require("path");function KS(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u")&&(typeof t.locale=="string"||typeof t.locale>"u"))}function XS(t){try{let e=(0,Ht.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(KS):[]}catch{return[]}}function Fn(t,e){(0,Ht.mkdirSync)((0,zd.dirname)(t),{recursive:!0}),(0,Ht.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
- `,"utf8")}var sr=class{constructor(e=tu){this.pushSubscriptionsPath=e;this.records=XS(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}listRecipients(){return this.records.map(e=>({pushToken:e.pushToken,...e.locale?{locale:e.locale}:{}}))}count(){return this.records.length}register(e,n,s){let r=new Date().toISOString(),i=this.records.find(l=>l.deviceId===e),o=s??i?.locale,a={deviceId:e,pushToken:n,platform:"expo",createdAt:i?.createdAt??r,updatedAt:r,...i?.lastSentAt?{lastSentAt:i.lastSentAt}:{},...o?{locale:o}:{}};this.records=[a,...this.records.filter(l=>l.deviceId!==e&&l.pushToken!==n)],Fn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let s=this.records.filter(r=>!(r.deviceId===e&&r.pushToken===n));return s.length===this.records.length?!1:(this.records=s,Fn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(s=>s.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,Fn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),s=new Date().toISOString(),r=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=s,r=!0);r&&Fn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],Fn(this.pushSubscriptionsPath,this.records)}};var K=L.child({module:"push"}),ZS="https://exp.host/--/api/v2/push/send",e_="https://exp.host/--/api/v2/push/getReceipts",t_=[0,1e3,3e3],Un=new sr;function n_(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 s_(t){return new Promise(e=>{setTimeout(e,t)})}function Vd(t){return t==="DeviceNotRegistered"}function r_(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],s=[];for(let[r,i]of t.data.entries()){let o=e[r];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}s.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:s}}function i_(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[s,r]of t.data.entries()){let i=e[s];!i||!r||r.status!=="ok"||typeof r.id!="string"||r.id.length===0||n.set(r.id,i)}return n}function o_(t,e){let n=[],s=[],r=t.data;for(let[i,o]of e.entries()){let a=r?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&s.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:s}}async function a_(t,e,n,s){let r=new Map(t);for(let i of t_){if(r.size===0)return;i>0&&await n(i);let o;try{o=await e(e_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...r.keys()]})})}catch(c){K.error({error:String(c),count:r.size},"push receipt request failed");return}if(!o.ok){K.error({status:o.status,statusText:o.statusText,count:r.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){K.error({count:r.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=o_(a,r);for(let{token:c,receipt:d}of u){let f=d.details?.error;if(K.error({token:c,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Vd(f)){let h=s.unregisterToken(c);K.info({token:c,errorCode:f,removed:h},"push token removed after receipt rejection")}}r=new Map(l.map(c=>[c,r.get(c)]))}r.size>0&&K.warn({pendingReceipts:r.size},"push receipts still pending after polling")}function l_(t){let e=t?.pushStore??Un,n=t?.fetchImpl??globalThis.fetch,s=t?.sleepImpl??s_;return async function(i,o){let a=e.listRecipients();if(a.length===0)return;let l=typeof i=="function"?i:()=>i,u=a.map(d=>d.pushToken),c=a.map(({pushToken:d,locale:f})=>{let{title:h,body:g}=l(f);return{to:d,sound:"default",title:h,body:g,data:o,badge:1,priority:"high",_contentAvailable:!0,...n_(o)&&o.eventType==="approval_request"?{categoryId:$d.approvalRequestV1}:{}}});try{let d=await n(ZS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){K.error({status:d.status,statusText:d.statusText},"push send failed");return}let f=await d.json().catch(()=>null);if(!f){K.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:h,ticketErrors:g}=r_(f,u),m=i_(f,u);for(let{token:p,ticket:y}of g){let C=y.details?.error;if(K.error({token:p,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),Vd(C)){let A=e.unregisterToken(p);K.info({token:p,errorCode:C,removed:A},"push token removed after ticket rejection")}}h.length>0&&(K.debug({count:h.length},"push sent"),e.markSent(h)),m.size>0&&await a_(m,n,s,e)}catch(d){K.error({error:String(d)},"push send error")}}}function _o(t,e,n){Un.register(t,e,n),K.info({deviceId:t,token:e,locale:n,total:Un.count()},"push token registered")}function bo(t,e){let n=Un.unregister(t,e);K.info({deviceId:t,token:e,total:Un.count(),removed:n},"push token unregistered")}var rr=l_();var Yd=require("child_process"),Wt=require("fs"),Wn=require("os"),wo=require("path"),Kd=require("util");var qn=L.child({module:"usage-limits"}),c_=(0,Kd.promisify)(Yd.execFile),u_=6e4,Xd=8e3,d_="https://api.anthropic.com/api/oauth/usage",f_="https://chatgpt.com/backend-api/codex/usage",p_="https://chatgpt.com/backend-api/codex/responses",h_="claude-cli/2.1 (vibelet-daemon)",g_="codex_cli_rs/0.20.0 (vibelet-daemon)",ir=new Map,Hn=null;function m_(){let t=(process.env.VIBE_USAGE_LIMITS??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="disabled"}async function Zd(t,e={}){if(m_())return{limits:null,reason:"disabled"};let n=Date.now(),s=ir.get(t);if(!e.force&&s&&n-s.at<u_)return s.payload;if(s?.inflight)return s.inflight;let r=(t==="claude"?v_():w_()).then(i=>(ir.set(t,{at:Date.now(),payload:i}),i)).catch(i=>{let o=i instanceof Error?i.message:String(i);qn.warn({agent:t,error:o},"usage-limits fetch failed");let a={limits:null,reason:"unknown",detail:o};return ir.set(t,{at:Date.now(),payload:a}),a});return ir.set(t,{at:s?.at??0,payload:s?.payload??{limits:null},inflight:r}),r}async function y_(){if((0,Wn.platform)()==="darwin")try{let{stdout:e}=await c_("security",["find-generic-password","-s","Claude Code-credentials","-w"],{timeout:5e3}),n=e.trim();if(!n)return null;let s=JSON.parse(n);return s.claudeAiOauth??s.oauth??s}catch(e){return qn.debug({error:e instanceof Error?e.message:String(e)},"keychain read failed"),null}let t=(0,wo.join)((0,Wn.homedir)(),".claude",".credentials.json");if(!(0,Wt.existsSync)(t))return null;try{let e=(0,Wt.readFileSync)(t,"utf8"),n=JSON.parse(e);return n.claudeAiOauth??n.oauth??n}catch{return null}}function or(t){if(!t)return;let e=Number(t.utilization);if(Number.isFinite(e))return t.resets_at?{usedPercent:e,resetsAt:t.resets_at}:{usedPercent:e,resetsAt:""}}async function v_(){let t=await y_(),e=t?.accessToken??t?.access_token;if(!e)return{limits:null,reason:"no_credentials"};let n=new AbortController,s=setTimeout(()=>n.abort(),Xd),r;try{r=await fetch(d_,{method:"GET",headers:{Authorization:`Bearer ${e}`,"anthropic-beta":"oauth-2025-04-20","User-Agent":h_,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(s)}if(!r.ok){let a=await r.text().catch(()=>"");return qn.warn({agent:"claude",status:r.status,statusText:r.statusText,bodyPreview:a.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${r.status} ${r.statusText} ${a.slice(0,200)}`}}let i;try{i=await r.json()}catch(a){return{limits:null,reason:"parse_error",detail:a instanceof Error?a.message:String(a)}}return{limits:{agent:"claude",fiveHour:or(i.five_hour),weekly:or(i.seven_day),weeklyOpus:or(i.seven_day_opus),weeklySonnet:or(i.seven_day_sonnet),planType:t?.subscriptionType??t?.rateLimitTier,fetchedAt:Date.now()}}}function S_(){let t=(0,wo.join)((0,Wn.homedir)(),".codex","auth.json");if(!(0,Wt.existsSync)(t))return null;try{return JSON.parse((0,Wt.readFileSync)(t,"utf8"))}catch{return null}}function ar(t){if(!t)return;let e=Number(t.used_percent);if(!Number.isFinite(e))return;let n="";return typeof t.reset_at=="number"&&Number.isFinite(t.reset_at)?n=new Date(t.reset_at*1e3).toISOString():typeof t.reset_after_seconds=="number"&&Number.isFinite(t.reset_after_seconds)&&(n=new Date(Date.now()+t.reset_after_seconds*1e3).toISOString()),{usedPercent:e,resetsAt:n}}function __(t){let e=t.getSetCookie,s=(typeof e=="function"?e.call(t):t.get("set-cookie")?[t.get("set-cookie")]:[]).flatMap(r=>r.split(/,(?=\s*[^;,]+=)/g)).map(r=>r.split(";")[0]?.trim()??"").filter(Boolean);return s.length>0?s.join("; "):null}function b_(t){return Hn?{...t,Cookie:Hn}:t}async function Qd(t,e){try{let n=await fetch(p_,{method:"HEAD",headers:t,signal:e}),s=__(n.headers);s&&(Hn=s)}catch(n){if(e.aborted)throw n;qn.debug({error:n instanceof Error?n.message:String(n)},"usage-limits codex cookie warmup failed")}}async function Jd(t,e){return fetch(f_,{method:"GET",headers:b_(t),signal:e})}async function w_(){let t=S_();if(!t)return{limits:null,reason:"no_credentials"};if(t.auth_mode!=="chatgpt")return{limits:null,reason:"unsupported_auth"};let e=t.tokens?.access_token,n=t.tokens?.account_id;if(!e)return{limits:null,reason:"no_credentials"};let s=new AbortController,r=setTimeout(()=>s.abort(),Xd),i,o={Authorization:`Bearer ${e}`,"User-Agent":g_,Accept:"application/json","OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};n&&(o["chatgpt-account-id"]=n);try{Hn||await Qd(o,s.signal),i=await Jd(o,s.signal),i.status===403&&(i.headers.get("content-type")??"").includes("text/html")&&(await i.text().catch(()=>""),Hn=null,await Qd(o,s.signal),i=await Jd(o,s.signal))}finally{clearTimeout(r)}if(!i.ok){let c=await i.text().catch(()=>"");return qn.warn({agent:"codex",status:i.status,statusText:i.statusText,bodyPreview:c.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${i.status} ${i.statusText} ${c.slice(0,200)}`}}let a;try{a=await i.json()}catch(c){return{limits:null,reason:"parse_error",detail:c instanceof Error?c.message:String(c)}}let l=(a.additional_rate_limits??[]).map(c=>({name:c.limit_name??"",primary:ar(c.rate_limit?.primary_window),secondary:ar(c.rate_limit?.secondary_window)})).filter(c=>c.name&&(c.primary||c.secondary));return{limits:{agent:"codex",fiveHour:ar(a.rate_limit?.primary_window),weekly:ar(a.rate_limit?.secondary_window),additional:l.length?l:void 0,planType:a.plan_type,fetchedAt:Date.now()}}}var w=L.child({module:"manager"}),I_="Done.",A_="Approval required",ef=180,Gt=200,T_=6e4,tf=9e4,C_=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]);function pf(t,e){let n=e?.length?e.map(s=>{let r=s.lastIndexOf("."),i=r>=0?s.slice(r).toLowerCase():"";return`[Attached ${C_.has(i)?"image":"file"}: ${s}]`}).join(`
105
+ `):""}function kS(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
106
+ `):""}function kd(t){if(typeof t=="string")return t;let e=kS(t);return e||(Array.isArray(t)&&t.length>0&&t.every(s=>s&&typeof s=="object"&&s.type==="tool_reference")?"":JSON.stringify(t))}var CS=/Claude requested permissions to (?:edit|write to) (.+?) which is a sensitive file\.?$/i;function xS(t){let n=t.match(CS)?.[1]?.trim();return n||null}function RS(t){return{role:"assistant",type:"info",historyKey:`claude-sensitive-file:${t}`,content:`Vibelet \u63D0\u793A\uFF1AClaude \u628A ${t} \u89C6\u4E3A\u654F\u611F\u8DEF\u5F84\u3002\u8FD9\u7C7B\u6279\u51C6\u65E0\u6CD5\u4ECE\u5DF2\u6709\u4F1A\u8BDD\u8BB0\u5F55\u91CC\u8865\u56DE\u5230 Vibelet\u3002\u8BF7\u91CD\u65B0\u6267\u884C\u8FD9\u6B21\u4FEE\u6539\u5E76\u5728 Claude \u4E2D\u660E\u786E\u6279\u51C6\uFF1B\u5982\u679C\u5E0C\u671B\u5728 Vibelet \u91CC\u770B\u5230\u5BA1\u6279\u5F39\u7A97\uFF0C\u8BF7\u4ECE Vibelet \u542F\u52A8\u6216\u7EE7\u7EED\u8FD9\u4E2A\u4F1A\u8BDD\u3002`}}function ES(t){let e=TS(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 Bd(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Xs(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,lastUsage:t.lastUsage,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:ro()}}function Ot(t,e){let n=(0,U.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 PS(t,e){let n=await Ld(t,e),s=Md(n,64),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(!r&&typeof d.cwd=="string"&&(r=d.cwd),!i&&typeof d.sessionId=="string"&&(i=d.sessionId),o||(o=rt([d.customTitle,d.summary])),!l){let f=nr(d),p=rt([],f);p&&(a=f,l=p)}if(r&&(o||l))break}if(!r)return null;let u=await Od(t,e);return{sessionId:i||Ot("claude",t)||(0,U.basename)(t,".jsonl"),cwd:r,title:o??l??rt([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function MS(t,e){let n=await Ld(t,e),s=Md(n,96),r="",i="",o,a,l;for(let c of s){let d;try{d=JSON.parse(c)}catch{continue}if(r||(r=d.payload?.cwd??d.cwd??""),i||(i=d.payload?.id??d.id??""),o||(o=rt([d.payload?.title,d.title])),!l){let f=Dd(d),p=f&&!Bd(f)?rt([],f):void 0;p&&(a=f,l=p)}if(r&&(o||l))break}if(!r)return null;let u=await yS(t,e);return{sessionId:i||Ot("codex",t)||(0,U.basename)(t,".jsonl"),cwd:r,title:o??l??rt([],a),approvalMode:u.approvalMode,lastUsage:u.lastUsage}}async function ot(t,e){let n=await(0,O.stat)(t).catch(()=>null);if(!n)return null;try{let s=n.size;if(e==="claude"){let i=await PS(t,s);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,lastUsage:i.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let r=await MS(t,s);return r?{sessionId:r.sessionId,agent:e,cwd:r.cwd,title:r.title,approvalMode:r.approvalMode,lastUsage:r.lastUsage,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Cd(t,e){let n=(0,U.join)((0,ye.homedir)(),".claude","projects");try{let s;t?s=[Ed(t)]:s=(await(0,O.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let r=[];for(let l of s){let u=(0,U.join)(n,l),c=await(0,O.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&r.push((0,U.join)(u,d))}let i=await lt(r,at,async l=>{let u=await(0,O.stat)(l).catch(()=>null);return{path:l,mtimeMs:u?.mtimeMs??0}});return i.sort((l,u)=>u.mtimeMs-l.mtimeMs),(await lt(i,at,async l=>{let u=await ot(l.path,"claude");return u&&e&&e.push(Xs(u)),u})).filter(l=>l!==null).map(l=>Xs(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(s){return Te.warn({error:String(s)},"failed to list claude sessions"),[]}}async function xd(t,e){try{let n=await go(),s=await lt(n,at,async i=>{let o=await ot(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Xs(o)),o});return fS(s.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),s.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Xs(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Te.warn({error:String(n)},"failed to list codex sessions"),[]}}async function id(t){if(!t)return null;let e=`codex-latest:${(0,ye.homedir)()}`,n=Ks.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Ys||(Ys=(async()=>{let i=await go(),o=await lt(i,at,async l=>{let u=await ot(l.path,"codex");return u?{cwd:u.cwd,match:{path:l.path,mtimeMs:l.mtimeMs,sessionId:u.sessionId}}:null}),a=new Map;for(let l of o)!l||a.has(l.cwd)||a.set(l.cwd,l.match);return Ks.set(e,a),a})().finally(()=>{Ys=null}));let r=(await Ys).get(t);return r?{sessionId:r.sessionId,filePath:r.path}:null}async function Dn(t,e,n){let r=`list:${(0,ye.homedir)()}:${t??"all"}:${e??""}`,i=lo.get(r);if(i)return i;let o=io.get(r);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Cd(e,n);else if(t==="codex")l=await xd(e,n);else{let[u,c]=await Promise.all([Cd(e,n),xd(e,n)]);l=[...u,...c].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return lo.set(r,l),l})();return io.set(r,a),a.finally(()=>io.delete(r)),a}async function wd(t,e,n){let r=`search:${(0,ye.homedir)()}:${t}:${e??"all"}:${n??"all"}`,i=co.get(r);if(i)return i;let o=oo.get(r);if(o)return o;let a=(async()=>{let l=new Set,u=t.toLowerCase(),c=n??0;function d(g){if(c<=0)return g;let m=g.findIndex(h=>h.mtimeMs<c);return m===-1?g:g.slice(0,m)}async function f(){try{let g=await uS(),m=d(await Pd(g)),h=await lt(m,at,y=>Rd(y.path,u,"claude"));for(let y of h)y&&l.add(y)}catch(g){Te.warn({error:String(g)},"failed to search claude files")}}async function p(){try{let g=d(await go()),m=await lt(g,at,h=>Rd(h.path,u,"codex"));for(let h of m)h&&l.add(h)}catch(g){Te.warn({error:String(g)},"failed to search codex files")}}return e==="claude"?await f():e==="codex"?await p():await Promise.all([f(),p()]),co.set(r,l),l})();return oo.set(r,a),a.finally(()=>oo.delete(r)),a}async function Rd(t,e,n){let s=(0,uo.createReadStream)(t,{encoding:"utf-8"}),r=(0,fo.createInterface)({input:s,crlfDelay:1/0}),i=n==="claude"?LS:NS,o="",a=!1;try{for await(let l of r){if(!l.trim())continue;let u;try{u=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof u.sessionId=="string"&&(o=u.sessionId):o=u.payload?.id??u.id??""),!a){let c=i(u);c&&c.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{r.close(),s.destroy()}return a?o||Ot(n,t):null}function LS(t){return t?.type==="user"&&t.message?.role==="user"?nr(t):t?.type==="assistant"&&t.message?.role==="assistant"?tr(t.message.content):""}function NS(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return mo(t.payload.content)}let e=Dd(t);return e||""}async function Zs(t,e){let n=(0,uo.createReadStream)(t,{encoding:"utf-8"}),s=(0,fo.createInterface)({input:n,crlfDelay:1/0});try{for await(let r of s){if(!r.trim())continue;let i;try{i=JSON.parse(r)}catch{continue}if(e(i))break}}finally{s.close(),n.destroy()}}async function yo(t,e){let n=(0,U.join)((0,ye.homedir)(),".claude","projects"),s=e?Ed(e):null,r=await(0,O.readdir)(n).catch(()=>[]),i=s?[s,...r.filter(o=>o!==s)]:r;for(let o of i){let a=(0,U.join)(n,o,`${t}.jsonl`);if((await(0,O.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Fd(t,e){let n=await yo(t,e);if(!n)return;let s=await(0,O.stat)(n).catch(()=>null);return s?.isFile()?(await Od(n,s.size)).lastUsage:void 0}async function vo(t,e,n){if(e==="claude")return yo(t,n);let s=(0,U.join)((0,ye.homedir)(),".codex","sessions");return Hd(s,t)}function OS(t){if(t?.type==="user"&&t.message?.role==="user")return AS(t.message.content)?{kind:"toolResult",...ES(t)?{interrupted:!0}:{}}:nr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=tr(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 DS(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 Zi(t,e){if(e!=="claude")return{};let n=null;try{await Zs(t,s=>{let r=OS(s);r&&(n=r)})}catch(s){return s.code!=="ENOENT"&&Te.warn({filePath:t,error:String(s)},"failed to read session runtime hints"),{}}return DS(n)}async function So(t,e,n){let s=await vo(t,e,n);return s?Zi(s,e):{}}function BS(t){if(typeof t?.timestamp!="string")return null;let e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}async function Ud(t,e,n,s){if(e!=="codex"||!s||s<=0)return[];let r=await vo(t,e,n);if(!r)return[];let i=[];try{await Zs(r,l=>{let u=BS(l);u!=null&&u<s||i.push(...Ui(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Te.warn({filePath:r,error:String(l)},"failed to read generated file notices"),[]}let o=await Cu(i,s),a=Ae(o);return a?[a]:[]}async function Bn(t,e,n){let s=[],r=(i,o)=>{let a=bS(i);if(o?.coalesceConsecutiveAssistant&&a.role==="assistant"){let l=s[s.length-1];if(l?.role==="assistant"&&l.type!=="info"&&a.type!=="info"&&!ku(l.content)){s[s.length-1]=a;return}}s.push(a)};if(e==="claude")try{let i=await yo(t,n);if(i){let o=new Map;await Zs(i,a=>{if(a.type==="assistant"&&a.message?.role==="assistant"&&Array.isArray(a.message.content))for(let l of a.message.content){if(!l||typeof l!="object"||l.type!=="tool_use"||typeof l.id!="string")continue;let u=Es(typeof l.name=="string"?l.name:null,l.input&&typeof l.input=="object"?l.input:null,n);u&&o.set(l.id,u)}if(a.type==="user"&&a.message?.role==="user"){if(Array.isArray(a.message.content))for(let u of a.message.content){if(!u||typeof u!="object"||u.type!=="tool_result")continue;if(u.is_error===!0){let g=kd(u.content),m=xS(g);m&&r(RS(m));continue}let c=typeof u.tool_use_id=="string"?u.tool_use_id:"",d=c?o.get(c):void 0;if(!d)continue;let f=kd(u.content);if(!Ps(a.toolUseResult,f))continue;let p=Ae([d]);p&&r({role:"assistant",content:p})}let l=nr(a);l&&r({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=tr(a.message.content);l&&r({role:"assistant",content:l})}})}}catch(i){Te.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await vo(t,e,n);i&&await Zs(i,o=>{let a=Ui(o,{cwd:n,includePatchCalls:!0}),l=Ae(a);if(l&&r({role:"assistant",content:l}),o.type!=="response_item"||o.payload?.type!=="message")return;let u=o.payload.role;if(u!=="user"&&u!=="assistant")return;let c=mo(o.payload.content);c&&(u==="user"&&Bd(c)||r({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Te.warn({error:String(i)},"failed to read codex session history")}return s}async function Hd(t,e){try{let n=await(0,O.readdir)(t,{withFileTypes:!0});for(let s of n){let r=(0,U.join)(t,s.name);if(s.isDirectory()){let i=await Hd(r,e);if(i)return i}else if(s.name.includes(e)&&s.name.endsWith(".jsonl"))return r}}catch(n){Te.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Ft=require("fs"),jd=require("path");var FS=500,Wd=200;function qd(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Wd?e:e.slice(-Wd)}function US(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 HS(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 WS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof n!="string"||n.length===0||typeof s!="string"||s.length===0||n===s||(e[n]=s);return e}function qS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",s=typeof e.toolName=="string"?e.toolName:"",r=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!s||!r)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:s,input:i,description:r,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:s,input:i,description:r}}function GS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"&&e.kind!=="daemon_shutdown"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.softThresholdMs=="number"&&Number.isFinite(e.softThresholdMs)&&(n.softThresholdMs=e.softThresholdMs),typeof e.stopThresholdMs=="number"&&Number.isFinite(e.stopThresholdMs)&&(n.stopThresholdMs=e.stopThresholdMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),typeof e.shutdownReason=="string"&&e.shutdownReason&&(n.shutdownReason=e.shutdownReason),n}function jS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.content!="string"||typeof e.enqueuedAt!="string"||!e.enqueuedAt)return;let n={content:e.content,enqueuedAt:e.enqueuedAt};if(typeof e.clientMessageId=="string"&&e.clientMessageId&&(n.clientMessageId=e.clientMessageId),typeof e.model=="string"&&e.model&&(n.model=e.model),Array.isArray(e.images)){let s=e.images.filter(r=>typeof r=="string"&&r.length>0);s.length>0&&(n.images=s)}return n}function $S(t){if(!Array.isArray(t))return;let e=[];for(let n of t){let s=jS(n);s&&e.push(s)}return e.length>0?e:void 0}function zS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={at:e.at,humanText:e.humanText};return typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.hardTimeoutMs=="number"&&Number.isFinite(e.hardTimeoutMs)&&(n.hardTimeoutMs=e.hardTimeoutMs),n}function VS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.inputTokens),s=Number(e.outputTokens);if(!Number.isFinite(n)||!Number.isFinite(s))return;let r=Number(e.contextWindowTokens),i=Number(e.cacheCreationInputTokens),o=Number(e.cacheReadInputTokens);return{inputTokens:n,outputTokens:s,...Number.isFinite(i)&&i>=0?{cacheCreationInputTokens:i}:{},...Number.isFinite(o)&&o>=0?{cacheReadInputTokens:o}:{},...Number.isFinite(r)&&r>0?{contextWindowTokens:r}:{}}}function Gd(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:qd(t.acceptedClientMessageIds),interruptedClientMessageIds:qd(t.interruptedClientMessageIds),pendingApproval:qS(t.pendingApproval),lastUsage:VS(t.lastUsage),interruptReason:GS(t.interruptReason),stallWarning:zS(t.stallWarning),pendingQueue:$S(t.pendingQueue)}}var QS=new Set(["records","deletedSessionIds","sessionAliases","archivedSessionIds"]);function JS(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))QS.has(n)||(e[n]=s);return e}function YS(t){if(Array.isArray(t))return{records:t.map(Gd),deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Gd):[],deletedSessionIds:US(e.deletedSessionIds),sessionAliases:WS(e.sessionAliases),archivedSessionIds:HS(e.archivedSessionIds)}}return{records:[],deletedSessionIds:[],sessionAliases:{},archivedSessionIds:[]}}var sr=class{records;deletedSessionIds;sessionAliases;archivedSessionIds;unknownFields={};debounceTimer=null;constructor(){let e=this.readRawFromDisk(),n=YS(e);this.records=n.records,this.deletedSessionIds=new Set(n.deletedSessionIds),this.sessionAliases=new Map(Object.entries(n.sessionAliases)),this.archivedSessionIds=new Set(n.archivedSessionIds),this.unknownFields=JS(e)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,s=new Set;for(;!s.has(n);){s.add(n);let r=this.sessionAliases.get(n);if(!r||r===n)break;n=r}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(s=>s.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}isArchived(e){let n=this.resolveSessionId(e);return this.archivedSessionIds.has(e)||this.archivedSessionIds.has(n)}getArchivedSessionIds(){return[...this.archivedSessionIds]}setArchived(e,n){let s=this.resolveSessionId(e),r=this.archivedSessionIds.has(e)||this.archivedSessionIds.has(s);return n&&!r?(this.archivedSessionIds.add(s),this.scheduleSave(),!0):!n&&r?(this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(s),this.scheduleSave(),!0):!1}replaceArchivedSessionIds(e){let n=new Set;for(let s of e)typeof s!="string"||s.length===0||n.add(this.resolveSessionId(s));return this.archivedSessionIds=n,this.scheduleSave(),[...this.archivedSessionIds]}mergeArchivedSessionIds(e){for(let n of e)typeof n!="string"||n.length===0||this.archivedSessionIds.add(this.resolveSessionId(n));return this.scheduleSave(),[...this.archivedSessionIds]}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(s=>s.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let s=this.resolveSessionId(n);if(!s||e===s){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,s),this.archivedSessionIds.delete(e)&&this.archivedSessionIds.add(s),this.scheduleSave()}forget(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.delete(e),this.scheduleSave()}remove(e){let n=this.resolveSessionId(e);this.records=this.records.filter(r=>r.sessionId!==e&&r.sessionId!==n);let s=[];for(let[r,i]of this.sessionAliases)(r===e||r===n||i===n)&&(this.sessionAliases.delete(r),s.push(r));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let r of s)this.deletedSessionIds.add(r);this.archivedSessionIds.delete(e),this.archivedSessionIds.delete(n);for(let r of s)this.archivedSessionIds.delete(r);this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},FS)}readRawFromDisk(){try{let e=(0,Ft.readFileSync)(ws,"utf-8");return JSON.parse(e)}catch{return null}}saveToDisk(){(0,Ft.mkdirSync)((0,jd.dirname)(ws),{recursive:!0}),(0,Ft.writeFileSync)(ws,JSON.stringify({...this.unknownFields,records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases),archivedSessionIds:[...this.archivedSessionIds]},null,2))}};var Ut=require("path"),rr=require("os");function _o(t){return t=t.replace(/^~/,"~"),t==="~"?(0,rr.homedir)():t.startsWith("~/")||t.startsWith("~\\")?(0,Ut.join)((0,rr.homedir)(),t.slice(2)):t}function $d(t){let e=(t??"").trim();return e?_o(e):(0,rr.homedir)()}function KS(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let s=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return s&&(e=s[1]??e),e}function bo(t,e){let n=_o(KS(t));if(!n||(0,Ut.isAbsolute)(n))return n;let s=_o(e??"");return s?(0,Ut.resolve)(s,n):n}var zd={approvalRequestV1:"vibelet.approvalRequest.v1"};var Ht=require("fs"),Vd=require("path");function XS(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u")&&(typeof t.locale=="string"||typeof t.locale>"u"))}function ZS(t){try{let e=(0,Ht.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(XS):[]}catch{return[]}}function Fn(t,e){(0,Ht.mkdirSync)((0,Vd.dirname)(t),{recursive:!0}),(0,Ht.writeFileSync)(t,JSON.stringify(e,null,2)+`
107
+ `,"utf8")}var ir=class{constructor(e=ru){this.pushSubscriptionsPath=e;this.records=ZS(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}listRecipients(){return this.records.map(e=>({pushToken:e.pushToken,...e.locale?{locale:e.locale}:{}}))}count(){return this.records.length}register(e,n,s){let r=new Date().toISOString(),i=this.records.find(l=>l.deviceId===e),o=s??i?.locale,a={deviceId:e,pushToken:n,platform:"expo",createdAt:i?.createdAt??r,updatedAt:r,...i?.lastSentAt?{lastSentAt:i.lastSentAt}:{},...o?{locale:o}:{}};this.records=[a,...this.records.filter(l=>l.deviceId!==e&&l.pushToken!==n)],Fn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let s=this.records.filter(r=>!(r.deviceId===e&&r.pushToken===n));return s.length===this.records.length?!1:(this.records=s,Fn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(s=>s.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,Fn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),s=new Date().toISOString(),r=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=s,r=!0);r&&Fn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],Fn(this.pushSubscriptionsPath,this.records)}};var K=L.child({module:"push"}),e_="https://exp.host/--/api/v2/push/send",t_="https://exp.host/--/api/v2/push/getReceipts",n_=[0,1e3,3e3],Un=new ir;function s_(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 r_(t){return new Promise(e=>{setTimeout(e,t)})}function Qd(t){return t==="DeviceNotRegistered"}function i_(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],s=[];for(let[r,i]of t.data.entries()){let o=e[r];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}s.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:s}}function o_(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[s,r]of t.data.entries()){let i=e[s];!i||!r||r.status!=="ok"||typeof r.id!="string"||r.id.length===0||n.set(r.id,i)}return n}function a_(t,e){let n=[],s=[],r=t.data;for(let[i,o]of e.entries()){let a=r?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&s.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:s}}async function l_(t,e,n,s){let r=new Map(t);for(let i of n_){if(r.size===0)return;i>0&&await n(i);let o;try{o=await e(t_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...r.keys()]})})}catch(c){K.error({error:String(c),count:r.size},"push receipt request failed");return}if(!o.ok){K.error({status:o.status,statusText:o.statusText,count:r.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){K.error({count:r.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=a_(a,r);for(let{token:c,receipt:d}of u){let f=d.details?.error;if(K.error({token:c,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Qd(f)){let p=s.unregisterToken(c);K.info({token:c,errorCode:f,removed:p},"push token removed after receipt rejection")}}r=new Map(l.map(c=>[c,r.get(c)]))}r.size>0&&K.warn({pendingReceipts:r.size},"push receipts still pending after polling")}function c_(t){let e=t?.pushStore??Un,n=t?.fetchImpl??globalThis.fetch,s=t?.sleepImpl??r_;return async function(i,o){let a=e.listRecipients();if(a.length===0)return;let l=typeof i=="function"?i:()=>i,u=a.map(d=>d.pushToken),c=a.map(({pushToken:d,locale:f})=>{let{title:p,body:g}=l(f);return{to:d,sound:"default",title:p,body:g,data:o,badge:1,priority:"high",_contentAvailable:!0,...s_(o)&&o.eventType==="approval_request"?{categoryId:zd.approvalRequestV1}:{}}});try{let d=await n(e_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!d.ok){K.error({status:d.status,statusText:d.statusText},"push send failed");return}let f=await d.json().catch(()=>null);if(!f){K.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:p,ticketErrors:g}=i_(f,u),m=o_(f,u);for(let{token:h,ticket:y}of g){let T=y.details?.error;if(K.error({token:h,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),Qd(T)){let I=e.unregisterToken(h);K.info({token:h,errorCode:T,removed:I},"push token removed after ticket rejection")}}p.length>0&&(K.debug({count:p.length},"push sent"),e.markSent(p)),m.size>0&&await l_(m,n,s,e)}catch(d){K.error({error:String(d)},"push send error")}}}function wo(t,e,n){Un.register(t,e,n),K.info({deviceId:t,token:e,locale:n,total:Un.count()},"push token registered")}function Io(t,e){let n=Un.unregister(t,e);K.info({deviceId:t,token:e,total:Un.count(),removed:n},"push token unregistered")}var or=c_();var Kd=require("child_process"),Wt=require("fs"),Wn=require("os"),Ao=require("path"),Xd=require("util");var qn=L.child({module:"usage-limits"}),u_=(0,Xd.promisify)(Kd.execFile),d_=6e4,Zd=8e3,f_="https://api.anthropic.com/api/oauth/usage",p_="https://chatgpt.com/backend-api/codex/usage",h_="https://chatgpt.com/backend-api/codex/responses",g_="claude-cli/2.1 (vibelet-daemon)",m_="codex_cli_rs/0.20.0 (vibelet-daemon)",ar=new Map,Hn=null;function y_(){let t=(process.env.VIBE_USAGE_LIMITS??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="disabled"}async function ef(t,e={}){if(y_())return{limits:null,reason:"disabled"};let n=Date.now(),s=ar.get(t);if(!e.force&&s&&n-s.at<d_)return s.payload;if(s?.inflight)return s.inflight;let r=(t==="claude"?S_():I_()).then(i=>(ar.set(t,{at:Date.now(),payload:i}),i)).catch(i=>{let o=i instanceof Error?i.message:String(i);qn.warn({agent:t,error:o},"usage-limits fetch failed");let a={limits:null,reason:"unknown",detail:o};return ar.set(t,{at:Date.now(),payload:a}),a});return ar.set(t,{at:s?.at??0,payload:s?.payload??{limits:null},inflight:r}),r}async function v_(){if((0,Wn.platform)()==="darwin")try{let{stdout:e}=await u_("security",["find-generic-password","-s","Claude Code-credentials","-w"],{timeout:5e3}),n=e.trim();if(!n)return null;let s=JSON.parse(n);return s.claudeAiOauth??s.oauth??s}catch(e){return qn.debug({error:e instanceof Error?e.message:String(e)},"keychain read failed"),null}let t=(0,Ao.join)((0,Wn.homedir)(),".claude",".credentials.json");if(!(0,Wt.existsSync)(t))return null;try{let e=(0,Wt.readFileSync)(t,"utf8"),n=JSON.parse(e);return n.claudeAiOauth??n.oauth??n}catch{return null}}function lr(t){if(!t)return;let e=Number(t.utilization);if(Number.isFinite(e))return t.resets_at?{usedPercent:e,resetsAt:t.resets_at}:{usedPercent:e,resetsAt:""}}async function S_(){let t=await v_(),e=t?.accessToken??t?.access_token;if(!e)return{limits:null,reason:"no_credentials"};let n=new AbortController,s=setTimeout(()=>n.abort(),Zd),r;try{r=await fetch(f_,{method:"GET",headers:{Authorization:`Bearer ${e}`,"anthropic-beta":"oauth-2025-04-20","User-Agent":g_,Accept:"application/json"},signal:n.signal})}finally{clearTimeout(s)}if(!r.ok){let a=await r.text().catch(()=>"");return qn.warn({agent:"claude",status:r.status,statusText:r.statusText,bodyPreview:a.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${r.status} ${r.statusText} ${a.slice(0,200)}`}}let i;try{i=await r.json()}catch(a){return{limits:null,reason:"parse_error",detail:a instanceof Error?a.message:String(a)}}return{limits:{agent:"claude",fiveHour:lr(i.five_hour),weekly:lr(i.seven_day),weeklyOpus:lr(i.seven_day_opus),weeklySonnet:lr(i.seven_day_sonnet),planType:t?.subscriptionType??t?.rateLimitTier,fetchedAt:Date.now()}}}function __(){let t=(0,Ao.join)((0,Wn.homedir)(),".codex","auth.json");if(!(0,Wt.existsSync)(t))return null;try{return JSON.parse((0,Wt.readFileSync)(t,"utf8"))}catch{return null}}function cr(t){if(!t)return;let e=Number(t.used_percent);if(!Number.isFinite(e))return;let n="";return typeof t.reset_at=="number"&&Number.isFinite(t.reset_at)?n=new Date(t.reset_at*1e3).toISOString():typeof t.reset_after_seconds=="number"&&Number.isFinite(t.reset_after_seconds)&&(n=new Date(Date.now()+t.reset_after_seconds*1e3).toISOString()),{usedPercent:e,resetsAt:n}}function b_(t){let e=t.getSetCookie,s=(typeof e=="function"?e.call(t):t.get("set-cookie")?[t.get("set-cookie")]:[]).flatMap(r=>r.split(/,(?=\s*[^;,]+=)/g)).map(r=>r.split(";")[0]?.trim()??"").filter(Boolean);return s.length>0?s.join("; "):null}function w_(t){return Hn?{...t,Cookie:Hn}:t}async function Jd(t,e){try{let n=await fetch(h_,{method:"HEAD",headers:t,signal:e}),s=b_(n.headers);s&&(Hn=s)}catch(n){if(e.aborted)throw n;qn.debug({error:n instanceof Error?n.message:String(n)},"usage-limits codex cookie warmup failed")}}async function Yd(t,e){return fetch(p_,{method:"GET",headers:w_(t),signal:e})}async function I_(){let t=__();if(!t)return{limits:null,reason:"no_credentials"};if(t.auth_mode!=="chatgpt")return{limits:null,reason:"unsupported_auth"};let e=t.tokens?.access_token,n=t.tokens?.account_id;if(!e)return{limits:null,reason:"no_credentials"};let s=new AbortController,r=setTimeout(()=>s.abort(),Zd),i,o={Authorization:`Bearer ${e}`,"User-Agent":m_,Accept:"application/json","OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};n&&(o["chatgpt-account-id"]=n);try{Hn||await Jd(o,s.signal),i=await Yd(o,s.signal),i.status===403&&(i.headers.get("content-type")??"").includes("text/html")&&(await i.text().catch(()=>""),Hn=null,await Jd(o,s.signal),i=await Yd(o,s.signal))}finally{clearTimeout(r)}if(!i.ok){let c=await i.text().catch(()=>"");return qn.warn({agent:"codex",status:i.status,statusText:i.statusText,bodyPreview:c.slice(0,200)},"usage-limits http error"),{limits:null,reason:"http_error",detail:`HTTP ${i.status} ${i.statusText} ${c.slice(0,200)}`}}let a;try{a=await i.json()}catch(c){return{limits:null,reason:"parse_error",detail:c instanceof Error?c.message:String(c)}}let l=(a.additional_rate_limits??[]).map(c=>({name:c.limit_name??"",primary:cr(c.rate_limit?.primary_window),secondary:cr(c.rate_limit?.secondary_window)})).filter(c=>c.name&&(c.primary||c.secondary));return{limits:{agent:"codex",fiveHour:cr(a.rate_limit?.primary_window),weekly:cr(a.rate_limit?.secondary_window),additional:l.length?l:void 0,planType:a.plan_type,fetchedAt:Date.now()}}}var w=L.child({module:"manager"}),A_="Done.",T_="Approval required",tf=180,Gt=200,k_=6e4,nf=9e4,C_=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]);function hf(t,e){let n=e?.length?e.map(s=>{let r=s.lastIndexOf("."),i=r>=0?s.slice(r).toLowerCase():"";return`[Attached ${C_.has(i)?"image":"file"}: ${s}]`}).join(`
108
108
  `):"";return n?t?`${t}
109
109
 
110
- ${n}`:n:t}function qt(t){return t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},enqueuedAt:e.enqueuedAt}))}function nf(t){return t?.length?t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},prompt:pf(e.content,e.images),enqueuedAt:e.enqueuedAt})):[]}function k_(t,e){let n=t?.length?t:void 0,s=e?.length?e:void 0;return!n||!s?n===s:n.length!==s.length?!1:n.every((r,i)=>r===s[i])}function Io(t,e,n){return{content:t,...e?.length?{images:e}:{},...n!==void 0?{model:n}:{}}}function sf(t,e){return t?t.content===e.content&&k_(t.images,e.images)&&t.model===e.model:!1}var rf=200;function of(t){return t?.replace(/_/g,"-").toLowerCase()?.startsWith("zh")?"zh":"en"}var x_={zh:"Agent \u5361\u4F4F",en:"Agent stalled"},R_={zh:"Agent \u5D29\u6E83",en:"Agent crashed"};function jt(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),s=e%60;return s===0?`${n} \u5206\u949F`:`${n} \u5206 ${s} \u79D2`}function To(t){if(!t)return;let e=t.trim();if(e)return e.length>rf?`${e.slice(0,rf-1)}\u2026`:e}function E_(t,e,n,s){let r=jt(t),i=jt(n),o=jt(e),a=To(s),l=a?`
111
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${a}"\u3002`:"",u=n>e?`Agent \u957F\u65F6\u95F4\u6CA1\u6709\u8F93\u51FA\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\u540E\u88AB\u81EA\u52A8\u505C\u6B62\uFF08${o} \u65F6\u5DF2\u6807\u8BB0\u7591\u4F3C\u5361\u4F4F\uFF09\u3002`:`Agent \u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u9608\u503C\u540E\u88AB\u81EA\u52A8\u505C\u6B62\u3002`;return{kind:"stall_timeout",at:new Date().toISOString(),humanText:`${u}${l}`,...a?{lastPrompt:a}:{},idleMs:t,softThresholdMs:e,stopThresholdMs:n}}function P_(t,e,n){let s=jt(t),r=jt(e),i=n>0?jt(n):void 0;return{at:new Date().toISOString(),humanText:i?`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5982\u679C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\uFF0C\u5C06\u81EA\u52A8\u505C\u6B62\u3002`:`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5F53\u524D\u4E0D\u4F1A\u81EA\u52A8\u505C\u6B62\uFF0C\u4F60\u53EF\u4EE5\u7EE7\u7EED\u7B49\u5F85\u6216\u624B\u52A8\u505C\u6B62\u3002`,idleMs:t,softThresholdMs:e,...n>0?{hardTimeoutMs:n}:{}}}function M_(t,e){let n=To(e),s=n?`
112
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"driver_crash",at:new Date().toISOString(),humanText:`Agent \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${t}\uFF09\u3002${s}`,...n?{lastPrompt:n}:{},exitCode:t}}function L_(t,e){let n=To(e),s=n?`
113
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"daemon_shutdown",at:new Date().toISOString(),humanText:`\u684C\u9762\u7AEF daemon \u5DF2\u91CD\u542F\u6216\u5173\u95ED\uFF0C\u5F53\u524D\u56DE\u590D\u88AB\u4E2D\u65AD\u3002\u70B9\u300C\u7EE7\u7EED\u300D\u8BA9 Agent \u57FA\u4E8E\u5F53\u524D\u72B6\u6001\u63A5\u7740\u505A\u3002${s}`,...n?{lastPrompt:n}:{},...t?{shutdownReason:t}:{}}}function N_(t,e){return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,...Number.isFinite(e.cacheCreationInputTokens)?{cacheCreationInputTokens:e.cacheCreationInputTokens}:Number.isFinite(t?.cacheCreationInputTokens)?{cacheCreationInputTokens:t?.cacheCreationInputTokens}:{},...Number.isFinite(e.cacheReadInputTokens)?{cacheReadInputTokens:e.cacheReadInputTokens}:Number.isFinite(t?.cacheReadInputTokens)?{cacheReadInputTokens:t?.cacheReadInputTokens}:{},...Number.isFinite(e.contextWindowTokens)?{contextWindowTokens:e.contextWindowTokens}:Number.isFinite(t?.contextWindowTokens)?{contextWindowTokens:t?.contextWindowTokens}:{}}:t}function af(t){if(t)return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,...Number.isFinite(t.cacheCreationInputTokens)?{cacheCreationInputTokens:t.cacheCreationInputTokens}:{},...Number.isFinite(t.cacheReadInputTokens)?{cacheReadInputTokens:t.cacheReadInputTokens}:{},...Number.isFinite(t.contextWindowTokens)?{contextWindowTokens:t.contextWindowTokens}:{}}}function O_(t,e){return t?.inputTokens===e?.inputTokens&&t?.outputTokens===e?.outputTokens&&t?.cacheCreationInputTokens===e?.cacheCreationInputTokens&&t?.cacheReadInputTokens===e?.cacheReadInputTokens&&t?.contextWindowTokens===e?.contextWindowTokens}function Ce(...t){let e=[];for(let n of t)if(n?.length)for(let s of n)!s||e.includes(s)||(e.push(s),e.length>Gt&&e.splice(0,e.length-Gt));return e}function lr(t){return t?.length?{acceptedClientMessageIds:Ce(t)}:{}}function G(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,model:t.model,acceptedClientMessageIds:Ce(t.acceptedClientMessageIds),interruptedClientMessageIds:Ce(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,lastUsage:t.lastUsage,managed:t.managed,isResponding:t.isResponding||void 0,interruptReason:t.interruptReason,stallWarning:t.stallWarning,pendingQueue:t.pendingQueue.length>0?qt(t.pendingQueue):void 0}}function lf(t){t.managed||(t.managed=!0)}function cf(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Ls(e)}function uf(t,e,n){return{sessionId:t,agent:e,...n}}function D_(t){return t.startsWith(Oi)}function df(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var cr=class{constructor(e=rr,n=sd){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=gd(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.updateGauges(),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new tr;idleSweepInterval=null;watchdogNowMs=Date.now();lastWatchdogWallClockMs=this.watchdogNowMs;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),T_),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=this.advanceWatchdogClock(Date.now(),"sweep"),n=S.idleTimeoutMs,s=S.turnStallTimeoutMs,r=S.turnStallHardTimeoutMs;if(n<=0&&s<=0)return;let i=3600*1e3;for(let[o,a]of this.sessions){if(!a.active&&!a.driver){if(a.clients.size===0){let u=e-a.lastActivityTs;u>=i&&(w.info({sessionId:a.sessionId,inactiveMs:u},"removing inactive session from memory"),b.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(a),this.sessions.delete(o))}continue}if(!a.active||!a.driver)continue;let l=e-a.lastActivityTs;if(a.isResponding){if(s<=0||a.pendingApproval||l<s)continue;let u=this.getRespondingLivenessHint(a),c=r>0&&l>=r,d=u==="dead";if(!d&&!c){if(!a.stallWarningAt){let m=P_(l,s,r);a.stallWarningAt=e,a.stallWarning=m,this.updateGauges(),w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"responding session exceeded soft stall threshold; waiting before forced stop"),b.increment("driver.stall_warning",{agent:a.agent}),_.emit("driver.stall_warning",{sessionId:a.sessionId,agent:a.agent,idleMs:l,hardTimeoutMs:r||void 0}),this.broadcast(a.sessionId,{type:"session.stall_warning",sessionId:a.sessionId,warning:m}),this.store.upsert(G(a)),this.noteInventoryChanged("session_updated")}continue}let f=d||r<=0?s:r;w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"stopping stalled driver"),b.increment("driver.stall_timeout",{agent:a.agent}),_.emit("driver.stall_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l});let h=E_(l,s,f,a.lastUserMessage);a.interruptReason=h,this.clearStallWarning(a),this.resolvePendingClaudeHookApprovals(a),a.driver.stop(),a.active=!1,a.driver=null,a.isResponding=!1,a.currentReplyText="",delete a.currentTurn,this.updateGauges(),this.broadcast(a.sessionId,{type:"session.interrupted_notice",sessionId:a.sessionId,reason:h});let g=this.buildPushBody(`${a.title||a.sessionId}: ${h.lastPrompt??""}`.trim());this.pushSender(m=>({title:x_[of(m)],body:g}),{sessionId:a.sessionId,agent:a.agent,eventType:"agent_stalled"}),this.touchSession(a.sessionId),this.store.upsert(G(a)),this.noteInventoryChanged("session_updated");continue}a.pendingApproval||n<=0||l<n||(w.info({sessionId:a.sessionId,agent:a.agent,idleMs:l,timeoutMs:n},"stopping idle driver"),b.increment("driver.idle_timeout",{agent:a.agent}),_.emit("driver.idle_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l}),a.driver.stop(),a.active=!1,a.driver=null,this.updateGauges(),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,s,r){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){w.info({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(w.debug({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,r),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,delete e.currentTurn,o.type==="session.done"&&(n==="claude"?(e.lastUsage=af(o.usage),this.reconcileClaudeSessionUsage(e,o.usage)):o.usage&&(e.lastUsage=N_(e.lastUsage,o.usage))),o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!cf(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}w.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender({title:A_,body:this.buildPushBody(`${e.title||e.sessionId}: ${o.description||o.toolName}`)},{sessionId:e.sessionId,agent:e.agent,requestId:o.requestId,eventType:"approval_request"})}n==="claude"&&o.type==="approval.request"&&Ls(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:w.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry"));let a=this.clearStallWarning(e);this.touchSession(e.sessionId,o.type!=="text.delta"||a),(a||o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),o.type==="session.done"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.pendingQueue.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;b.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&cf(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.clearStallWarning(e),l||(e.pendingApproval=void 0),a){let u=M_(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u});let c=this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim());this.pushSender(d=>({title:R_[of(d)],body:c}),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert(G(e)),this.noteInventoryChanged("session_updated")})}async reconcileClaudeSessionUsage(e,n){let s=await Bd(e.sessionId,e.cwd),r=af(s??n);!r||O_(e.lastUsage,r)||(e.lastUsage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"))}remapSessionId(e,n,s){if(!n||n===e.sessionId)return;let r=this.sessions.get(n);if(r&&r!==e){w.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;w.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(G(e)),this.noteInventoryChanged("session_remapped"),s&&this.reply(s,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let s=e.pendingQueue.shift();return s?(s.clientMessageId&&this.rememberAcceptedClientMessage(e,s.clientMessageId),s.model!==void 0&&(e.model=s.model||void 0),e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=s.content,e.currentTurn=Io(s.content,s.images,s.model),e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),this.store.upsert(G(e)),this.broadcastPendingQueue(e),e.driver.sendPrompt(s.prompt,e.model),!0):!1}broadcastPendingQueue(e){this.broadcast(e.sessionId,{type:"session.queue",sessionId:e.sessionId,pending:qt(e.pendingQueue)})}cancelQueuedTurn(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){this.reply(e,n,!1,void 0,"Session not found");return}if(!r){this.reply(e,n,!1,void 0,"clientMessageId required");return}let a=o.pendingQueue.length;o.pendingQueue=o.pendingQueue.filter(u=>u.clientMessageId!==r);let l=a-o.pendingQueue.length;l>0&&(_.emit("session.queue.cancel",{sessionId:s,agent:o.agent,clientMessageId:r,removed:l}),this.store.upsert(G(o)),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.broadcastPendingQueue(o)),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s,removed:l}))}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&Fd(e.sessionId,e.agent,e.cwd,n).then(s=>{for(let r of s)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:r})}).catch(s=>{w.warn({sessionId:e.sessionId,error:String(s)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let s=e.driver,r=e.sessionId,i=e.startupToken,o=b.startTimer("driver.spawn");(async()=>{try{let a=await s.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(r)!==e||e.startupToken!==i||e.driver!==s){w.info({pendingSessionId:r,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,w.info({pendingSessionId:r,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==r&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(r)!==e||e.startupToken!==i){w.info({pendingSessionId:r,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1;let u=e.pendingQueue.length>0;e.pendingQueue=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),u&&this.broadcastPendingQueue(e),w.error({sessionId:r,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,s,r){if(e==="codex"&&n instanceof xn&&r&&n.setModel(r),e!=="claude"||!(n instanceof kn))return;let i=s??(0,Ao.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=Tn){for(let s of e.pendingClaudeHookApprovals.values())s.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&D_(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let s=this.resolveClaudeHookSession(e);return s?(this.touchSession(s.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let s=this.resolveClaudeHookSession(e);if(!s||s.agent!=="claude"||!s.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Tn;if(s.approvalMode==="autoApprove")return df(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return Tn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",u=`${Oi}${l.trim()||(0,Ao.randomUUID)()}`,c=s.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return s.pendingClaudeHookApprovals.set(u,{requestId:u,promise:h,resolve:g=>{s.pendingClaudeHookApprovals.delete(u),f(g)}}),s.pendingApproval={requestId:u,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:s.sessionId,toolName:i}),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"approval.request",sessionId:s.sessionId,requestId:u,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,s){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let r=new Date().toISOString(),i=s?.agent,o=s?.cwd??"",a=s?.approvalMode,l=s?.model,u=s?.pendingApproval,c=s?.title??"",d=s?.createdAt??r,f=s?.lastActivityAt??r,h=s?.lastUsage,g=Ce(s?.acceptedClientMessageIds),m=Ce(s?.interruptedClientMessageIds),p=s?.isResponding,y=s?.interruptReason,C=s?.stallWarning,A=s?[...s.pendingQueue]:[],T=s?"memory":"client",I=this.store.find(e);if(I)i=I.agent,o=I.cwd||o,a=I.approvalMode??a,l=I.model??l,u=I.pendingApproval??u,c=I.title||c,d=I.createdAt||d,f=I.lastActivityAt||f,h=I.lastUsage??h,g=Ce(I.acceptedClientMessageIds,g),m=Ce(I.interruptedClientMessageIds,m),y=y??I.interruptReason,C=C??I.stallWarning,s||(A=nf(I.pendingQueue)),T="record";else if(!s){let R=(await Dn(n??i)).find(X=>X.sessionId===e);R&&(i=R.agent,o=R.cwd||o,c=R.title??c,d=R.createdAt,f=R.lastActivityAt,h=R.lastUsage??h,p=R.runtime.isResponding??p,T="scanner")}if(!i&&n&&(i=n,T=s?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,model:l,pendingApproval:u,title:c,createdAt:d,lastActivityAt:f,lastUsage:h,acceptedClientMessageIds:g,interruptedClientMessageIds:m,source:T,managed:s?.managed??I?.managed,isResponding:p||void 0,...y?{interruptReason:y}:{},...C?{stallWarning:C}:{},pendingQueue:A}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let s of this.sessions.values()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(uf(s.sessionId,s.agent,s.pendingApproval)))}for(let s of this.store.getAll()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(uf(s.sessionId,s.agent,s.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),s=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=s??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(G(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<=ef?n:`${n.slice(0,Math.max(1,ef-3)).trimEnd()}...`:I_}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}currentWatchdogTime(){return this.advanceWatchdogClock(Date.now(),"activity")}getRespondingLivenessHint(e){return e.driver?.getRespondingLivenessHint?.()??"unknown"}clearStallWarning(e){return!e.stallWarning&&!e.stallWarningAt?!1:(e.stallWarning=void 0,e.stallWarningAt=void 0,this.updateGauges(),!0)}dismissStallWarning(e){return e.stallWarning?(e.stallWarning=void 0,this.updateGauges(),!0):!1}advanceWatchdogClock(e,n){let s=Math.max(0,e-this.lastWatchdogWallClockMs);return this.lastWatchdogWallClockMs=e,s<=0?this.watchdogNowMs:s>tf?(n==="sweep"&&w.warn({elapsedWallMs:s,toleratedGapMs:tf},"watchdog gap detected; discounting paused wall-clock time"),this.watchdogNowMs):(this.watchdogNowMs+=s,this.watchdogNowMs)}touchSession(e,n=!0){let s=Date.now(),r=new Date(s).toISOString(),i=this.advanceWatchdogClock(s,"activity"),o=this.sessions.get(e);if(o){o.lastActivityAt=r,o.lastActivityTs=i,n&&this.store.upsert(G(o));return}let a=this.store.find(e);a&&this.store.upsert({...a,lastActivityAt:r})}updateGauges(){let e=0,n=0;for(let s of this.sessions.values())s.active&&e++,s.stallWarning&&n++;b.gauge("session.active",e),b.gauge("session.stall_warning_active",n)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,model:n.model,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,lastUsage:n.lastUsage,...n.pendingApproval||n.stallWarning?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{},...n.stallWarning?{stallWarning:n.stallWarning}:{}});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}resolveSessionRef(e){let n=this.store.resolveSessionId(e);return{requestedSessionId:e,resolvedSessionId:n,remapped:n!==e}}buildResolvedSessionResponseData(e,n){let s=n?{...n}:{};return e.remapped&&(s.sessionId=e.resolvedSessionId,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s:void 0}buildSessionResponseData(e,n,s){let r=s?{...s}:{};return n&&n!==e.requestedSessionId&&(r.sessionId=n,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}canResumeDriverSession(e,n){return!(e==="codex"&&n.startsWith("pending_"))}rememberSessionAlias(e,n){!e||!n||e===n||(this.store.forget(e),this.store.addAlias(e,n),this.noteInventoryChanged("session_remapped"))}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return Dn(e,n)}async handle(e,n){switch(w.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.queue.cancel":this.cancelQueuedTurn(e,n.id,n.sessionId,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.clearInterrupt":this.clearInterrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles,n.sinceMs);break;case"sessions.list":{let s=typeof n.skipGitMetadata=="boolean"?n.skipGitMetadata:void 0;await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles,n.sinceMs,s);break}case"sessions.archiveableManaged":this.listArchiveableManagedSessions(e,n.id);break;case"session.setArchived":this.setSessionArchived(e,n.id,n.sessionId,n.archived);break;case"sessions.archiveSync":this.archiveSync(e,n.id,n.mode,n.archivedSessionIds);break;case"usage.limits.fetch":await this.handleUsageLimitsFetch(e,n.id,n.agent,n.force);break}}async handleUsageLimitsFetch(e,n,s,r){let i=await Zd(s,{force:!!r});this.reply(e,n,!0,i)}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(e){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let n of this.sessions.values()){let s=!1;try{if(this.resolvePendingClaudeHookApprovals(n),this.shouldMarkDaemonShutdownInterrupt(n)){let r=L_(e,n.lastUserMessage);n.interruptReason=r,this.markLatestAcceptedClientMessageInterrupted(n),this.clearStallWarning(n),n.pendingApproval=void 0,n.isResponding=!1,n.currentReplyText="",delete n.currentTurn,this.broadcast(n.sessionId,{type:"session.interrupted_notice",sessionId:n.sessionId,reason:r}),s=!0}n.driver?.stop()}catch(r){w.error({sessionId:n.sessionId,agent:n.agent,error:String(r)},"failed to stop session on shutdown")}n.active=!1,n.driver=null,n.clients.clear(),this.unregisterClaudeHookSession(n),s&&this.store.upsert(G(n))}this.claudeHookSessions.clear(),this.store.flushSync()}shouldMarkDaemonShutdownInterrupt(e){return!e.active||!e.driver?!1:!!(e.isResponding||e.pendingApproval||e.startupInProgress||e.currentTurn||e.currentReplyText)}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Vs({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},s=JSON.stringify(n);for(let r of this.globalClients)r.readyState===1&&r.send(s)}async createSession(e,n,s,r,i,o,a){r=jd(r),w.info({agent:s,cwd:r,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,ff.stat)(r)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${r}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${r}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(s,r)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return w.info({sessionId:u.sessionId,cwd:r},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,s,r,i);w.info("continue mode: no previous sessions found, creating new")}catch(l){w.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(s),u=this.configureDriverBeforeStart(s,l,void 0,a);if(s==="codex"){let g=`pending_${Date.now()}`;w.info({sessionId:g,agent:s,cwd:r},"session created (pending codex startup)"),b.increment("session.create",{agent:s}),_.emit("session.create",{sessionId:g,agent:s,cwd:r,approvalMode:i});let m={sessionId:g,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,pendingQueue:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(g,m),this.registerClaudeHookSession(m),this.store.upsert(G(m)),this.updateGauges(),Xs(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(m,s,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(m,e);return}let c=b.startTimer("driver.spawn"),d=await l.start(r,void 0,i),f=c();w.info({sessionId:d,agent:s,spawnMs:f},"session created"),b.increment("session.create",{agent:s}),_.emit("session.create",{sessionId:d,agent:s,cwd:r,approvalMode:i});let h={sessionId:d,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(G(h)),this.updateGauges(),Xs(),Hs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,s,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){w.error({agent:s,cwd:r,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,s,r,i,o){let a=this.resolveSessionRef(s);if(s=a.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(s);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let h=await Bn(s,r,l.cwd),g=this.annotateHistoryMessages(h,l.acceptedClientMessageIds,l.interruptedClientMessageIds),m=this.currentPartialReplyText(l),p=l.pendingQueue.length>0?qt(l.pendingQueue):void 0;if(h.length>0||m||l.approvalMode||l.pendingApproval||l.stallWarning||p){let y={type:"session.history",sessionId:s,messages:g,...lr(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:m,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval,stallWarning:l.stallWarning,...p?{pendingQueue:p}:{}};e.readyState===1&&e.send(JSON.stringify(y))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:s}));return}let u=this.store.find(s),c=i||u?.cwd||"",d=o??u?.approvalMode,f=u?.title??"Resumed session";try{let h=b.startTimer("driver.spawn"),g=this.createDriver(r),m=this.configureDriverBeforeStart(r,g),p=this.canResumeDriverSession(r,s),y=await g.start(c,p?s:void 0,d),C=h();w.info({sessionId:y,agent:r,spawnMs:C},"session resumed"),b.increment("session.resume",{agent:r}),_.emit("session.resume",{sessionId:y,agent:r,cwd:c});let A={sessionId:y,agent:r,cwd:c,approvalMode:d,model:u?.model,driver:g,clients:new Set([e]),title:f,createdAt:u?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),lastUsage:u?.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:u?.acceptedClientMessageIds??[],interruptedClientMessageIds:u?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:nf(u?.pendingQueue),startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,stallWarning:u?.stallWarning,claudeHookSecret:m,pendingClaudeHookApprovals:new Map};this.sessions.set(y,A),this.rememberSessionAlias(s,y),this.registerClaudeHookSession(A),this.store.upsert(G(A)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(A,r," (resumed)",e),this.restoreDriverPendingApproval(g,A.pendingApproval);let I=await Bn(p?s:y,r,c),D=this.annotateHistoryMessages(I,A.acceptedClientMessageIds,A.interruptedClientMessageIds),R=A.pendingQueue.length>0?qt(A.pendingQueue):void 0;if(I.length>0||A.pendingApproval||A.stallWarning||R){w.info({sessionId:s,historyCount:I.length},"sending history messages");let X={type:"session.history",sessionId:y,messages:D,...lr(A.acceptedClientMessageIds),approvalMode:d,pendingApproval:A.pendingApproval,stallWarning:A.stallWarning,...R?{pendingQueue:R}:{}};e.readyState===1&&e.send(JSON.stringify(X))}this.reply(e,n,!0,this.buildSessionResponseData(a,y,{sessionId:y}))}catch(h){this.reply(e,n,!1,void 0,String(h))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Gt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Gt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Gt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Gt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,s){if(!e.length||!n?.length||!s?.length)return e;let r=new Set(s),i=[];for(let c=0;c<e.length;c+=1)e[c]?.role==="user"&&i.push(c);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,u=i.length-o;for(let c=0;c<o;c+=1){let d=n[l+c];r.has(d)&&a.set(i[u+c],"interrupted")}return a.size===0?e:e.map((c,d)=>c.role==="user"&&a.has(d)?{...c,delivery:"interrupted"}:c)}hasDuplicateInFlightTurn(e,n){return(e.isResponding||e.pendingApproval)&&sf(e.currentTurn,n)?!0:e.pendingQueue.some(s=>sf(s,n))}async sendMessage(e,n,s,r,i,o,a,l){let u=this.resolveSessionRef(s);if(s=u.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(s);if(!c||!c.driver){let p=await this.resolveReconnectSession(s,i,c);if(!p){w.warn({sessionId:s},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:p.agent,source:p.source},"auto-reconnecting session"),b.increment("session.reconnect",{agent:p.agent,source:p.source}),_.emit("session.reconnect",{sessionId:s,agent:p.agent,source:p.source});try{let y=this.createDriver(p.agent),C=this.configureDriverBeforeStart(p.agent,y,c?.claudeHookSecret),A=this.canResumeDriverSession(p.agent,s),T=await y.start(p.cwd,A?s:void 0,p.approvalMode);this.restoreDriverPendingApproval(y,p.pendingApproval),c?(c.approvalMode=p.approvalMode,c.model=p.model,c.pendingApproval=p.pendingApproval,c.driver=y,c.active=!0,c.clients.add(e),c.lastActivityAt=p.lastActivityAt,c.lastUsage=p.lastUsage,c.lastActivityTs=this.currentWatchdogTime(),c.isResponding=!1,c.currentReplyText="",delete c.currentTurn,c.acceptedClientMessageIds=Ce(c.acceptedClientMessageIds,p.acceptedClientMessageIds),c.interruptedClientMessageIds=Ce(c.interruptedClientMessageIds,p.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,(!c.pendingQueue||c.pendingQueue.length===0)&&(c.pendingQueue=p.pendingQueue),c.startupToken=c.startupToken??0,c.claudeHookSecret=C??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,T&&T!==c.sessionId&&this.remapSessionId(c,T)):(c={sessionId:T,agent:p.agent,cwd:p.cwd,approvalMode:p.approvalMode,model:p.model,driver:y,clients:new Set([e]),title:p.title,createdAt:p.createdAt,lastActivityAt:p.lastActivityAt,lastUsage:p.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:p.acceptedClientMessageIds,interruptedClientMessageIds:p.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:p.pendingQueue,startupToken:0,managed:p.managed,pendingApproval:p.pendingApproval,claudeHookSecret:C,pendingClaudeHookApprovals:new Map,interruptReason:p.interruptReason},this.sessions.set(T,c),this.rememberSessionAlias(s,T)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,p.agent," (reconnected)"),this.store.upsert(G(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),s=c.sessionId,c.pendingQueue.length>0&&this.flushBufferedPrompt(c)}catch(y){this.reply(e,n,!1,void 0,`Failed to reconnect: ${y}`);return}}if(c.clients.add(e),o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,clientMessageId:o,duplicate:!0}));return}let d=pf(r,a),f=l!==void 0&&l||void 0,h=Io(r,a,f);if(this.hasDuplicateInFlightTurn(c,h)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,...o?{clientMessageId:o}:{},duplicate:!0})),w.debug({sessionId:s,hasClientMessageId:!!o,imageCount:a?.length??0},"duplicate in-flight session.send suppressed");return}w.info({sessionId:s,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:s,agent:c.agent,messagePreview:r.slice(0,100),imageCount:a?.length??0}),lf(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert(G(c)),this.noteInventoryChanged("session_updated"));let g=this.clearStallWarning(c);if(Nt(c.title)){let p=ji(r,50);p&&p!==c.title&&(c.title=p),this.store.upsert(G(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId),g&&this.noteInventoryChanged("session_updated");let m=p=>{let y={...o?{clientMessageId:o}:{},content:h.content,...h.images?.length?{images:h.images}:{},...f!==void 0?{model:f}:{},prompt:d,enqueuedAt:new Date().toISOString()};c.pendingQueue.push(y),this.store.upsert(G(c)),this.broadcastPendingQueue(c);let C=o?{sessionId:s,clientMessageId:o,queued:!0}:{sessionId:s,queued:!0};this.reply(e,n,!0,this.buildSessionResponseData(u,s,C)),w.debug({sessionId:s,reason:p,queueLength:c.pendingQueue.length},"message enqueued on daemon")};if(l!==void 0&&(c.model=l||void 0),c.pendingApproval){m("pending_approval");return}if(c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,this.noteInventoryChanged("session_updated"),m("startup");return}if(c.isResponding||c.pendingQueue.length>0){m("busy"),c.isResponding||this.flushBufferedPrompt(c);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,c.currentTurn=h,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,s,o?{sessionId:s,clientMessageId:o}:{sessionId:s}))}async sendReconnectSnapshot(e,n,s,r,i,o,a,l,u){try{let c=this.getDeletedSessionIds(),d;try{d=await Vs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(g){w.warn({error:String(g)},"failed to build reconnect snapshot session list"),d={sessions:[],nextCursor:void 0}}d={...d,sessions:this.decorateSessionsWithArchived(d.sessions),inventoryVersion:this.inventoryVersion};let f;if(o&&!c.has(o)){let g=o;o=this.resolveSessionRef(o).resolvedSessionId;let m=a??d.sessions.find(C=>C.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let y=await this.resolveReconnectSession(o,m,p);if(y){let C=await Bn(o,y.agent,p?.cwd??y.cwd),A=this.annotateHistoryMessages(C,p?.acceptedClientMessageIds??y.acceptedClientMessageIds,p?.interruptedClientMessageIds??y.interruptedClientMessageIds),T=p?{}:await yo(o,y.agent,y.cwd),I=!p&&!!T.isResponding,D=I?await this.externalProcessPresenceCheck(o):!1,R=I&&!D?{}:T,X=p?.interruptReason??y.interruptReason,dt=p?.stallWarning??y.stallWarning,Vn=p?.pendingQueue??y.pendingQueue;f={sessionId:o,agent:y.agent,messages:A,...lr(p?.acceptedClientMessageIds??y.acceptedClientMessageIds),isResponding:p?.isResponding??R.isResponding??(I&&!D?void 0:y.isResponding),...D?{externallyResponding:!0}:{},partialReplyText:p?this.currentPartialReplyText(p):R.partialReplyText,approvalMode:p?.approvalMode??y.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{},...X?{interruptReason:X}:{},...dt?{stallWarning:dt}:{},...Vn.length>0?{pendingQueue:qt(Vn)}:{}},g!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:g})}}let h=this.collectReconnectPendingApprovals();b.increment("reconnect.snapshot",{activeSession:f?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:d.sessions,nextCursor:d.nextCursor,inventoryVersion:d.inventoryVersion,...f?{activeSession:f}:{},...h.length>0?{pendingApprovals:h}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,s,r,i){let o=this.resolveSessionRef(s);s=o.resolvedSessionId;let a=this.sessions.get(s),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(r);if(a&&u){a.pendingApproval=void 0,_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(df(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}));return}let c=a?.syntheticApprovalRetries[r];if(a&&c&&Ls(r)){delete a.syntheticApprovalRetries[r],a.pendingApproval=void 0,_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s})),i&&await this.retrySyntheticClaudeApproval(a,c);return}if(a&&!a.driver&&l)try{await this.reviveSessionForApproval(a)}catch(f){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(f)}`);return}if(!a?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),!a.driver.respondApproval(r,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}a.pendingApproval=void 0,this.touchSession(a.sessionId),a.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let s=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",r=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,r,e.claudeHookSecret);await r.start(e.cwd,e.sessionId,s),e.driver=r,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.currentTurn=Io(n.message),e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(G(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:s},"retrying Claude turn after synthetic approval"),r.sendPrompt(n.message,e.model)}catch(s){e.driver=null,e.active=!1,e.isResponding=!1,delete e.currentTurn,e.startupInProgress=!1;let r=e.pendingQueue.length>0;e.pendingQueue=[],e.startupToken+=1,r&&this.broadcastPendingQueue(e),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:e.sessionId,error:String(s)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(s)}`})}}async setApprovalMode(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){let l=this.store.find(s);l?(r===null?delete l.approvalMode:l.approvalMode=r,this.store.upsert(l),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:l.agent,newMode:r},"approval mode changed (inactive session)")):w.info({sessionId:s,newMode:r},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}));return}if(r===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=r,this.store.upsert(G(o)),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:o.agent,oldMode:a,newMode:r},"approval mode changed"),o.driver&&o.driver.setApprovalMode(r),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}))}interrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("session.interrupt",{sessionId:s,agent:i.agent}),!i.driver){if(i.isResponding||i.pendingQueue.length>0){w.info({sessionId:s,agent:i.agent},"interrupting driverless session with stale responding state");let o=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),o&&this.broadcastPendingQueue(i),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})}this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}if(i.startupInProgress){let o=i.isResponding||i.pendingQueue.length>0;w.info({sessionId:s,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session");let a=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),a&&this.broadcastPendingQueue(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}clearInterrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s),o=this.store.find(s),a=!!(o?.interruptReason||o?.stallWarning);if(!i&&!a){this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}let l=!1;i?.interruptReason&&(i.interruptReason=void 0,l=!0),i&&this.dismissStallWarning(i)&&(l=!0),i?(this.store.upsert(G(i)),a&&(l=!0)):a&&o&&(this.store.upsert({...o,interruptReason:void 0,stallWarning:void 0}),l=!0),l&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}stopSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:i.agent},"stopping session"),_.emit("session.stop",{sessionId:s,agent:i.agent}),lf(i);let o=i.isResponding||i.pendingQueue.length>0||i.startupInProgress,a=i.pendingQueue.length>0;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",delete i.currentTurn,i.pendingApproval=void 0,i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),a&&this.broadcastPendingQueue(i),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}deleteSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);i&&(w.info({sessionId:s,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(s)),_.emit("session.delete",{sessionId:s}),this.store.remove(s),this.updateGauges(),Xs(),Hs(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}async sendHistory(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}o&&o.clients.add(e);let l=a?.cwd??o?.cwd??this.store.find(s)?.cwd??"",u=this.store.find(s),c=await Bn(s,r,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),f=a||o?{}:await yo(s,r,l),h=!a&&!!f.isResponding,g=h?await this.externalProcessPresenceCheck(s):!1,m=g?!0:void 0,p=h&&!g?{}:f,y=a?.isResponding??p.isResponding,C=a?this.currentPartialReplyText(a):p.partialReplyText;w.info({sessionId:s,historyCount:c.length,isResponding:y,externallyResponding:m,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let A=o&&o.pendingQueue.length>0?qt(o.pendingQueue):u?.pendingQueue&&u.pendingQueue.length>0?u.pendingQueue:void 0,T={type:"session.history",sessionId:s,messages:d,...lr(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:m,partialReplyText:C,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval,stallWarning:o?.stallWarning??u?.stallWarning,...A?{pendingQueue:A}:{}};e.readyState===1&&e.send(JSON.stringify(T));let I=o?.interruptReason??u?.interruptReason;if(I&&e.readyState===1){let D={type:"session.interrupted_notice",sessionId:s,reason:I};e.send(JSON.stringify(D))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s}))}async listSessions(e,n,s,r,i,o=50,a,l,u,c){try{let d=await Vs({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:c}),f=this.decorateSessionsWithArchived(d.sessions);this.reply(e,n,!0,{...d,sessions:f,inventoryVersion:this.inventoryVersion})}catch(d){this.reply(e,n,!1,void 0,String(d))}}setSessionArchived(e,n,s,r){if(typeof s!="string"||s.length===0){this.reply(e,n,!1,void 0,"sessionId is required");return}this.store.setArchived(s,r===!0)&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,{archived:this.store.isArchived(s)})}archiveSync(e,n,s,r){let i,o=!1;switch(s){case"pushReplace":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.replaceArchivedSessionIds(l),o=u.size!==i.length||i.some(c=>!u.has(c));break}case"pushMerge":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.mergeArchivedSessionIds(l),o=i.some(c=>!u.has(c));break}case"pull":{i=this.store.getArchivedSessionIds();break}default:this.reply(e,n,!1,void 0,`unknown archive sync mode: ${String(s)}`);return}o&&this.noteInventoryChanged("session_updated");let a={archivedSessionIds:i};this.reply(e,n,!0,a)}decorateSessionsWithArchived(e){return e.length===0?e:e.map(n=>({...n,archived:this.store.isArchived(n.sessionId)}))}listArchiveableManagedSessions(e,n){let s=this.getDeletedSessionIds(),r=new Set;for(let o of this.sessions.values())o.managed&&(o.sessionId.startsWith("pending_")||s.has(o.sessionId)||r.add(o.sessionId));for(let o of this.store.getAll())o.managed&&(s.has(o.sessionId)||r.add(o.sessionId));let i={count:r.size,ids:[...r]};this.reply(e,n,!0,i)}createDriver(e){if(S.reviewMock)return new Ns;switch(e){case"claude":return new kn;case"codex":return new xn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let s=this.sessions.get(e);if(!s){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let r=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:s.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(r),a++):l++;if(l>0&&b.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){s.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=s.title||e,c=this.buildPushBody(s.currentReplyText);s.currentReplyText="",this.pushSender({title:u,body:c},{sessionId:e,agent:s.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(s.currentReplyText="")}reply(e,n,s,r,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:s,data:r,error:i};e.send(JSON.stringify(o))}};function Co(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken,t.locale):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var hf=require("child_process");function B_(t,e){return(0,hf.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function F_(t){let e=t.split(`
114
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function gf(t,e=B_){let n;try{n=F_(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(s=>{try{let r=e("ps",["-p",String(s),"-o","command="]);return r?{pid:s,command:r}:{pid:s}}catch{return{pid:s}}})}var $t=require("fs"),ko=require("os"),yf=require("crypto"),vf=require("path");function Sf(t){return(0,yf.randomBytes)(t).toString("base64url")}function U_(){return`d_${Sf(12)}`}function H_(){return(0,ko.hostname)()}function W_(){let t=(0,ko.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function q_(t){return{daemonId:U_(),daemonSecret:Sf(32),displayName:H_(),canonicalHost:W_(),port:t,createdAt:new Date().toISOString()}}function mf(t,e){(0,$t.mkdirSync)((0,vf.dirname)(e),{recursive:!0}),(0,$t.writeFileSync)(e,JSON.stringify(t,null,2)+`
115
- `,"utf8")}function _f(t,e=Zc){try{let s=(0,$t.readFileSync)(e,"utf8"),r=JSON.parse(s);if(typeof r.daemonId=="string"&&typeof r.daemonSecret=="string"&&typeof r.displayName=="string"&&typeof r.canonicalHost=="string"&&typeof r.createdAt=="string"){let i={daemonId:r.daemonId,daemonSecret:r.daemonSecret,displayName:r.displayName,canonicalHost:r.canonicalHost,port:typeof r.port=="number"&&Number.isFinite(r.port)?r.port:t,createdAt:r.createdAt};return i.port!==t&&(i.port=t,mf(i,e)),i}}catch{}let n=q_(t);return mf(n,e),n}var zt=require("crypto"),Vt=require("fs"),wf=require("path");function xo(t){return(0,zt.randomBytes)(t).toString("base64url")}function Ro(t){return(0,zt.createHash)("sha256").update(t).digest("hex")}function bf(t,e){let n=Buffer.from(t),s=Buffer.from(e);return n.length!==s.length?!1:(0,zt.timingSafeEqual)(n,s)}function G_(t){try{let e=(0,Vt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(s=>s&&typeof s.deviceId=="string"&&typeof s.deviceName=="string"&&typeof s.tokenHash=="string"&&typeof s.createdAt=="string"&&typeof s.lastSeenAt=="string"&&(typeof s.revokedAt=="string"||s.revokedAt===null)):[]}catch{return[]}}function Gn(t,e){(0,Vt.mkdirSync)((0,wf.dirname)(t),{recursive:!0}),(0,Vt.writeFileSync)(t,JSON.stringify(e,null,2)+`
116
- `,"utf8")}var ur=class{constructor(e=eu){this.pairingsPath=e;this.records=G_(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let s=`pair_${xo(8)}`,r=xo(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:s,pairNonce:r,expiresAt:i,reusable:n};return this.windows.set(r,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let s=new Date().toISOString(),r=xo(32),i={deviceId:e,deviceName:n,tokenHash:Ro(r),createdAt:s,lastSeenAt:s,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Gn(this.pairingsPath,this.records),r}validatePairToken(e,n,s=!0){let r=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!r)return!1;let i=Ro(n);return bf(r.tokenHash,i)?(s&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let s=Ro(e),r=this.records.find(i=>!i.revokedAt&&bf(i.tokenHash,s));return r?(n&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),r):null}revoke(e){let n=this.records.find(s=>s.deviceId===e&&!s.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Gn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Gn(this.pairingsPath,this.records)}};function dr(t){return Array.isArray(t)?t[0]:t}function If(t){let e=dr(t.headers["x-forwarded-for"]),n=dr(t.headers["cf-connecting-ip"]),s=dr(t.headers["x-real-ip"]),r=e?.split(",")[0]?.trim()||n||s||t.socket.remoteAddress||void 0,i=dr(t.headers["user-agent"]);return{...r?{ip:r}:{},...i?{userAgent:i}:{}}}function j_(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}var $_=["x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","forwarded","via","cf-connecting-ip","cf-ray"];function z_(t){for(let e of $_)if(t[e]!==void 0)return!0;return!1}function ct(t){return j_(t.socket.remoteAddress)&&!z_(t.headers)}function V_(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Eo(t,e){return V_(t)??e}function fr(t,e){return!!(t&&e&&t===e)}function Po(t,e,n,s=!0){return t?fr(t,e)?!0:!!n(t,s):!1}var Af=require("fs");var Q_=new Set(["ws.connect","ws.auth.success"]);function J_(t){try{let n=(0,Af.readFileSync)(t,"utf8").split(`
117
- `),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&Q_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function Tf(t,e=20,n=De){let s=J_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var xf=require("child_process"),Rf=require("fs");function pr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Mo(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Y_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function K_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function X_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function hr(t){return!!t&&!Y_(t)&&!K_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Lo(t){return fe(t.replace(/^https?:\/\//,""))??t}function Z_(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>hr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function eb(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function tb(t){let e=Lo(t);return Mo(e)||e.endsWith(".ts.net")}function nb(t){let e=Lo(t);return X_(e)||e.endsWith(".local")}function sb(t){return Lo(t).endsWith(".trycloudflare.com")}function Cf(t,e){return tb(t)?"tailscale":nb(t)?"local_network":e?"configured_host":"fallback"}function Ef(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function rb(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function ib(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=sb(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function ob(t,e,n){let s=fe(t)||"localhost",r=Z_(e,s);return Ef([{kind:"direct",host:s,port:n,source:Cf(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:Cf(i,!1),stability:"stable"}))])}function Pf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function ab(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&eb(s))for(let i of r)i.internal||i.family!=="IPv4"||hr(i.address)&&(Mo(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function kf(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>Mo(o)&&hr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Mf(t=xf.execFileSync,e=Rf.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(s)}catch{return{fallbackHosts:[]}}}function Lf(t){let e=ob(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?ib(t.relayUrl):null,s=Ef([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:rb(s),port:r.port,connections:s}}function Nf(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...ab(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>hr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Of(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=L.child({module:"daemon"}),jn=L.child({module:"ws"});function lb(){try{let t=JSON.parse(require("fs").readFileSync(nu,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var cb=["-y","vibelet@latest","restart"],Bo=!1;function ub(){let t=process.env.VIBELET_DAEMON_UPDATE_COMMAND||(process.platform==="win32"?"npx.cmd":"npx"),e=cb;if(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON)try{let s=JSON.parse(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON);Array.isArray(s)&&s.every(r=>typeof r=="string")&&(e=s)}catch{}let n=[t==="npx.cmd"?"npx":t,...e].map(s=>/^[A-Za-z0-9_/@:=-]+$/.test(s)?s:JSON.stringify(s)).join(" ");return{command:t,args:e,displayCommand:n}}function db(t,e,n){(0,qe.mkdirSync)(xt,{recursive:!0});let s=null,r=null;try{s=(0,qe.openSync)(yn,"a"),r=(0,qe.openSync)(vn,"a");let i=(0,Ff.spawn)(t,e,{cwd:process.cwd(),env:{...process.env,VIBELET_UPDATE_SOURCE:"app"},detached:!0,stdio:["ignore",s,r]});i.once("error",o=>{Bo=!1,W.error({command:n,error:String(o)},"daemon update spawn failed"),_.emit("daemon.update.spawn_failed",{command:n,error:String(o)})}),i.unref(),W.info({command:n,pid:i.pid},"daemon update spawned"),_.emit("daemon.update.spawned",{command:n,pid:i.pid})}finally{s!==null&&(0,qe.closeSync)(s),r!==null&&(0,qe.closeSync)(r)}}function fb(t,e){let{command:n,args:s,displayCommand:r}=ub();if(Bo){t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!1,alreadyRunning:!0,command:r}}));return}Bo=!0,t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!0,command:r}})),W.info({command:r},"daemon update requested"),_.emit("daemon.update.requested",{command:r});let i=setTimeout(()=>{db(n,s,r)},100);typeof i.unref=="function"&&i.unref()}var j=_f(S.port),te=new cr((t,e)=>rr(t,{daemonId:j.daemonId,canonicalHost:$n().canonicalHost,...e??{}})),ae=new ur,mr=new Set,We=new WeakMap,Df=!1,Wf=Date.now(),Qt=null,gr=null,pb=1e3;function hb(){let t=Mf();return Nf({canonicalHost:j.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Pf(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Hf.networkInterfaces)()})}function $n(){let t=Date.now();if(gr&&gr.expiresAt>t)return gr.value;let e=hb(),n=Lf({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:j.port,relayUrl:S.relayUrl});return gr={value:n,expiresAt:t+pb},n}function gb(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability,n.secure===!0])),e}async function mb(t){let e=JSON.stringify(gb(t));await(0,le.mkdir)(Ie,{recursive:!0}),await Do.default.toFile(Ei,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Do.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});Rt(`
110
+ ${n}`:n:t}function qt(t){return t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},enqueuedAt:e.enqueuedAt}))}function sf(t){return t?.length?t.map(e=>({...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},content:e.content,...e.images?.length?{images:e.images}:{},...e.model?{model:e.model}:{},prompt:hf(e.content,e.images),enqueuedAt:e.enqueuedAt})):[]}function x_(t,e){let n=t?.length?t:void 0,s=e?.length?e:void 0;return!n||!s?n===s:n.length!==s.length?!1:n.every((r,i)=>r===s[i])}function To(t,e,n){return{content:t,...e?.length?{images:e}:{},...n!==void 0?{model:n}:{}}}function rf(t,e){return t?t.content===e.content&&x_(t.images,e.images)&&t.model===e.model:!1}var of=200;function af(t){return t?.replace(/_/g,"-").toLowerCase()?.startsWith("zh")?"zh":"en"}var R_={zh:"Agent \u5361\u4F4F",en:"Agent stalled"},E_={zh:"Agent \u5D29\u6E83",en:"Agent crashed"};function jt(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),s=e%60;return s===0?`${n} \u5206\u949F`:`${n} \u5206 ${s} \u79D2`}function Co(t){if(!t)return;let e=t.trim();if(e)return e.length>of?`${e.slice(0,of-1)}\u2026`:e}function P_(t,e,n,s){let r=jt(t),i=jt(n),o=jt(e),a=Co(s),l=a?`
111
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${a}"\u3002`:"",u=n>e?`Agent \u957F\u65F6\u95F4\u6CA1\u6709\u8F93\u51FA\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\u540E\u88AB\u81EA\u52A8\u505C\u6B62\uFF08${o} \u65F6\u5DF2\u6807\u8BB0\u7591\u4F3C\u5361\u4F4F\uFF09\u3002`:`Agent \u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${i} \u9608\u503C\u540E\u88AB\u81EA\u52A8\u505C\u6B62\u3002`;return{kind:"stall_timeout",at:new Date().toISOString(),humanText:`${u}${l}`,...a?{lastPrompt:a}:{},idleMs:t,softThresholdMs:e,stopThresholdMs:n}}function M_(t,e,n){let s=jt(t),r=jt(e),i=n>0?jt(n):void 0;return{at:new Date().toISOString(),humanText:i?`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5982\u679C\u8D85\u8FC7 ${i} \u4ECD\u672A\u6062\u590D\uFF0C\u5C06\u81EA\u52A8\u505C\u6B62\u3002`:`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${s} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${r} \u540E\u88AB\u6807\u8BB0\u4E3A\u7591\u4F3C\u5361\u4F4F\uFF1B\u5F53\u524D\u4E0D\u4F1A\u81EA\u52A8\u505C\u6B62\uFF0C\u4F60\u53EF\u4EE5\u7EE7\u7EED\u7B49\u5F85\u6216\u624B\u52A8\u505C\u6B62\u3002`,idleMs:t,softThresholdMs:e,...n>0?{hardTimeoutMs:n}:{}}}function L_(t,e){let n=Co(e),s=n?`
112
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"driver_crash",at:new Date().toISOString(),humanText:`Agent \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${t}\uFF09\u3002${s}`,...n?{lastPrompt:n}:{},exitCode:t}}function N_(t,e){let n=Co(e),s=n?`
113
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${n}"\u3002`:"";return{kind:"daemon_shutdown",at:new Date().toISOString(),humanText:`\u684C\u9762\u7AEF daemon \u5DF2\u91CD\u542F\u6216\u5173\u95ED\uFF0C\u5F53\u524D\u56DE\u590D\u88AB\u4E2D\u65AD\u3002\u70B9\u300C\u7EE7\u7EED\u300D\u8BA9 Agent \u57FA\u4E8E\u5F53\u524D\u72B6\u6001\u63A5\u7740\u505A\u3002${s}`,...n?{lastPrompt:n}:{},...t?{shutdownReason:t}:{}}}function O_(t,e){return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,...Number.isFinite(e.cacheCreationInputTokens)?{cacheCreationInputTokens:e.cacheCreationInputTokens}:Number.isFinite(t?.cacheCreationInputTokens)?{cacheCreationInputTokens:t?.cacheCreationInputTokens}:{},...Number.isFinite(e.cacheReadInputTokens)?{cacheReadInputTokens:e.cacheReadInputTokens}:Number.isFinite(t?.cacheReadInputTokens)?{cacheReadInputTokens:t?.cacheReadInputTokens}:{},...Number.isFinite(e.contextWindowTokens)?{contextWindowTokens:e.contextWindowTokens}:Number.isFinite(t?.contextWindowTokens)?{contextWindowTokens:t?.contextWindowTokens}:{}}:t}function lf(t){if(t)return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,...Number.isFinite(t.cacheCreationInputTokens)?{cacheCreationInputTokens:t.cacheCreationInputTokens}:{},...Number.isFinite(t.cacheReadInputTokens)?{cacheReadInputTokens:t.cacheReadInputTokens}:{},...Number.isFinite(t.contextWindowTokens)?{contextWindowTokens:t.contextWindowTokens}:{}}}function D_(t,e){return t?.inputTokens===e?.inputTokens&&t?.outputTokens===e?.outputTokens&&t?.cacheCreationInputTokens===e?.cacheCreationInputTokens&&t?.cacheReadInputTokens===e?.cacheReadInputTokens&&t?.contextWindowTokens===e?.contextWindowTokens}function ke(...t){let e=[];for(let n of t)if(n?.length)for(let s of n)!s||e.includes(s)||(e.push(s),e.length>Gt&&e.splice(0,e.length-Gt));return e}function ur(t){return t?.length?{acceptedClientMessageIds:ke(t)}:{}}function G(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,model:t.model,acceptedClientMessageIds:ke(t.acceptedClientMessageIds),interruptedClientMessageIds:ke(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,lastUsage:t.lastUsage,managed:t.managed,isResponding:t.isResponding||void 0,interruptReason:t.interruptReason,stallWarning:t.stallWarning,pendingQueue:t.pendingQueue.length>0?qt(t.pendingQueue):void 0}}function cf(t){t.managed||(t.managed=!0)}function uf(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Ls(e)}function df(t,e,n){return{sessionId:t,agent:e,...n}}function B_(t){return t.startsWith(Bi)}function ff(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,n=rd){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=md(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.updateGauges(),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new sr;idleSweepInterval=null;watchdogNowMs=Date.now();lastWatchdogWallClockMs=this.watchdogNowMs;globalClients=new Set;inventoryVersion=Date.now();removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),k_),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=this.advanceWatchdogClock(Date.now(),"sweep"),n=S.idleTimeoutMs,s=S.turnStallTimeoutMs,r=S.turnStallHardTimeoutMs;if(n<=0&&s<=0)return;let i=3600*1e3;for(let[o,a]of this.sessions){if(!a.active&&!a.driver){if(a.clients.size===0){let u=e-a.lastActivityTs;u>=i&&(w.info({sessionId:a.sessionId,inactiveMs:u},"removing inactive session from memory"),b.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(a),this.sessions.delete(o))}continue}if(!a.active||!a.driver)continue;let l=e-a.lastActivityTs;if(a.isResponding){if(s<=0||a.pendingApproval||l<s)continue;let u=this.getRespondingLivenessHint(a),c=r>0&&l>=r,d=u==="dead";if(!d&&!c){if(!a.stallWarningAt){let m=M_(l,s,r);a.stallWarningAt=e,a.stallWarning=m,this.updateGauges(),w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"responding session exceeded soft stall threshold; waiting before forced stop"),b.increment("driver.stall_warning",{agent:a.agent}),_.emit("driver.stall_warning",{sessionId:a.sessionId,agent:a.agent,idleMs:l,hardTimeoutMs:r||void 0}),this.broadcast(a.sessionId,{type:"session.stall_warning",sessionId:a.sessionId,warning:m}),this.store.upsert(G(a)),this.noteInventoryChanged("session_updated")}continue}let f=d||r<=0?s:r;w.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:s,turnStallHardTimeoutMs:r,livenessHint:u},"stopping stalled driver"),b.increment("driver.stall_timeout",{agent:a.agent}),_.emit("driver.stall_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l});let p=P_(l,s,f,a.lastUserMessage);a.interruptReason=p,this.clearStallWarning(a),this.resolvePendingClaudeHookApprovals(a),a.driver.stop(),a.active=!1,a.driver=null,a.isResponding=!1,a.currentReplyText="",delete a.currentTurn,this.updateGauges(),this.broadcast(a.sessionId,{type:"session.interrupted_notice",sessionId:a.sessionId,reason:p});let g=this.buildPushBody(`${a.title||a.sessionId}: ${p.lastPrompt??""}`.trim());this.pushSender(m=>({title:R_[af(m)],body:g}),{sessionId:a.sessionId,agent:a.agent,eventType:"agent_stalled"}),this.touchSession(a.sessionId),this.store.upsert(G(a)),this.noteInventoryChanged("session_updated");continue}a.pendingApproval||n<=0||l<n||(w.info({sessionId:a.sessionId,agent:a.agent,idleMs:l,timeoutMs:n},"stopping idle driver"),b.increment("driver.idle_timeout",{agent:a.agent}),_.emit("driver.idle_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l}),a.driver.stop(),a.active=!1,a.driver=null,this.updateGauges(),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,s,r){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){w.info({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(w.debug({agent:n,context:s,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,r),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,delete e.currentTurn,o.type==="session.done"&&(n==="claude"?(e.lastUsage=lf(o.usage),this.reconcileClaudeSessionUsage(e,o.usage)):o.usage&&(e.lastUsage=O_(e.lastUsage,o.usage))),o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!uf(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}w.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender({title:T_,body:this.buildPushBody(`${e.title||e.sessionId}: ${o.description||o.toolName}`)},{sessionId:e.sessionId,agent:e.agent,requestId:o.requestId,eventType:"approval_request"})}n==="claude"&&o.type==="approval.request"&&Ls(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:w.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry"));let a=this.clearStallWarning(e);this.touchSession(e.sessionId,o.type!=="text.delta"||a),(a||o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),o.type==="session.done"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.pendingQueue.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}w.info({agent:n,context:s,exitCode:o,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;b.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&uf(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.clearStallWarning(e),l||(e.pendingApproval=void 0),a){let u=L_(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u});let c=this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim());this.pushSender(d=>({title:E_[af(d)],body:c}),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert(G(e)),this.noteInventoryChanged("session_updated")})}async reconcileClaudeSessionUsage(e,n){let s=await Fd(e.sessionId,e.cwd),r=lf(s??n);!r||D_(e.lastUsage,r)||(e.lastUsage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"))}remapSessionId(e,n,s){if(!n||n===e.sessionId)return;let r=this.sessions.get(n);if(r&&r!==e){w.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;w.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(G(e)),this.noteInventoryChanged("session_remapped"),s&&this.reply(s,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let s=e.pendingQueue.shift();return s?(s.clientMessageId&&this.rememberAcceptedClientMessage(e,s.clientMessageId),s.model!==void 0&&(e.model=s.model||void 0),e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=s.content,e.currentTurn=To(s.content,s.images,s.model),e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),this.store.upsert(G(e)),this.broadcastPendingQueue(e),e.driver.sendPrompt(s.prompt,e.model),!0):!1}broadcastPendingQueue(e){this.broadcast(e.sessionId,{type:"session.queue",sessionId:e.sessionId,pending:qt(e.pendingQueue)})}cancelQueuedTurn(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){this.reply(e,n,!1,void 0,"Session not found");return}if(!r){this.reply(e,n,!1,void 0,"clientMessageId required");return}let a=o.pendingQueue.length;o.pendingQueue=o.pendingQueue.filter(u=>u.clientMessageId!==r);let l=a-o.pendingQueue.length;l>0&&(_.emit("session.queue.cancel",{sessionId:s,agent:o.agent,clientMessageId:r,removed:l}),this.store.upsert(G(o)),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.broadcastPendingQueue(o)),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s,removed:l}))}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&Ud(e.sessionId,e.agent,e.cwd,n).then(s=>{for(let r of s)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:r})}).catch(s=>{w.warn({sessionId:e.sessionId,error:String(s)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let s=e.driver,r=e.sessionId,i=e.startupToken,o=b.startTimer("driver.spawn");(async()=>{try{let a=await s.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(r)!==e||e.startupToken!==i||e.driver!==s){w.info({pendingSessionId:r,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,w.info({pendingSessionId:r,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==r&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(r)!==e||e.startupToken!==i){w.info({pendingSessionId:r,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1;let u=e.pendingQueue.length>0;e.pendingQueue=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),u&&this.broadcastPendingQueue(e),w.error({sessionId:r,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,s,r){if(e==="codex"&&n instanceof xn&&r&&n.setModel(r),e!=="claude"||!(n instanceof Cn))return;let i=s??(0,ko.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=Tn){for(let s of e.pendingClaudeHookApprovals.values())s.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&B_(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let s=this.resolveClaudeHookSession(e);return s?(this.touchSession(s.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let s=this.resolveClaudeHookSession(e);if(!s||s.agent!=="claude"||!s.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Tn;if(s.approvalMode==="autoApprove")return ff(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return Tn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",u=`${Bi}${l.trim()||(0,ko.randomUUID)()}`,c=s.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return s.pendingClaudeHookApprovals.set(u,{requestId:u,promise:p,resolve:g=>{s.pendingClaudeHookApprovals.delete(u),f(g)}}),s.pendingApproval={requestId:u,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:s.sessionId,toolName:i}),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"approval.request",sessionId:s.sessionId,requestId:u,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,s){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let r=new Date().toISOString(),i=s?.agent,o=s?.cwd??"",a=s?.approvalMode,l=s?.model,u=s?.pendingApproval,c=s?.title??"",d=s?.createdAt??r,f=s?.lastActivityAt??r,p=s?.lastUsage,g=ke(s?.acceptedClientMessageIds),m=ke(s?.interruptedClientMessageIds),h=s?.isResponding,y=s?.interruptReason,T=s?.stallWarning,I=s?[...s.pendingQueue]:[],k=s?"memory":"client",A=this.store.find(e);if(A)i=A.agent,o=A.cwd||o,a=A.approvalMode??a,l=A.model??l,u=A.pendingApproval??u,c=A.title||c,d=A.createdAt||d,f=A.lastActivityAt||f,p=A.lastUsage??p,g=ke(A.acceptedClientMessageIds,g),m=ke(A.interruptedClientMessageIds,m),y=y??A.interruptReason,T=T??A.stallWarning,s||(I=sf(A.pendingQueue)),k="record";else if(!s){let x=(await Dn(n??i)).find(X=>X.sessionId===e);x&&(i=x.agent,o=x.cwd||o,c=x.title??c,d=x.createdAt,f=x.lastActivityAt,p=x.lastUsage??p,h=x.runtime.isResponding??h,k="scanner")}if(!i&&n&&(i=n,k=s?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,model:l,pendingApproval:u,title:c,createdAt:d,lastActivityAt:f,lastUsage:p,acceptedClientMessageIds:g,interruptedClientMessageIds:m,source:k,managed:s?.managed??A?.managed,isResponding:h||void 0,...y?{interruptReason:y}:{},...T?{stallWarning:T}:{},pendingQueue:I}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let s of this.sessions.values()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(df(s.sessionId,s.agent,s.pendingApproval)))}for(let s of this.store.getAll()){if(!s.pendingApproval)continue;let r=`${s.agent}:${s.sessionId}:${s.pendingApproval.requestId}`;n.has(r)||(n.add(r),e.push(df(s.sessionId,s.agent,s.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),s=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",delete e.currentTurn,e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=s??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(G(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<=tf?n:`${n.slice(0,Math.max(1,tf-3)).trimEnd()}...`:A_}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}currentWatchdogTime(){return this.advanceWatchdogClock(Date.now(),"activity")}getRespondingLivenessHint(e){return e.driver?.getRespondingLivenessHint?.()??"unknown"}clearStallWarning(e){return!e.stallWarning&&!e.stallWarningAt?!1:(e.stallWarning=void 0,e.stallWarningAt=void 0,this.updateGauges(),!0)}dismissStallWarning(e){return e.stallWarning?(e.stallWarning=void 0,this.updateGauges(),!0):!1}advanceWatchdogClock(e,n){let s=Math.max(0,e-this.lastWatchdogWallClockMs);return this.lastWatchdogWallClockMs=e,s<=0?this.watchdogNowMs:s>nf?(n==="sweep"&&w.warn({elapsedWallMs:s,toleratedGapMs:nf},"watchdog gap detected; discounting paused wall-clock time"),this.watchdogNowMs):(this.watchdogNowMs+=s,this.watchdogNowMs)}touchSession(e,n=!0){let s=Date.now(),r=new Date(s).toISOString(),i=this.advanceWatchdogClock(s,"activity"),o=this.sessions.get(e);if(o){o.lastActivityAt=r,o.lastActivityTs=i,n&&this.store.upsert(G(o));return}let a=this.store.find(e);a&&this.store.upsert({...a,lastActivityAt:r})}updateGauges(){let e=0,n=0;for(let s of this.sessions.values())s.active&&e++,s.stallWarning&&n++;b.gauge("session.active",e),b.gauge("session.stall_warning_active",n)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,model:n.model,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,lastUsage:n.lastUsage,...n.pendingApproval||n.stallWarning?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{},...n.stallWarning?{stallWarning:n.stallWarning}:{}});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}resolveSessionRef(e){let n=this.store.resolveSessionId(e);return{requestedSessionId:e,resolvedSessionId:n,remapped:n!==e}}buildResolvedSessionResponseData(e,n){let s=n?{...n}:{};return e.remapped&&(s.sessionId=e.resolvedSessionId,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s:void 0}buildSessionResponseData(e,n,s){let r=s?{...s}:{};return n&&n!==e.requestedSessionId&&(r.sessionId=n,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}canResumeDriverSession(e,n){return!(e==="codex"&&n.startsWith("pending_"))}rememberSessionAlias(e,n){!e||!n||e===n||(this.store.forget(e),this.store.addAlias(e,n),this.noteInventoryChanged("session_remapped"))}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return Dn(e,n)}async handle(e,n){switch(w.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.queue.cancel":this.cancelQueuedTurn(e,n.id,n.sessionId,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.clearInterrupt":this.clearInterrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":{let s=typeof n.skipGitMetadata=="boolean"?n.skipGitMetadata:void 0;await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles,n.sinceMs,s);break}case"sessions.list":{let s=typeof n.skipGitMetadata=="boolean"?n.skipGitMetadata:void 0;await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles,n.sinceMs,s);break}case"sessions.gitMetadata":await this.fetchGitMetadata(e,n.id,n.cwds);break;case"sessions.archiveableManaged":this.listArchiveableManagedSessions(e,n.id);break;case"session.setArchived":this.setSessionArchived(e,n.id,n.sessionId,n.archived);break;case"sessions.archiveSync":this.archiveSync(e,n.id,n.mode,n.archivedSessionIds);break;case"usage.limits.fetch":await this.handleUsageLimitsFetch(e,n.id,n.agent,n.force);break}}async handleUsageLimitsFetch(e,n,s,r){let i=await ef(s,{force:!!r});this.reply(e,n,!0,i)}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(e){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let n of this.sessions.values()){let s=!1;try{if(this.resolvePendingClaudeHookApprovals(n),this.shouldMarkDaemonShutdownInterrupt(n)){let r=N_(e,n.lastUserMessage);n.interruptReason=r,this.markLatestAcceptedClientMessageInterrupted(n),this.clearStallWarning(n),n.pendingApproval=void 0,n.isResponding=!1,n.currentReplyText="",delete n.currentTurn,this.broadcast(n.sessionId,{type:"session.interrupted_notice",sessionId:n.sessionId,reason:r}),s=!0}n.driver?.stop()}catch(r){w.error({sessionId:n.sessionId,agent:n.agent,error:String(r)},"failed to stop session on shutdown")}n.active=!1,n.driver=null,n.clients.clear(),this.unregisterClaudeHookSession(n),s&&this.store.upsert(G(n))}this.claudeHookSessions.clear(),this.store.flushSync()}shouldMarkDaemonShutdownInterrupt(e){return!e.active||!e.driver?!1:!!(e.isResponding||e.pendingApproval||e.startupInProgress||e.currentTurn||e.currentReplyText)}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Js({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},s=JSON.stringify(n);for(let r of this.globalClients)r.readyState===1&&r.send(s)}async createSession(e,n,s,r,i,o,a){r=$d(r),w.info({agent:s,cwd:r,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,pf.stat)(r)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${r}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${r}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(s,r)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return w.info({sessionId:u.sessionId,cwd:r},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,s,r,i);w.info("continue mode: no previous sessions found, creating new")}catch(l){w.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(s),u=this.configureDriverBeforeStart(s,l,void 0,a);if(s==="codex"){let g=`pending_${Date.now()}`;w.info({sessionId:g,agent:s,cwd:r},"session created (pending codex startup)"),b.increment("session.create",{agent:s}),_.emit("session.create",{sessionId:g,agent:s,cwd:r,approvalMode:i});let m={sessionId:g,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,pendingQueue:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(g,m),this.registerClaudeHookSession(m),this.store.upsert(G(m)),this.updateGauges(),er(),qs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(m,s,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(m,e);return}let c=b.startTimer("driver.spawn"),d=await l.start(r,void 0,i),f=c();w.info({sessionId:d,agent:s,spawnMs:f},"session created"),b.increment("session.create",{agent:s}),_.emit("session.create",{sessionId:d,agent:s,cwd:r,approvalMode:i});let p={sessionId:d,agent:s,cwd:r,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,p),this.registerClaudeHookSession(p),this.store.upsert(G(p)),this.updateGauges(),er(),qs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,s,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){w.error({agent:s,cwd:r,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,s,r,i,o){let a=this.resolveSessionRef(s);if(s=a.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(s);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let p=await Bn(s,r,l.cwd),g=this.annotateHistoryMessages(p,l.acceptedClientMessageIds,l.interruptedClientMessageIds),m=this.currentPartialReplyText(l),h=l.pendingQueue.length>0?qt(l.pendingQueue):void 0;if(p.length>0||m||l.approvalMode||l.pendingApproval||l.stallWarning||h){let y={type:"session.history",sessionId:s,messages:g,...ur(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:m,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval,stallWarning:l.stallWarning,...h?{pendingQueue:h}:{}};e.readyState===1&&e.send(JSON.stringify(y))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:s}));return}let u=this.store.find(s),c=i||u?.cwd||"",d=o??u?.approvalMode,f=u?.title??"Resumed session";try{let p=b.startTimer("driver.spawn"),g=this.createDriver(r),m=this.configureDriverBeforeStart(r,g),h=this.canResumeDriverSession(r,s),y=await g.start(c,h?s:void 0,d),T=p();w.info({sessionId:y,agent:r,spawnMs:T},"session resumed"),b.increment("session.resume",{agent:r}),_.emit("session.resume",{sessionId:y,agent:r,cwd:c});let I={sessionId:y,agent:r,cwd:c,approvalMode:d,model:u?.model,driver:g,clients:new Set([e]),title:f,createdAt:u?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),lastUsage:u?.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:u?.acceptedClientMessageIds??[],interruptedClientMessageIds:u?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:sf(u?.pendingQueue),startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,stallWarning:u?.stallWarning,claudeHookSecret:m,pendingClaudeHookApprovals:new Map};this.sessions.set(y,I),this.rememberSessionAlias(s,y),this.registerClaudeHookSession(I),this.store.upsert(G(I)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(I,r," (resumed)",e),this.restoreDriverPendingApproval(g,I.pendingApproval);let A=await Bn(h?s:y,r,c),D=this.annotateHistoryMessages(A,I.acceptedClientMessageIds,I.interruptedClientMessageIds),x=I.pendingQueue.length>0?qt(I.pendingQueue):void 0;if(A.length>0||I.pendingApproval||I.stallWarning||x){w.info({sessionId:s,historyCount:A.length},"sending history messages");let X={type:"session.history",sessionId:y,messages:D,...ur(I.acceptedClientMessageIds),approvalMode:d,pendingApproval:I.pendingApproval,stallWarning:I.stallWarning,...x?{pendingQueue:x}:{}};e.readyState===1&&e.send(JSON.stringify(X))}this.reply(e,n,!0,this.buildSessionResponseData(a,y,{sessionId:y}))}catch(p){this.reply(e,n,!1,void 0,String(p))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Gt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Gt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Gt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Gt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,s){if(!e.length||!n?.length||!s?.length)return e;let r=new Set(s),i=[];for(let c=0;c<e.length;c+=1)e[c]?.role==="user"&&i.push(c);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,u=i.length-o;for(let c=0;c<o;c+=1){let d=n[l+c];r.has(d)&&a.set(i[u+c],"interrupted")}return a.size===0?e:e.map((c,d)=>c.role==="user"&&a.has(d)?{...c,delivery:"interrupted"}:c)}hasDuplicateInFlightTurn(e,n){return(e.isResponding||e.pendingApproval)&&rf(e.currentTurn,n)?!0:e.pendingQueue.some(s=>rf(s,n))}async sendMessage(e,n,s,r,i,o,a,l){let u=this.resolveSessionRef(s);if(s=u.resolvedSessionId,this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(s);if(!c||!c.driver){let h=await this.resolveReconnectSession(s,i,c);if(!h){w.warn({sessionId:s},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:h.agent,source:h.source},"auto-reconnecting session"),b.increment("session.reconnect",{agent:h.agent,source:h.source}),_.emit("session.reconnect",{sessionId:s,agent:h.agent,source:h.source});try{let y=this.createDriver(h.agent),T=this.configureDriverBeforeStart(h.agent,y,c?.claudeHookSecret),I=this.canResumeDriverSession(h.agent,s),k=await y.start(h.cwd,I?s:void 0,h.approvalMode);this.restoreDriverPendingApproval(y,h.pendingApproval),c?(c.approvalMode=h.approvalMode,c.model=h.model,c.pendingApproval=h.pendingApproval,c.driver=y,c.active=!0,c.clients.add(e),c.lastActivityAt=h.lastActivityAt,c.lastUsage=h.lastUsage,c.lastActivityTs=this.currentWatchdogTime(),c.isResponding=!1,c.currentReplyText="",delete c.currentTurn,c.acceptedClientMessageIds=ke(c.acceptedClientMessageIds,h.acceptedClientMessageIds),c.interruptedClientMessageIds=ke(c.interruptedClientMessageIds,h.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,(!c.pendingQueue||c.pendingQueue.length===0)&&(c.pendingQueue=h.pendingQueue),c.startupToken=c.startupToken??0,c.claudeHookSecret=T??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,k&&k!==c.sessionId&&this.remapSessionId(c,k)):(c={sessionId:k,agent:h.agent,cwd:h.cwd,approvalMode:h.approvalMode,model:h.model,driver:y,clients:new Set([e]),title:h.title,createdAt:h.createdAt,lastActivityAt:h.lastActivityAt,lastUsage:h.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:h.acceptedClientMessageIds,interruptedClientMessageIds:h.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,pendingQueue:h.pendingQueue,startupToken:0,managed:h.managed,pendingApproval:h.pendingApproval,claudeHookSecret:T,pendingClaudeHookApprovals:new Map,interruptReason:h.interruptReason},this.sessions.set(k,c),this.rememberSessionAlias(s,k)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,h.agent," (reconnected)"),this.store.upsert(G(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),s=c.sessionId,c.pendingQueue.length>0&&this.flushBufferedPrompt(c)}catch(y){this.reply(e,n,!1,void 0,`Failed to reconnect: ${y}`);return}}if(c.clients.add(e),o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,clientMessageId:o,duplicate:!0}));return}let d=hf(r,a),f=l!==void 0&&l||void 0,p=To(r,a,f);if(this.hasDuplicateInFlightTurn(c,p)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:s,...o?{clientMessageId:o}:{},duplicate:!0})),w.debug({sessionId:s,hasClientMessageId:!!o,imageCount:a?.length??0},"duplicate in-flight session.send suppressed");return}w.info({sessionId:s,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:s,agent:c.agent,messagePreview:r.slice(0,100),imageCount:a?.length??0}),cf(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert(G(c)),this.noteInventoryChanged("session_updated"));let g=this.clearStallWarning(c);if(Nt(c.title)){let h=zi(r,50);h&&h!==c.title&&(c.title=h),this.store.upsert(G(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId),g&&this.noteInventoryChanged("session_updated");let m=h=>{let y={...o?{clientMessageId:o}:{},content:p.content,...p.images?.length?{images:p.images}:{},...f!==void 0?{model:f}:{},prompt:d,enqueuedAt:new Date().toISOString()};c.pendingQueue.push(y),this.store.upsert(G(c)),this.broadcastPendingQueue(c);let T=o?{sessionId:s,clientMessageId:o,queued:!0}:{sessionId:s,queued:!0};this.reply(e,n,!0,this.buildSessionResponseData(u,s,T)),w.debug({sessionId:s,reason:h,queueLength:c.pendingQueue.length},"message enqueued on daemon")};if(l!==void 0&&(c.model=l||void 0),c.pendingApproval){m("pending_approval");return}if(c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,this.noteInventoryChanged("session_updated"),m("startup");return}if(c.isResponding||c.pendingQueue.length>0){m("busy"),c.isResponding||this.flushBufferedPrompt(c);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=r,c.currentTurn=p,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,s,o?{sessionId:s,clientMessageId:o}:{sessionId:s}))}async sendReconnectSnapshot(e,n,s,r,i,o,a,l,u,c){try{let d=this.getDeletedSessionIds(),f;try{f=await Js({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:d,skipGitMetadata:c})}catch(m){w.warn({error:String(m)},"failed to build reconnect snapshot session list"),f={sessions:[],nextCursor:void 0}}f={...f,sessions:this.decorateSessionsWithArchived(f.sessions),inventoryVersion:this.inventoryVersion};let p;if(o&&!d.has(o)){let m=o;o=this.resolveSessionRef(o).resolvedSessionId;let h=a??f.sessions.find(I=>I.sessionId===o)?.agent,y=this.sessions.get(o);y&&y.clients.add(e);let T=await this.resolveReconnectSession(o,h,y);if(T){let I=await Bn(o,T.agent,y?.cwd??T.cwd),k=this.annotateHistoryMessages(I,y?.acceptedClientMessageIds??T.acceptedClientMessageIds,y?.interruptedClientMessageIds??T.interruptedClientMessageIds),A=y?{}:await So(o,T.agent,T.cwd),D=!y&&!!A.isResponding,x=D?await this.externalProcessPresenceCheck(o):!1,X=D&&!x?{}:A,dt=y?.interruptReason??T.interruptReason,Vn=y?.stallWarning??T.stallWarning,Ho=y?.pendingQueue??T.pendingQueue;p={sessionId:o,agent:T.agent,messages:k,...ur(y?.acceptedClientMessageIds??T.acceptedClientMessageIds),isResponding:y?.isResponding??X.isResponding??(D&&!x?void 0:T.isResponding),...x?{externallyResponding:!0}:{},partialReplyText:y?this.currentPartialReplyText(y):X.partialReplyText,approvalMode:y?.approvalMode??T.approvalMode,...y?.pendingApproval?{pendingApproval:y.pendingApproval}:{},...dt?{interruptReason:dt}:{},...Vn?{stallWarning:Vn}:{},...Ho.length>0?{pendingQueue:qt(Ho)}:{}},m!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:m})}}let g=this.collectReconnectPendingApprovals();b.increment("reconnect.snapshot",{activeSession:p?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:f.sessions,nextCursor:f.nextCursor,inventoryVersion:f.inventoryVersion,...p?{activeSession:p}:{},...g.length>0?{pendingApprovals:g}:{}}})}catch(d){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(d)}`)}}async approve(e,n,s,r,i){let o=this.resolveSessionRef(s);s=o.resolvedSessionId;let a=this.sessions.get(s),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(r);if(a&&u){a.pendingApproval=void 0,_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(ff(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}));return}let c=a?.syntheticApprovalRetries[r];if(a&&c&&Ls(r)){delete a.syntheticApprovalRetries[r],a.pendingApproval=void 0,_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s})),i&&await this.retrySyntheticClaudeApproval(a,c);return}if(a&&!a.driver&&l)try{await this.reviveSessionForApproval(a)}catch(f){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(f)}`);return}if(!a?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("approval.response",{sessionId:s,requestId:r,approved:i}),!a.driver.respondApproval(r,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}a.pendingApproval=void 0,this.touchSession(a.sessionId),a.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:s}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let s=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",r=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,r,e.claudeHookSecret);await r.start(e.cwd,e.sessionId,s),e.driver=r,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.currentTurn=To(n.message),e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.pendingQueue=e.pendingQueue??[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(G(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:s},"retrying Claude turn after synthetic approval"),r.sendPrompt(n.message,e.model)}catch(s){e.driver=null,e.active=!1,e.isResponding=!1,delete e.currentTurn,e.startupInProgress=!1;let r=e.pendingQueue.length>0;e.pendingQueue=[],e.startupToken+=1,r&&this.broadcastPendingQueue(e),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:e.sessionId,error:String(s)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(s)}`})}}async setApprovalMode(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s);if(!o){let l=this.store.find(s);l?(r===null?delete l.approvalMode:l.approvalMode=r,this.store.upsert(l),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:l.agent,newMode:r},"approval mode changed (inactive session)")):w.info({sessionId:s,newMode:r},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}));return}if(r===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=r,this.store.upsert(G(o)),this.noteInventoryChanged("session_updated"),w.info({sessionId:s,agent:o.agent,oldMode:a,newMode:r},"approval mode changed"),o.driver&&o.driver.setApprovalMode(r),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:r,sessionId:s}))}interrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("session.interrupt",{sessionId:s,agent:i.agent}),!i.driver){if(i.isResponding||i.pendingQueue.length>0){w.info({sessionId:s,agent:i.agent},"interrupting driverless session with stale responding state");let o=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),o&&this.broadcastPendingQueue(i),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})}this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}if(i.startupInProgress){let o=i.isResponding||i.pendingQueue.length>0;w.info({sessionId:s,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session");let a=i.pendingQueue.length>0;i.pendingQueue=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,delete i.currentTurn,i.pendingApproval=void 0,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),a&&this.broadcastPendingQueue(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}clearInterrupt(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s),o=this.store.find(s),a=!!(o?.interruptReason||o?.stallWarning);if(!i&&!a){this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}));return}let l=!1;i?.interruptReason&&(i.interruptReason=void 0,l=!0),i&&this.dismissStallWarning(i)&&(l=!0),i?(this.store.upsert(G(i)),a&&(l=!0)):a&&o&&(this.store.upsert({...o,interruptReason:void 0,stallWarning:void 0}),l=!0),l&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}stopSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:s,agent:i.agent},"stopping session"),_.emit("session.stop",{sessionId:s,agent:i.agent}),cf(i);let o=i.isResponding||i.pendingQueue.length>0||i.startupInProgress,a=i.pendingQueue.length>0;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",delete i.currentTurn,i.pendingApproval=void 0,i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),a&&this.broadcastPendingQueue(i),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}deleteSession(e,n,s){let r=this.resolveSessionRef(s);s=r.resolvedSessionId;let i=this.sessions.get(s);i&&(w.info({sessionId:s,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.pendingQueue=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(s)),_.emit("session.delete",{sessionId:s}),this.store.remove(s),this.updateGauges(),er(),qs(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(r,{sessionId:s}))}async sendHistory(e,n,s,r){let i=this.resolveSessionRef(s);s=i.resolvedSessionId;let o=this.sessions.get(s),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(s)){this.reply(e,n,!1,void 0,"Session not found");return}o&&o.clients.add(e);let l=a?.cwd??o?.cwd??this.store.find(s)?.cwd??"",u=this.store.find(s),c=await Bn(s,r,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),f=a||o?{}:await So(s,r,l),p=!a&&!!f.isResponding,g=p?await this.externalProcessPresenceCheck(s):!1,m=g?!0:void 0,h=p&&!g?{}:f,y=a?.isResponding??h.isResponding,T=a?this.currentPartialReplyText(a):h.partialReplyText;w.info({sessionId:s,historyCount:c.length,isResponding:y,externallyResponding:m,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let I=o&&o.pendingQueue.length>0?qt(o.pendingQueue):u?.pendingQueue&&u.pendingQueue.length>0?u.pendingQueue:void 0,k={type:"session.history",sessionId:s,messages:d,...ur(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:m,partialReplyText:T,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval,stallWarning:o?.stallWarning??u?.stallWarning,...I?{pendingQueue:I}:{}};e.readyState===1&&e.send(JSON.stringify(k));let A=o?.interruptReason??u?.interruptReason;if(A&&e.readyState===1){let D={type:"session.interrupted_notice",sessionId:s,reason:A};e.send(JSON.stringify(D))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:s}))}async fetchGitMetadata(e,n,s){if(!Array.isArray(s)){this.reply(e,n,!1,void 0,"cwds must be an array");return}let r=[...new Set(s.filter(i=>typeof i=="string"&&i.length>0))];try{let[i,o]=await Promise.all([Bs(r),Fs(r)]),a={},l={};for(let u of r)a[u]=i.get(u)??null,l[u]=o.get(u)??null;this.reply(e,n,!0,{branches:a,diffStats:l})}catch(i){this.reply(e,n,!1,void 0,String(i))}}async listSessions(e,n,s,r,i,o=50,a,l,u,c){try{let d=await Js({agent:s,cwd:r,search:i,sinceMs:u,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:c}),f=this.decorateSessionsWithArchived(d.sessions);this.reply(e,n,!0,{...d,sessions:f,inventoryVersion:this.inventoryVersion})}catch(d){this.reply(e,n,!1,void 0,String(d))}}setSessionArchived(e,n,s,r){if(typeof s!="string"||s.length===0){this.reply(e,n,!1,void 0,"sessionId is required");return}this.store.setArchived(s,r===!0)&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,{archived:this.store.isArchived(s)})}archiveSync(e,n,s,r){let i,o=!1;switch(s){case"pushReplace":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.replaceArchivedSessionIds(l),o=u.size!==i.length||i.some(c=>!u.has(c));break}case"pushMerge":{let l=Array.isArray(r)?r:[],u=new Set(this.store.getArchivedSessionIds());i=this.store.mergeArchivedSessionIds(l),o=i.some(c=>!u.has(c));break}case"pull":{i=this.store.getArchivedSessionIds();break}default:this.reply(e,n,!1,void 0,`unknown archive sync mode: ${String(s)}`);return}o&&this.noteInventoryChanged("session_updated");let a={archivedSessionIds:i};this.reply(e,n,!0,a)}decorateSessionsWithArchived(e){return e.length===0?e:e.map(n=>({...n,archived:this.store.isArchived(n.sessionId)}))}listArchiveableManagedSessions(e,n){let s=this.getDeletedSessionIds(),r=new Set;for(let o of this.sessions.values())o.managed&&(o.sessionId.startsWith("pending_")||s.has(o.sessionId)||r.add(o.sessionId));for(let o of this.store.getAll())o.managed&&(s.has(o.sessionId)||r.add(o.sessionId));let i={count:r.size,ids:[...r]};this.reply(e,n,!0,i)}createDriver(e){if(S.reviewMock)return new Ns;switch(e){case"claude":return new Cn;case"codex":return new xn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let s=this.sessions.get(e);if(!s){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let r=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:s.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(r),a++):l++;if(l>0&&b.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){s.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=s.title||e,c=this.buildPushBody(s.currentReplyText);s.currentReplyText="",this.pushSender({title:u,body:c},{sessionId:e,agent:s.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(s.currentReplyText="")}reply(e,n,s,r,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:s,data:r,error:i};e.send(JSON.stringify(o))}};function xo(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken,t.locale):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var gf=require("child_process");function F_(t,e){return(0,gf.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function U_(t){let e=t.split(`
114
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function mf(t,e=F_){let n;try{n=U_(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(s=>{try{let r=e("ps",["-p",String(s),"-o","command="]);return r?{pid:s,command:r}:{pid:s}}catch{return{pid:s}}})}var $t=require("fs"),Ro=require("os"),vf=require("crypto"),Sf=require("path");function _f(t){return(0,vf.randomBytes)(t).toString("base64url")}function H_(){return`d_${_f(12)}`}function W_(){return(0,Ro.hostname)()}function q_(){let t=(0,Ro.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function G_(t){return{daemonId:H_(),daemonSecret:_f(32),displayName:W_(),canonicalHost:q_(),port:t,createdAt:new Date().toISOString()}}function yf(t,e){(0,$t.mkdirSync)((0,Sf.dirname)(e),{recursive:!0}),(0,$t.writeFileSync)(e,JSON.stringify(t,null,2)+`
115
+ `,"utf8")}function bf(t,e=nu){try{let s=(0,$t.readFileSync)(e,"utf8"),r=JSON.parse(s);if(typeof r.daemonId=="string"&&typeof r.daemonSecret=="string"&&typeof r.displayName=="string"&&typeof r.canonicalHost=="string"&&typeof r.createdAt=="string"){let i={daemonId:r.daemonId,daemonSecret:r.daemonSecret,displayName:r.displayName,canonicalHost:r.canonicalHost,port:typeof r.port=="number"&&Number.isFinite(r.port)?r.port:t,createdAt:r.createdAt};return i.port!==t&&(i.port=t,yf(i,e)),i}}catch{}let n=G_(t);return yf(n,e),n}var zt=require("crypto"),Vt=require("fs"),If=require("path");function Eo(t){return(0,zt.randomBytes)(t).toString("base64url")}function Po(t){return(0,zt.createHash)("sha256").update(t).digest("hex")}function wf(t,e){let n=Buffer.from(t),s=Buffer.from(e);return n.length!==s.length?!1:(0,zt.timingSafeEqual)(n,s)}function j_(t){try{let e=(0,Vt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(s=>s&&typeof s.deviceId=="string"&&typeof s.deviceName=="string"&&typeof s.tokenHash=="string"&&typeof s.createdAt=="string"&&typeof s.lastSeenAt=="string"&&(typeof s.revokedAt=="string"||s.revokedAt===null)):[]}catch{return[]}}function Gn(t,e){(0,Vt.mkdirSync)((0,If.dirname)(t),{recursive:!0}),(0,Vt.writeFileSync)(t,JSON.stringify(e,null,2)+`
116
+ `,"utf8")}var fr=class{constructor(e=su){this.pairingsPath=e;this.records=j_(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let s=`pair_${Eo(8)}`,r=Eo(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:s,pairNonce:r,expiresAt:i,reusable:n};return this.windows.set(r,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let s=new Date().toISOString(),r=Eo(32),i={deviceId:e,deviceName:n,tokenHash:Po(r),createdAt:s,lastSeenAt:s,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Gn(this.pairingsPath,this.records),r}validatePairToken(e,n,s=!0){let r=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!r)return!1;let i=Po(n);return wf(r.tokenHash,i)?(s&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let s=Po(e),r=this.records.find(i=>!i.revokedAt&&wf(i.tokenHash,s));return r?(n&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),r):null}revoke(e){let n=this.records.find(s=>s.deviceId===e&&!s.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Gn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Gn(this.pairingsPath,this.records)}};function pr(t){return Array.isArray(t)?t[0]:t}function Af(t){let e=pr(t.headers["x-forwarded-for"]),n=pr(t.headers["cf-connecting-ip"]),s=pr(t.headers["x-real-ip"]),r=e?.split(",")[0]?.trim()||n||s||t.socket.remoteAddress||void 0,i=pr(t.headers["user-agent"]);return{...r?{ip:r}:{},...i?{userAgent:i}:{}}}function $_(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}var z_=["x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","forwarded","via","cf-connecting-ip","cf-ray"];function V_(t){for(let e of z_)if(t[e]!==void 0)return!0;return!1}function ct(t){return $_(t.socket.remoteAddress)&&!V_(t.headers)}function Q_(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Mo(t,e){return Q_(t)??e}function hr(t,e){return!!(t&&e&&t===e)}function Lo(t,e,n,s=!0){return t?hr(t,e)?!0:!!n(t,s):!1}var Tf=require("fs");var J_=new Set(["ws.connect","ws.auth.success"]);function Y_(t){try{let n=(0,Tf.readFileSync)(t,"utf8").split(`
117
+ `),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&J_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function kf(t,e=20,n=De){let s=Y_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var Rf=require("child_process"),Ef=require("fs");function gr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function No(t){if(!gr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function K_(t){if(!gr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function X_(t){if(!gr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Z_(t){if(!gr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function mr(t){return!!t&&!K_(t)&&!X_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Oo(t){return fe(t.replace(/^https?:\/\//,""))??t}function eb(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>mr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function tb(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function nb(t){let e=Oo(t);return No(e)||e.endsWith(".ts.net")}function sb(t){let e=Oo(t);return Z_(e)||e.endsWith(".local")}function rb(t){return Oo(t).endsWith(".trycloudflare.com")}function Cf(t,e){return nb(t)?"tailscale":sb(t)?"local_network":e?"configured_host":"fallback"}function Pf(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function ib(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function ob(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=rb(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function ab(t,e,n){let s=fe(t)||"localhost",r=eb(e,s);return Pf([{kind:"direct",host:s,port:n,source:Cf(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:Cf(i,!1),stability:"stable"}))])}function Mf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function lb(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&tb(s))for(let i of r)i.internal||i.family!=="IPv4"||mr(i.address)&&(No(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function xf(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>No(o)&&mr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Lf(t=Rf.execFileSync,e=Ef.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return xf(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return xf(s)}catch{return{fallbackHosts:[]}}}function Nf(t){let e=ab(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?ob(t.relayUrl):null,s=Pf([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:ib(s),port:r.port,connections:s}}function Of(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...lb(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>mr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Df(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=L.child({module:"daemon"}),jn=L.child({module:"ws"});function cb(){try{let t=JSON.parse(require("fs").readFileSync(iu,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var ub=["-y","vibelet@latest","restart"],Uo=!1;function db(){let t=process.env.VIBELET_DAEMON_UPDATE_COMMAND||(process.platform==="win32"?"npx.cmd":"npx"),e=ub;if(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON)try{let s=JSON.parse(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON);Array.isArray(s)&&s.every(r=>typeof r=="string")&&(e=s)}catch{}let n=[t==="npx.cmd"?"npx":t,...e].map(s=>/^[A-Za-z0-9_/@:=-]+$/.test(s)?s:JSON.stringify(s)).join(" ");return{command:t,args:e,displayCommand:n}}function fb(t,e,n){(0,qe.mkdirSync)(xt,{recursive:!0});let s=null,r=null;try{s=(0,qe.openSync)(yn,"a"),r=(0,qe.openSync)(vn,"a");let i=(0,Uf.spawn)(t,e,{cwd:process.cwd(),env:{...process.env,VIBELET_UPDATE_SOURCE:"app"},detached:!0,stdio:["ignore",s,r]});i.once("error",o=>{Uo=!1,W.error({command:n,error:String(o)},"daemon update spawn failed"),_.emit("daemon.update.spawn_failed",{command:n,error:String(o)})}),i.unref(),W.info({command:n,pid:i.pid},"daemon update spawned"),_.emit("daemon.update.spawned",{command:n,pid:i.pid})}finally{s!==null&&(0,qe.closeSync)(s),r!==null&&(0,qe.closeSync)(r)}}function pb(t,e){let{command:n,args:s,displayCommand:r}=db();if(Uo){t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!1,alreadyRunning:!0,command:r}}));return}Uo=!0,t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!0,command:r}})),W.info({command:r},"daemon update requested"),_.emit("daemon.update.requested",{command:r});let i=setTimeout(()=>{fb(n,s,r)},100);typeof i.unref=="function"&&i.unref()}var j=bf(S.port),te=new dr((t,e)=>or(t,{daemonId:j.daemonId,canonicalHost:$n().canonicalHost,...e??{}})),ae=new fr,vr=new Set,We=new WeakMap,Bf=!1,qf=Date.now(),Qt=null,yr=null,hb=1e3;function gb(){let t=Lf();return Of({canonicalHost:j.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Mf(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Wf.networkInterfaces)()})}function $n(){let t=Date.now();if(yr&&yr.expiresAt>t)return yr.value;let e=gb(),n=Nf({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:j.port,relayUrl:S.relayUrl});return yr={value:n,expiresAt:t+hb},n}function mb(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability,n.secure===!0])),e}async function yb(t){let e=JSON.stringify(mb(t));await(0,le.mkdir)(Ie,{recursive:!0}),await Fo.default.toFile(Mi,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Fo.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});Rt(`
118
118
  Scan this QR code with Vibelet app:
119
119
 
120
120
  ${n}
121
121
  `),Rt(`If Vibelet app can't scan the terminal QR, open this PNG instead:
122
- ${Ei}
123
- `)}async function No(t){let e=[];for await(let s of t)e.push(Buffer.isBuffer(s)?s:Buffer.from(s));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function H(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function yb(t){let e=(0,Jt.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 qf(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function vb(t,e){if(ct(t))return!0;let n=Eo(t.headers.authorization,e.searchParams.get("token"));return Po(n,S.legacyToken,(s,r)=>ae.validateAnyPairToken(s,r),!1)}function Sb(){let t=ae.openWindow(qf(),S.pairReusable),e=$n();return{type:"vibelet-pair",daemonId:j.daemonId,displayName:j.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 _b(t,e){let n=So(t,e),s=await(0,le.readdir)(n),r=[];for(let i of s){if(i.startsWith("."))continue;let o=await(0,le.stat)((0,Jt.join)(n,i)).catch(()=>null);o&&r.push({name:i,isDirectory:o.isDirectory()})}return r.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:r}}var zn=(0,Bf.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let r=$n(),i=lb(),o={status:"ok",version:Lt,...i?{latestVersion:i}:{}};if(!vb(t,n)){H(e,200,o);return}let a={...o,status:"ok",daemonId:j.daemonId,displayName:j.displayName,canonicalHost:r.canonicalHost,uptimeSeconds:Math.round((Date.now()-Wf)/1e3),activeSessions:te.getActiveSessionCount(),pairedDevices:ae.pairedCount(),wsClients:pe.clients.size,drivers:te.getDriverCounts(),sessionInventory:md(),metrics:b.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),H(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!ct(t)){H(e,403,{error:"forbidden"});return}H(e,200,Sb());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!ct(t)){H(e,403,{error:"forbidden"});return}ae.reset(),H(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!ct(t)){H(e,403,{error:"forbidden"});return}H(e,200,{status:"stopping"}),setTimeout(()=>ut("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!ct(t)){H(e,403,{error:"forbidden"});return}try{let r=await No(t),i=t.headers[An],o=Array.isArray(i)?i[0]:i;te.handleClaudeSessionStartHook(o,r),H(e,200,{ok:!0})}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!ct(t)){H(e,403,{error:"forbidden"});return}try{let r=await No(t),i=t.headers[An],o=Array.isArray(i)?i[0]:i,a=await te.handleClaudePermissionHook(o,r);H(e,200,a)}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let r=await No(t);if(r.daemonId!==j.daemonId||typeof r.pairNonce!="string"||typeof r.deviceId!="string"||typeof r.deviceName!="string"){H(e,400,{error:"invalid_pair_request"});return}if(!ae.consumeWindow(r.pairNonce)){H(e,401,{error:"pair_window_expired"});return}let o=ae.issuePairToken(r.deviceId,r.deviceName),a=$n();H(e,200,{daemonId:j.daemonId,displayName:j.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:r.deviceId,pairToken:o})}catch(r){H(e,400,{error:String(r)})}return}let s=Eo(t.headers.authorization,n.searchParams.get("token"));if(!Po(s,S.legacyToken,(r,i)=>ae.validateAnyPairToken(r,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let r={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","application/json":".json","application/zip":".zip"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=n.searchParams.get("name")??"",l=(0,Jt.extname)(o).toLowerCase()||r[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let f of t){let h=Buffer.isBuffer(f)?f:Buffer.from(f);if(d+=h.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(h)}try{await(0,le.mkdir)(Ri,{recursive:!0});let f=`${Date.now()}_${(0,Uf.randomBytes)(8).toString("hex")}${l}`,h=(0,Jt.join)(Ri,f);await(0,le.writeFile)(h,Buffer.concat(c)),W.info({filePath:h,size:d,contentType:i,providedName:o||void 0},"file uploaded"),H(e,200,{path:h})}catch(f){W.error({error:String(f)},"upload failed"),H(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let r=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!r){e.writeHead(400),e.end("Missing path parameter");return}try{let o=So(r,i);if(!(await(0,le.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=yb(o),u=await(0,le.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${Lt}`)}),pe=new Fr.default({server:zn});zn.on("connection",t=>{mr.add(t),t.on("close",()=>{mr.delete(t)})});pe.on("connection",(t,e)=>{let s=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token"),r=If(e);if(s&&fr(s,S.legacyToken))We.set(t,{authMode:"query_token"}),b.increment("ws.auth.success",{mode:"query_token"}),_.emit("ws.auth.success",{authMode:"query_token",...r}),te.addGlobalClient(t),te.prewarmCaches();else if(s){let i=ae.validateAnyPairToken(s);if(i)We.set(t,{authMode:"query_token",deviceId:i.deviceId}),b.increment("ws.auth.success",{mode:"query_token"}),_.emit("ws.auth.success",{authMode:"query_token",deviceId:i.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches();else{b.increment("ws.auth.failure",{mode:"query_token"}),_.emit("ws.auth.failure",{authMode:"query_token",...r}),t.close(4001,"Unauthorized");return}}jn.info({clients:pe.clients.size},"client connected"),b.increment("ws.connect"),b.gauge("ws.clients",pe.clients.size),_.emit("ws.connect",{clients:pe.clients.size,authMode:We.get(t)?.authMode??"pending",deviceId:We.get(t)?.deviceId,...r}),t.on("message",async i=>{try{let o=JSON.parse(Of(i));if(!o||typeof o.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(o.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let a=o;if(!We.has(t)){if(a.action==="auth.hello"){let l=(()=>{if(fr(a.pairToken,S.legacyToken))return{deviceId:a.deviceId};if(a.deviceId&&a.daemonId===j.daemonId&&ae.validatePairToken(a.deviceId,a.pairToken))return{deviceId:a.deviceId};if(!a.daemonId||a.daemonId===j.daemonId){let u=ae.validateAnyPairToken(a.pairToken);if(u)return{deviceId:u.deviceId}}return null})();if(l){We.set(t,{authMode:"auth_hello",deviceId:l.deviceId,...a.locale?{locale:a.locale}:{}}),b.increment("ws.auth.success",{mode:"auth_hello"}),_.emit("ws.auth.success",{authMode:"auth_hello",deviceId:l.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches(),t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{daemonId:j.daemonId,...l.deviceId?{deviceId:l.deviceId}:{},displayName:j.displayName}}));return}b.increment("ws.auth.failure",{mode:"auth_hello"}),_.emit("ws.auth.failure",{authMode:"auth_hello",...r}),t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}b.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(a.action==="log.report"){for(let l of a.entries)_.emitApp(l.event,l.level,l.data??{},l.ts),(l.level==="error"?W.error:l.level==="warn"?W.warn:W.info).call(W,{event:l.event,...l.data},`[app] ${l.event}`);t.send(JSON.stringify({type:"response",id:a.id,ok:!0}));return}if(a.action==="dirs.list"){try{let l=await _b(a.path,a.cwd);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:l}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}if(o.action==="push.register"){let l=We.get(t),u=o.locale?o:{...o,locale:l?.locale};Co(u,{deviceId:l?.deviceId,registerToken:_o,unregisterToken:bo,respond:c=>t.send(JSON.stringify(c))});return}if(o.action==="push.unregister"){let l=We.get(t);Co(o,{deviceId:l?.deviceId,registerToken:_o,unregisterToken:bo,respond:u=>t.send(JSON.stringify(u))});return}if(a.action==="daemon.update"){fb(t,a.id);return}if(a.action==="audit.list_devices"){try{let l=Tf(ae,a.maxConnectionsPerDevice);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{devices:l}}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}await te.handle(t,a)}catch(o){jn.error({error:String(o)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(o)}))}}),t.on("close",i=>{jn.info({clients:pe.clients.size,code:i},"client disconnected"),b.increment("ws.disconnect"),b.increment("ws.disconnect.code",{code:String(i)}),b.gauge("ws.clients",pe.clients.size),_.emit("ws.disconnect",{clients:pe.clients.size,code:i}),te.removeClient(t)}),t.on("error",i=>{jn.error({error:i.message},"websocket error")})});function Oo(){for(let t of mr)try{t.destroy()}catch{}mr.clear()}function Gf(){let t=pu({auditPath:De,stdoutLogPath:yn,stderrLogPath:vn,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&W.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function bb(){Qt||(Qt=setInterval(Gf,S.storageHousekeepingIntervalMs),Qt.unref())}function wb(){Qt&&(clearInterval(Qt),Qt=null)}function ut(t,e=0){if(!Df){Df=!0,W.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Wf)/1e3)}),b.stopPeriodicLog(),wb(),Dt.stop().catch(()=>{}),te.shutdown(t);for(let n of pe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}pe.close(n=>{n&&W.error({error:String(n)},"websocket close error")}),zn.close(n=>{if(n){W.error({error:String(n)},"http close error"),Oo(),process.exit(1);return}Oo(),process.exit(e)}),setTimeout(()=>{W.error("force exiting after shutdown timeout"),Oo(),process.exit(e||1)},3e3).unref()}}pe.on("error",t=>{jn.error({error:t.message},"wss error")});zn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=gf(S.port).filter(n=>n.pid!==process.pid);W.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or start Vibelet with --port <port> (or VIBE_PORT=<port>)")}else W.error({error:String(t)},"server error");ut(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ut("SIGINT"));process.once("SIGTERM",()=>ut("SIGTERM"));process.once("SIGHUP",()=>ut("SIGHUP"));process.once("SIGTTIN",()=>ut("SIGTTIN"));process.once("SIGTSTP",()=>ut("SIGTSTP"));process.on("uncaughtException",t=>{W.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{W.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});zn.listen(S.port,async()=>{Gf(),_.emit("daemon.start",{port:S.port}),b.startPeriodicLog(),bb(),yd(),Dt.start().catch(s=>{W.warn({error:String(s)},"session activity watcher failed to start")});let t=$n();W.info({port:S.port,pairingPort:t.port,daemonId:j.daemonId,displayName:j.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs,turnStallHardTimeoutMs:S.turnStallHardTimeoutMs},"daemon started");let e=ae.openWindow(qf(),S.pairReusable),n={type:"vibelet-pair",daemonId:j.daemonId,displayName:j.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};Rt(`
122
+ ${Mi}
123
+ `)}async function Do(t){let e=[];for await(let s of t)e.push(Buffer.isBuffer(s)?s:Buffer.from(s));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function H(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function vb(t){let e=(0,Jt.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 Gf(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function Sb(t,e){if(ct(t))return!0;let n=Mo(t.headers.authorization,e.searchParams.get("token"));return Lo(n,S.legacyToken,(s,r)=>ae.validateAnyPairToken(s,r),!1)}function _b(){let t=ae.openWindow(Gf(),S.pairReusable),e=$n();return{type:"vibelet-pair",daemonId:j.daemonId,displayName:j.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 bb(t,e){let n=bo(t,e),s=await(0,le.readdir)(n),r=[];for(let i of s){if(i.startsWith("."))continue;let o=await(0,le.stat)((0,Jt.join)(n,i)).catch(()=>null);o&&r.push({name:i,isDirectory:o.isDirectory()})}return r.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:r}}var zn=(0,Ff.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let r=$n(),i=cb(),o={status:"ok",version:Lt,...i?{latestVersion:i}:{}};if(!Sb(t,n)){H(e,200,o);return}let a={...o,status:"ok",daemonId:j.daemonId,displayName:j.displayName,canonicalHost:r.canonicalHost,uptimeSeconds:Math.round((Date.now()-qf)/1e3),activeSessions:te.getActiveSessionCount(),pairedDevices:ae.pairedCount(),wsClients:pe.clients.size,drivers:te.getDriverCounts(),sessionInventory:yd(),metrics:b.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),H(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!ct(t)){H(e,403,{error:"forbidden"});return}H(e,200,_b());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!ct(t)){H(e,403,{error:"forbidden"});return}ae.reset(),H(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!ct(t)){H(e,403,{error:"forbidden"});return}H(e,200,{status:"stopping"}),setTimeout(()=>ut("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!ct(t)){H(e,403,{error:"forbidden"});return}try{let r=await Do(t),i=t.headers[An],o=Array.isArray(i)?i[0]:i;te.handleClaudeSessionStartHook(o,r),H(e,200,{ok:!0})}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!ct(t)){H(e,403,{error:"forbidden"});return}try{let r=await Do(t),i=t.headers[An],o=Array.isArray(i)?i[0]:i,a=await te.handleClaudePermissionHook(o,r);H(e,200,a)}catch(r){H(e,400,{error:String(r)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let r=await Do(t);if(r.daemonId!==j.daemonId||typeof r.pairNonce!="string"||typeof r.deviceId!="string"||typeof r.deviceName!="string"){H(e,400,{error:"invalid_pair_request"});return}if(!ae.consumeWindow(r.pairNonce)){H(e,401,{error:"pair_window_expired"});return}let o=ae.issuePairToken(r.deviceId,r.deviceName),a=$n();H(e,200,{daemonId:j.daemonId,displayName:j.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:r.deviceId,pairToken:o})}catch(r){H(e,400,{error:String(r)})}return}let s=Mo(t.headers.authorization,n.searchParams.get("token"));if(!Lo(s,S.legacyToken,(r,i)=>ae.validateAnyPairToken(r,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let r={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","application/pdf":".pdf","text/plain":".txt","text/markdown":".md","application/json":".json","application/zip":".zip"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=n.searchParams.get("name")??"",l=(0,Jt.extname)(o).toLowerCase()||r[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let f of t){let p=Buffer.isBuffer(f)?f:Buffer.from(f);if(d+=p.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(p)}try{await(0,le.mkdir)(Pi,{recursive:!0});let f=`${Date.now()}_${(0,Hf.randomBytes)(8).toString("hex")}${l}`,p=(0,Jt.join)(Pi,f);await(0,le.writeFile)(p,Buffer.concat(c)),W.info({filePath:p,size:d,contentType:i,providedName:o||void 0},"file uploaded"),H(e,200,{path:p})}catch(f){W.error({error:String(f)},"upload failed"),H(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let r=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!r){e.writeHead(400),e.end("Missing path parameter");return}try{let o=bo(r,i);if(!(await(0,le.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=vb(o),u=await(0,le.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${Lt}`)}),pe=new Hr.default({server:zn});zn.on("connection",t=>{vr.add(t),t.on("close",()=>{vr.delete(t)})});pe.on("connection",(t,e)=>{let s=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token"),r=Af(e);if(s&&hr(s,S.legacyToken))We.set(t,{authMode:"query_token"}),b.increment("ws.auth.success",{mode:"query_token"}),_.emit("ws.auth.success",{authMode:"query_token",...r}),te.addGlobalClient(t),te.prewarmCaches();else if(s){let i=ae.validateAnyPairToken(s);if(i)We.set(t,{authMode:"query_token",deviceId:i.deviceId}),b.increment("ws.auth.success",{mode:"query_token"}),_.emit("ws.auth.success",{authMode:"query_token",deviceId:i.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches();else{b.increment("ws.auth.failure",{mode:"query_token"}),_.emit("ws.auth.failure",{authMode:"query_token",...r}),t.close(4001,"Unauthorized");return}}jn.info({clients:pe.clients.size},"client connected"),b.increment("ws.connect"),b.gauge("ws.clients",pe.clients.size),_.emit("ws.connect",{clients:pe.clients.size,authMode:We.get(t)?.authMode??"pending",deviceId:We.get(t)?.deviceId,...r}),t.on("message",async i=>{try{let o=JSON.parse(Df(i));if(!o||typeof o.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(o.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let a=o;if(!We.has(t)){if(a.action==="auth.hello"){let l=(()=>{if(hr(a.pairToken,S.legacyToken))return{deviceId:a.deviceId};if(a.deviceId&&a.daemonId===j.daemonId&&ae.validatePairToken(a.deviceId,a.pairToken))return{deviceId:a.deviceId};if(!a.daemonId||a.daemonId===j.daemonId){let u=ae.validateAnyPairToken(a.pairToken);if(u)return{deviceId:u.deviceId}}return null})();if(l){We.set(t,{authMode:"auth_hello",deviceId:l.deviceId,...a.locale?{locale:a.locale}:{}}),b.increment("ws.auth.success",{mode:"auth_hello"}),_.emit("ws.auth.success",{authMode:"auth_hello",deviceId:l.deviceId,...r}),te.addGlobalClient(t),te.prewarmCaches(),t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{daemonId:j.daemonId,...l.deviceId?{deviceId:l.deviceId}:{},displayName:j.displayName}}));return}b.increment("ws.auth.failure",{mode:"auth_hello"}),_.emit("ws.auth.failure",{authMode:"auth_hello",...r}),t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}b.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(a.action==="log.report"){for(let l of a.entries)_.emitApp(l.event,l.level,l.data??{},l.ts),(l.level==="error"?W.error:l.level==="warn"?W.warn:W.info).call(W,{event:l.event,...l.data},`[app] ${l.event}`);t.send(JSON.stringify({type:"response",id:a.id,ok:!0}));return}if(a.action==="dirs.list"){try{let l=await bb(a.path,a.cwd);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:l}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}if(o.action==="push.register"){let l=We.get(t),u=o.locale?o:{...o,locale:l?.locale};xo(u,{deviceId:l?.deviceId,registerToken:wo,unregisterToken:Io,respond:c=>t.send(JSON.stringify(c))});return}if(o.action==="push.unregister"){let l=We.get(t);xo(o,{deviceId:l?.deviceId,registerToken:wo,unregisterToken:Io,respond:u=>t.send(JSON.stringify(u))});return}if(a.action==="daemon.update"){pb(t,a.id);return}if(a.action==="audit.list_devices"){try{let l=kf(ae,a.maxConnectionsPerDevice);t.send(JSON.stringify({type:"response",id:a.id,ok:!0,data:{devices:l}}))}catch(l){t.send(JSON.stringify({type:"response",id:a.id,ok:!1,error:String(l)}))}return}await te.handle(t,a)}catch(o){jn.error({error:String(o)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(o)}))}}),t.on("close",i=>{jn.info({clients:pe.clients.size,code:i},"client disconnected"),b.increment("ws.disconnect"),b.increment("ws.disconnect.code",{code:String(i)}),b.gauge("ws.clients",pe.clients.size),_.emit("ws.disconnect",{clients:pe.clients.size,code:i}),te.removeClient(t)}),t.on("error",i=>{jn.error({error:i.message},"websocket error")})});function Bo(){for(let t of vr)try{t.destroy()}catch{}vr.clear()}function jf(){let t=mu({auditPath:De,stdoutLogPath:yn,stderrLogPath:vn,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&W.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function wb(){Qt||(Qt=setInterval(jf,S.storageHousekeepingIntervalMs),Qt.unref())}function Ib(){Qt&&(clearInterval(Qt),Qt=null)}function ut(t,e=0){if(!Bf){Bf=!0,W.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-qf)/1e3)}),b.stopPeriodicLog(),Ib(),Dt.stop().catch(()=>{}),te.shutdown(t);for(let n of pe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}pe.close(n=>{n&&W.error({error:String(n)},"websocket close error")}),zn.close(n=>{if(n){W.error({error:String(n)},"http close error"),Bo(),process.exit(1);return}Bo(),process.exit(e)}),setTimeout(()=>{W.error("force exiting after shutdown timeout"),Bo(),process.exit(e||1)},3e3).unref()}}pe.on("error",t=>{jn.error({error:t.message},"wss error")});zn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=mf(S.port).filter(n=>n.pid!==process.pid);W.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or start Vibelet with --port <port> (or VIBE_PORT=<port>)")}else W.error({error:String(t)},"server error");ut(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ut("SIGINT"));process.once("SIGTERM",()=>ut("SIGTERM"));process.once("SIGHUP",()=>ut("SIGHUP"));process.once("SIGTTIN",()=>ut("SIGTTIN"));process.once("SIGTSTP",()=>ut("SIGTSTP"));process.on("uncaughtException",t=>{W.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{W.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});zn.listen(S.port,async()=>{jf(),_.emit("daemon.start",{port:S.port}),b.startPeriodicLog(),wb(),vd(),Dt.start().catch(s=>{W.warn({error:String(s)},"session activity watcher failed to start")});let t=$n();W.info({port:S.port,pairingPort:t.port,daemonId:j.daemonId,displayName:j.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs,turnStallHardTimeoutMs:S.turnStallHardTimeoutMs},"daemon started");let e=ae.openWindow(Gf(),S.pairReusable),n={type:"vibelet-pair",daemonId:j.daemonId,displayName:j.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};Rt(`
124
124
  \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
125
125
  \u2551 Vibelet Daemon v${Lt} \u2551
126
126
  \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
@@ -135,4 +135,4 @@ Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
135
135
 
136
136
  Claude: ${S.claudePath}
137
137
  Codex: ${S.codexPath}
138
- `);try{await mb(n)}catch{}});
138
+ `);try{await yb(n)}catch{}});