@vibelet/cli 1.0.15 → 1.0.17

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 tf=Object.create;var mo=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var rf=Object.getOwnPropertyNames;var sf=Object.getPrototypeOf,of=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var af=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of rf(e))!of.call(t,s)&&s!==n&&mo(t,s,{get:()=>e[s],enumerable:!(r=nf(e,s))||r.enumerable});return t};var ct=(t,e,n)=>(n=t!=null?tf(sf(t)):{},af(e||!t||!t.__esModule?mo(n,"default",{value:t,enumerable:!0}):n,t));var ye=v((FS,So)=>{"use strict";var yo=["nodebuffer","arraybuffer","fragments"],vo=typeof Blob<"u";vo&&yo.push("blob");So.exports={BINARY_TYPES:yo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:vo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var jt=v((HS,Bn)=>{"use strict";var{EMPTY_BUFFER:lf}=ye(),ns=Buffer[Symbol.species];function cf(t,e){if(t.length===0)return lf;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new ns(n.buffer,n.byteOffset,r):n}function _o(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function bo(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function uf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function rs(t){if(rs.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ns(t):ArrayBuffer.isView(t)?e=new ns(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rs.readOnly=!1),e}Bn.exports={concat:cf,mask:_o,toArrayBuffer:uf,toBuffer:rs,unmask:bo};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Bn.exports.mask=function(e,n,r,s,i){i<48?_o(e,n,r,s,i):t.mask(e,n,r,s,i)},Bn.exports.unmask=function(e,n){e.length<32?bo(e,n):t.unmask(e,n)}}catch{}});var Ao=v((US,Io)=>{"use strict";var wo=Symbol("kDone"),ss=Symbol("kRun"),is=class{constructor(e){this[wo]=()=>{this.pending--,this[ss]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ss]()}[ss](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wo])}}};Io.exports=is});var zt=v((qS,ko)=>{"use strict";var $t=require("zlib"),xo=jt(),df=Ao(),{kStatusCode:Co}=ye(),ff=Buffer[Symbol.species],pf=Buffer.from([0,0,255,255]),Fn=Symbol("permessage-deflate"),ve=Symbol("total-length"),ut=Symbol("callback"),Ce=Symbol("buffers"),dt=Symbol("error"),Dn,os=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Dn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Dn=new df(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ut];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Dn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Dn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?$t.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=$t.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Fn]=this,this._inflate[ve]=0,this._inflate[Ce]=[],this._inflate.on("error",gf),this._inflate.on("data",To)}this._inflate[ut]=r,this._inflate.write(e),n&&this._inflate.write(pf),this._inflate.flush(()=>{let i=this._inflate[dt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=xo.concat(this._inflate[Ce],this._inflate[ve]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ve]=0,this._inflate[Ce]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?$t.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=$t.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ve]=0,this._deflate[Ce]=[],this._deflate.on("data",hf)}this._deflate[ut]=r,this._deflate.write(e),this._deflate.flush($t.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=xo.concat(this._deflate[Ce],this._deflate[ve]);n&&(i=new ff(i.buffer,i.byteOffset,i.length-4)),this._deflate[ut]=null,this._deflate[ve]=0,this._deflate[Ce]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ko.exports=os;function hf(t){this[Ce].push(t),this[ve]+=t.length}function To(t){if(this[ve]+=t.length,this[Fn]._maxPayload<1||this[ve]<=this[Fn]._maxPayload){this[Ce].push(t);return}this[dt]=new RangeError("Max payload size exceeded"),this[dt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[dt][Co]=1009,this.removeListener("data",To),this.reset()}function gf(t){if(this[Fn]._inflate=null,this[dt]){this[ut](this[dt]);return}t[Co]=1007,this[ut](t)}});var ft=v((WS,Hn)=>{"use strict";var{isUtf8:Ro}=require("buffer"),{hasBlob:mf}=ye(),yf=[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 vf(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function as(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 Sf(t){return mf&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Hn.exports={isBlob:Sf,isValidStatusCode:vf,isValidUTF8:as,tokenChars:yf};if(Ro)Hn.exports.isValidUTF8=function(t){return t.length<24?as(t):Ro(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Hn.exports.isValidUTF8=function(e){return e.length<32?as(e):t(e)}}catch{}});var fs=v((GS,Bo)=>{"use strict";var{Writable:_f}=require("stream"),Eo=zt(),{BINARY_TYPES:bf,EMPTY_BUFFER:Po,kStatusCode:wf,kWebSocket:If}=ye(),{concat:ls,toArrayBuffer:Af,unmask:xf}=jt(),{isValidStatusCode:Cf,isValidUTF8:Mo}=ft(),Un=Buffer[Symbol.species],ee=0,Lo=1,No=2,Oo=3,cs=4,us=5,qn=6,ds=class extends _f{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||bf[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[If]=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=ee}_write(e,n,r){if(this._opcode===8&&this._state==ee)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Un(r.buffer,r.byteOffset+e,r.length-e),new Un(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Un(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ee:this.getInfo(e);break;case Lo:this.getPayloadLength16(e);break;case No:this.getPayloadLength64(e);break;case Oo:this.getMask();break;case cs:this.getData(e);break;case us:case qn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Eo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Lo:this._payloadLength===127?this._state=No:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Oo:this._state=cs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=cs}getData(e){let n=Po;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&&xf(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=us,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Eo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===ee&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ee;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ls(r,n):this._binaryType==="arraybuffer"?s=Af(ls(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit("message",s,!0),this._state=ee,this.startLoop(e)}))}else{let s=ls(r,n);if(!this._skipUTF8Validation&&!Mo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===us||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit("message",s,!1),this._state=ee,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Po),this.end();else{let r=e.readUInt16BE(0);if(!Cf(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Un(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=ee;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ee,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[wf]=s,o}};Bo.exports=ds});var gs=v(($S,Ho)=>{"use strict";var{Duplex:jS}=require("stream"),{randomFillSync:Tf}=require("crypto"),Do=zt(),{EMPTY_BUFFER:kf,kWebSocket:Rf,NOOP:Ef}=ye(),{isBlob:pt,isValidStatusCode:Pf}=ft(),{mask:Fo,toBuffer:He}=jt(),te=Symbol("kByteLength"),Mf=Buffer.alloc(4),Wn=8*1024,Ue,ht=Wn,ae=0,Lf=1,Nf=2,ps=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ae,this.onerror=Ef,this[Rf]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Mf,n.generateMask?n.generateMask(r):(ht===Wn&&(Ue===void 0&&(Ue=Buffer.alloc(Wn)),Tf(Ue,0,Wn),ht=0),r[0]=Ue[ht++],r[1]=Ue[ht++],r[2]=Ue[ht++],r[3]=Ue[ht++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[te]!==void 0?a=n[te]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(s?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]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(Fo(e,r,u,i,a),[u]):(Fo(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=kf;else{if(typeof e!="number"||!Pf(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={[te]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ae?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):pt(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[te]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ae?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):pt(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[te]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ae?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Do.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):pt(e)?(a=e.size,l=!1):(e=He(e),a=e.length,l=He.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[te]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ae?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[te],this._state=Nf,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(hs,this,a,s);return}this._bufferedBytes-=r[te];let o=He(i);n?this.dispatch(o,n,r,s):(this._state=ae,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Of,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Do.extensionName];this._bufferedBytes+=r[te],this._state=Lf,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");hs(this,l,s);return}this._bufferedBytes-=r[te],this._state=ae,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ae&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][te],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][te],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)}};Ho.exports=ps;function hs(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Of(t,e,n){hs(t,e,n),t.onerror(e)}});var Yo=v((zS,Vo)=>{"use strict";var{kForOnEventAttribute:Vt,kListener:ms}=ye(),Uo=Symbol("kCode"),qo=Symbol("kData"),Wo=Symbol("kError"),Go=Symbol("kMessage"),jo=Symbol("kReason"),gt=Symbol("kTarget"),$o=Symbol("kType"),zo=Symbol("kWasClean"),Se=class{constructor(e){this[gt]=null,this[$o]=e}get target(){return this[gt]}get type(){return this[$o]}};Object.defineProperty(Se.prototype,"target",{enumerable:!0});Object.defineProperty(Se.prototype,"type",{enumerable:!0});var qe=class extends Se{constructor(e,n={}){super(e),this[Uo]=n.code===void 0?0:n.code,this[jo]=n.reason===void 0?"":n.reason,this[zo]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Uo]}get reason(){return this[jo]}get wasClean(){return this[zo]}};Object.defineProperty(qe.prototype,"code",{enumerable:!0});Object.defineProperty(qe.prototype,"reason",{enumerable:!0});Object.defineProperty(qe.prototype,"wasClean",{enumerable:!0});var mt=class extends Se{constructor(e,n={}){super(e),this[Wo]=n.error===void 0?null:n.error,this[Go]=n.message===void 0?"":n.message}get error(){return this[Wo]}get message(){return this[Go]}};Object.defineProperty(mt.prototype,"error",{enumerable:!0});Object.defineProperty(mt.prototype,"message",{enumerable:!0});var Yt=class extends Se{constructor(e,n={}){super(e),this[qo]=n.data===void 0?null:n.data}get data(){return this[qo]}};Object.defineProperty(Yt.prototype,"data",{enumerable:!0});var Bf={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Vt]&&s[ms]===e&&!s[Vt])return;let r;if(t==="message")r=function(i,o){let a=new Yt("message",{data:o?i:i.toString()});a[gt]=this,Gn(e,this,a)};else if(t==="close")r=function(i,o){let a=new qe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[gt]=this,Gn(e,this,a)};else if(t==="error")r=function(i){let o=new mt("error",{error:i,message:i.message});o[gt]=this,Gn(e,this,o)};else if(t==="open")r=function(){let i=new Se("open");i[gt]=this,Gn(e,this,i)};else return;r[Vt]=!!n[Vt],r[ms]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ms]===e&&!n[Vt]){this.removeListener(t,n);break}}};Vo.exports={CloseEvent:qe,ErrorEvent:mt,Event:Se,EventTarget:Bf,MessageEvent:Yt};function Gn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ys=v((VS,Jo)=>{"use strict";var{tokenChars:Jt}=ft();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Df(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!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&&Jt[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 g=t.slice(l,c);u===44?(he(e,g,n),n=Object.create(null)):o=g,l=c=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(c===-1&&Jt[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(s){if(Jt[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Jt[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)s=!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&&Jt[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 g=t.slice(l,c);r&&(g=g.replace(/\\/g,""),r=!1),he(n,a,g),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):r?he(n,a,f.replace(/\\/g,"")):he(n,a,f),he(e,o,n)),e}function Ff(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Jo.exports={format:Ff,parse:Df}});var Vn=v((KS,aa)=>{"use strict";var Hf=require("events"),Uf=require("https"),qf=require("http"),Qo=require("net"),Wf=require("tls"),{randomBytes:Gf,createHash:jf}=require("crypto"),{Duplex:YS,Readable:JS}=require("stream"),{URL:vs}=require("url"),Te=zt(),$f=fs(),zf=gs(),{isBlob:Vf}=ft(),{BINARY_TYPES:Ko,CLOSE_TIMEOUT:Yf,EMPTY_BUFFER:jn,GUID:Jf,kForOnEventAttribute:Ss,kListener:Kf,kStatusCode:Xf,kWebSocket:U,NOOP:Zo}=ye(),{EventTarget:{addEventListener:Qf,removeEventListener:Zf}}=Yo(),{format:ep,parse:tp}=ys(),{toBuffer:np}=jt(),ea=Symbol("kAborted"),_s=[8,13],_e=["CONNECTING","OPEN","CLOSING","CLOSED"],rp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,M=class t extends Hf{constructor(e,n,r){super(),this._binaryType=Ko[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=jn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),ta(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ko.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new $f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new zf(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[U]=this,i[U]=this,e[U]=this,s.on("conclude",op),s.on("drain",ap),s.on("error",lp),s.on("message",cp),s.on("ping",up),s.on("pong",dp),i.onerror=fp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",sa),e.on("data",zn),e.on("end",ia),e.on("error",oa),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Te.extensionName]&&this._extensions[Te.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ra(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bs(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||jn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bs(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||jn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){bs(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Te.extensionName]||(s.compress=!1),this._sender.send(e||jn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(M,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(M.prototype,"CONNECTING",{enumerable:!0,value:_e.indexOf("CONNECTING")});Object.defineProperty(M,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(M.prototype,"OPEN",{enumerable:!0,value:_e.indexOf("OPEN")});Object.defineProperty(M,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(M.prototype,"CLOSING",{enumerable:!0,value:_e.indexOf("CLOSING")});Object.defineProperty(M,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});Object.defineProperty(M.prototype,"CLOSED",{enumerable:!0,value:_e.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(M.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(M.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ss])return e[Kf];return null},set(e){for(let n of this.listeners(t))if(n[Ss]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ss]:!0})}})});M.prototype.addEventListener=Qf;M.prototype.removeEventListener=Zf;aa.exports=M;function ta(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Yf,protocolVersion:_s[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!_s.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${_s.join(", ")})`);let i;if(e instanceof vs)i=e;else try{i=new vs(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;$n(t,p);return}let u=o?443:80,c=Gf(16).toString("base64"),d=o?Uf.request:qf.request,f=new Set,g;if(s.createConnection=s.createConnection||(o?ip:sp),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new Te(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=ep({[Te.extensionName]:g.offer()})),n.length){for(let p of n){if(typeof p!="string"||!rp.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,y]of Object.entries(p))r.headers[m.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=d(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=d(s);s.timeout&&h.on("timeout",()=>{Q(t,h,"Opening handshake has timed out")}),h.on("error",p=>{h===null||h[ea]||(h=t._req=null,$n(t,p))}),h.on("response",p=>{let m=p.headers.location,y=p.statusCode;if(m&&s.followRedirects&&y>=300&&y<400){if(++t._redirects>s.maxRedirects){Q(t,h,"Maximum redirects exceeded");return}h.abort();let w;try{w=new vs(m,e)}catch{let x=new SyntaxError(`Invalid URL: ${m}`);$n(t,x);return}ta(t,w,n,r)}else t.emit("unexpected-response",h,p)||Q(t,h,`Unexpected server response: ${p.statusCode}`)}),h.on("upgrade",(p,m,y)=>{if(t.emit("upgrade",p),t.readyState!==M.CONNECTING)return;h=t._req=null;let w=p.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Q(t,m,"Invalid Upgrade header");return}let A=jf("sha1").update(c+Jf).digest("base64");if(p.headers["sec-websocket-accept"]!==A){Q(t,m,"Invalid Sec-WebSocket-Accept header");return}let x=p.headers["sec-websocket-protocol"],T;if(x!==void 0?f.size?f.has(x)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":f.size&&(T="Server sent no subprotocol"),T){Q(t,m,T);return}x&&(t._protocol=x);let W=p.headers["sec-websocket-extensions"];if(W!==void 0){if(!g){Q(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let z;try{z=tp(W)}catch{Q(t,m,"Invalid Sec-WebSocket-Extensions header");return}let lt=Object.keys(z);if(lt.length!==1||lt[0]!==Te.extensionName){Q(t,m,"Server indicated an extension that was not requested");return}try{g.accept(z[Te.extensionName])}catch{Q(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Te.extensionName]=g}t.setSocket(m,y,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function $n(t,e){t._readyState=M.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function sp(t){return t.path=t.socketPath,Qo.connect(t)}function ip(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Qo.isIP(t.host)?"":t.host),Wf.connect(t)}function Q(t,e,n){t._readyState=M.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Q),e.setHeader?(e[ea]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick($n,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function bs(t,e,n){if(e){let r=Vf(e)?e.size:np(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_e[t.readyState]})`);process.nextTick(n,r)}}function op(t,e){let n=this[U];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[U]!==void 0&&(n._socket.removeListener("data",zn),process.nextTick(na,n._socket),t===1005?n.close():n.close(t,e))}function ap(){let t=this[U];t.isPaused||t._socket.resume()}function lp(t){let e=this[U];e._socket[U]!==void 0&&(e._socket.removeListener("data",zn),process.nextTick(na,e._socket),e.close(t[Xf])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Xo(){this[U].emitClose()}function cp(t,e){this[U].emit("message",t,e)}function up(t){let e=this[U];e._autoPong&&e.pong(t,!this._isServer,Zo),e.emit("ping",t)}function dp(t){this[U].emit("pong",t)}function na(t){t.resume()}function fp(t){let e=this[U];e.readyState!==M.CLOSED&&(e.readyState===M.OPEN&&(e._readyState=M.CLOSING,ra(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ra(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sa(){let t=this[U];if(this.removeListener("close",sa),this.removeListener("data",zn),this.removeListener("end",ia),t._readyState=M.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[U]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Xo),t._receiver.on("finish",Xo))}function zn(t){this[U]._receiver.write(t)||this.pause()}function ia(){let t=this[U];t._readyState=M.CLOSING,t._receiver.end(),this.end()}function oa(){let t=this[U];this.removeListener("error",oa),this.on("error",Zo),t&&(t._readyState=M.CLOSING,this.destroy())}});var da=v((QS,ua)=>{"use strict";var XS=Vn(),{Duplex:pp}=require("stream");function la(t){t.emit("close")}function hp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ca(t){this.removeListener("error",ca),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gp(t,e){let n=!0,r=new pp({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(la,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(la,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",hp),r.on("error",ca),r}ua.exports=gp});var pa=v((ZS,fa)=>{"use strict";var{tokenChars:mp}=ft();function yp(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&mp[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}fa.exports={parse:yp}});var _a=v((t_,Sa)=>{"use strict";var vp=require("events"),Yn=require("http"),{Duplex:e_}=require("stream"),{createHash:Sp}=require("crypto"),ha=ys(),We=zt(),_p=pa(),bp=Vn(),{CLOSE_TIMEOUT:wp,GUID:Ip,kWebSocket:Ap}=ye(),xp=/^[+/0-9A-Za-z]{22}==$/,ga=0,ma=1,va=2,ws=class extends vp{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:wp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bp,...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=Yn.createServer((r,s)=>{let i=Yn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Cp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ga}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===va){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Kt,this);return}if(e&&this.once("close",e),this._state!==ma)if(this._state=ma,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(Kt,this):process.nextTick(Kt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Kt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",ya);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ge(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ge(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!xp.test(i)){Ge(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ge(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Xt(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=_p.parse(l)}catch{Ge(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 We(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let g=ha.parse(c);g[We.extensionName]&&(f.accept(g[We.extensionName]),d[We.extensionName]=f)}catch{Ge(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,(g,h,p,m)=>{if(!g)return Xt(n,h||401,p,m);this.completeUpgrade(d,i,u,e,n,r,s)});return}if(!this.options.verifyClient(f))return Xt(n,401)}this.completeUpgrade(d,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Ap])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ga)return Xt(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Sp("sha1").update(n+Ip).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[We.extensionName]){let d=e[We.extensionName].params,f=ha.format({[We.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${f}`),c._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
1
+ "use strict";var sf=Object.create;var vo=Object.defineProperty;var of=Object.getOwnPropertyDescriptor;var af=Object.getOwnPropertyNames;var lf=Object.getPrototypeOf,cf=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var uf=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of af(e))!cf.call(t,s)&&s!==n&&vo(t,s,{get:()=>e[s],enumerable:!(r=of(e,s))||r.enumerable});return t};var ct=(t,e,n)=>(n=t!=null?sf(lf(t)):{},uf(e||!t||!t.__esModule?vo(n,"default",{value:t,enumerable:!0}):n,t));var ve=v((YS,bo)=>{"use strict";var So=["nodebuffer","arraybuffer","fragments"],_o=typeof Blob<"u";_o&&So.push("blob");bo.exports={BINARY_TYPES:So,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:_o,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $t=v((JS,Dn)=>{"use strict";var{EMPTY_BUFFER:df}=ve(),is=Buffer[Symbol.species];function ff(t,e){if(t.length===0)return df;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new is(n.buffer,n.byteOffset,r):n}function wo(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Io(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function pf(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function os(t){if(os.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new is(t):ArrayBuffer.isView(t)?e=new is(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),os.readOnly=!1),e}Dn.exports={concat:ff,mask:wo,toArrayBuffer:pf,toBuffer:os,unmask:Io};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Dn.exports.mask=function(e,n,r,s,i){i<48?wo(e,n,r,s,i):t.mask(e,n,r,s,i)},Dn.exports.unmask=function(e,n){e.length<32?Io(e,n):t.unmask(e,n)}}catch{}});var xo=v((KS,To)=>{"use strict";var Ao=Symbol("kDone"),as=Symbol("kRun"),ls=class{constructor(e){this[Ao]=()=>{this.pending--,this[as]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[as]()}[as](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ao])}}};To.exports=ls});var Vt=v((XS,Eo)=>{"use strict";var zt=require("zlib"),Co=$t(),hf=xo(),{kStatusCode:ko}=ve(),gf=Buffer[Symbol.species],mf=Buffer.from([0,0,255,255]),Hn=Symbol("permessage-deflate"),Se=Symbol("total-length"),ut=Symbol("callback"),Ce=Symbol("buffers"),dt=Symbol("error"),Fn,cs=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Fn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fn=new hf(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ut];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Fn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Fn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?zt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=zt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Hn]=this,this._inflate[Se]=0,this._inflate[Ce]=[],this._inflate.on("error",vf),this._inflate.on("data",Ro)}this._inflate[ut]=r,this._inflate.write(e),n&&this._inflate.write(mf),this._inflate.flush(()=>{let i=this._inflate[dt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Co.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[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?zt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=zt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[Ce]=[],this._deflate.on("data",yf)}this._deflate[ut]=r,this._deflate.write(e),this._deflate.flush(zt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Co.concat(this._deflate[Ce],this._deflate[Se]);n&&(i=new gf(i.buffer,i.byteOffset,i.length-4)),this._deflate[ut]=null,this._deflate[Se]=0,this._deflate[Ce]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Eo.exports=cs;function yf(t){this[Ce].push(t),this[Se]+=t.length}function Ro(t){if(this[Se]+=t.length,this[Hn]._maxPayload<1||this[Se]<=this[Hn]._maxPayload){this[Ce].push(t);return}this[dt]=new RangeError("Max payload size exceeded"),this[dt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[dt][ko]=1009,this.removeListener("data",Ro),this.reset()}function vf(t){if(this[Hn]._inflate=null,this[dt]){this[ut](this[dt]);return}t[ko]=1007,this[ut](t)}});var ft=v((QS,Un)=>{"use strict";var{isUtf8:Po}=require("buffer"),{hasBlob:Sf}=ve(),_f=[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 bf(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function us(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 wf(t){return Sf&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Un.exports={isBlob:wf,isValidStatusCode:bf,isValidUTF8:us,tokenChars:_f};if(Po)Un.exports.isValidUTF8=function(t){return t.length<24?us(t):Po(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Un.exports.isValidUTF8=function(e){return e.length<32?us(e):t(e)}}catch{}});var gs=v((ZS,Fo)=>{"use strict";var{Writable:If}=require("stream"),Mo=Vt(),{BINARY_TYPES:Af,EMPTY_BUFFER:Lo,kStatusCode:Tf,kWebSocket:xf}=ve(),{concat:ds,toArrayBuffer:Cf,unmask:kf}=$t(),{isValidStatusCode:Rf,isValidUTF8:No}=ft(),Wn=Buffer[Symbol.species],ee=0,Oo=1,Bo=2,Do=3,fs=4,ps=5,qn=6,hs=class extends If{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Af[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xf]=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=ee}_write(e,n,r){if(this._opcode===8&&this._state==ee)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Wn(r.buffer,r.byteOffset+e,r.length-e),new Wn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Wn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ee:this.getInfo(e);break;case Oo:this.getPayloadLength16(e);break;case Bo:this.getPayloadLength64(e);break;case Do:this.getMask();break;case fs:this.getData(e);break;case ps:case qn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Mo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Oo:this._payloadLength===127?this._state=Bo:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Do:this._state=fs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fs}getData(e){let n=Lo;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&&kf(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ps,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Mo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===ee&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ee;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ds(r,n):this._binaryType==="arraybuffer"?s=Cf(ds(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit("message",s,!0),this._state=ee,this.startLoop(e)}))}else{let s=ds(r,n);if(!this._skipUTF8Validation&&!No(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ps||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit("message",s,!1),this._state=ee,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Lo),this.end();else{let r=e.readUInt16BE(0);if(!Rf(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Wn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!No(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=ee;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ee):(this._state=qn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ee,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Tf]=s,o}};Fo.exports=hs});var vs=v((t_,Wo)=>{"use strict";var{Duplex:e_}=require("stream"),{randomFillSync:Ef}=require("crypto"),Ho=Vt(),{EMPTY_BUFFER:Pf,kWebSocket:Mf,NOOP:Lf}=ve(),{isBlob:pt,isValidStatusCode:Nf}=ft(),{mask:Uo,toBuffer:Ue}=$t(),te=Symbol("kByteLength"),Of=Buffer.alloc(4),Gn=8*1024,We,ht=Gn,ae=0,Bf=1,Df=2,ms=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ae,this.onerror=Lf,this[Mf]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Of,n.generateMask?n.generateMask(r):(ht===Gn&&(We===void 0&&(We=Buffer.alloc(Gn)),Ef(We,0,Gn),ht=0),r[0]=We[ht++],r[1]=We[ht++],r[2]=We[ht++],r[3]=We[ht++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[te]!==void 0?a=n[te]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(s?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]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(Uo(e,r,u,i,a),[u]):(Uo(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Pf;else{if(typeof e!="number"||!Nf(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={[te]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ae?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):pt(e)?(s=e.size,i=!1):(e=Ue(e),s=e.length,i=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[te]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ae?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):pt(e)?(s=e.size,i=!1):(e=Ue(e),s=e.length,i=Ue.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[te]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ae?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Ho.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):pt(e)?(a=e.size,l=!1):(e=Ue(e),a=e.length,l=Ue.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[te]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};pt(e)?this._state!==ae?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ae?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[te],this._state=Df,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ys,this,a,s);return}this._bufferedBytes-=r[te];let o=Ue(i);n?this.dispatch(o,n,r,s):(this._state=ae,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ff,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Ho.extensionName];this._bufferedBytes+=r[te],this._state=Bf,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ys(this,l,s);return}this._bufferedBytes-=r[te],this._state=ae,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ae&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][te],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][te],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)}};Wo.exports=ms;function ys(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ff(t,e,n){ys(t,e,n),t.onerror(e)}});var Ko=v((n_,Jo)=>{"use strict";var{kForOnEventAttribute:Yt,kListener:Ss}=ve(),qo=Symbol("kCode"),Go=Symbol("kData"),jo=Symbol("kError"),$o=Symbol("kMessage"),zo=Symbol("kReason"),gt=Symbol("kTarget"),Vo=Symbol("kType"),Yo=Symbol("kWasClean"),_e=class{constructor(e){this[gt]=null,this[Vo]=e}get target(){return this[gt]}get type(){return this[Vo]}};Object.defineProperty(_e.prototype,"target",{enumerable:!0});Object.defineProperty(_e.prototype,"type",{enumerable:!0});var qe=class extends _e{constructor(e,n={}){super(e),this[qo]=n.code===void 0?0:n.code,this[zo]=n.reason===void 0?"":n.reason,this[Yo]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[qo]}get reason(){return this[zo]}get wasClean(){return this[Yo]}};Object.defineProperty(qe.prototype,"code",{enumerable:!0});Object.defineProperty(qe.prototype,"reason",{enumerable:!0});Object.defineProperty(qe.prototype,"wasClean",{enumerable:!0});var mt=class extends _e{constructor(e,n={}){super(e),this[jo]=n.error===void 0?null:n.error,this[$o]=n.message===void 0?"":n.message}get error(){return this[jo]}get message(){return this[$o]}};Object.defineProperty(mt.prototype,"error",{enumerable:!0});Object.defineProperty(mt.prototype,"message",{enumerable:!0});var Jt=class extends _e{constructor(e,n={}){super(e),this[Go]=n.data===void 0?null:n.data}get data(){return this[Go]}};Object.defineProperty(Jt.prototype,"data",{enumerable:!0});var Hf={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Yt]&&s[Ss]===e&&!s[Yt])return;let r;if(t==="message")r=function(i,o){let a=new Jt("message",{data:o?i:i.toString()});a[gt]=this,jn(e,this,a)};else if(t==="close")r=function(i,o){let a=new qe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[gt]=this,jn(e,this,a)};else if(t==="error")r=function(i){let o=new mt("error",{error:i,message:i.message});o[gt]=this,jn(e,this,o)};else if(t==="open")r=function(){let i=new _e("open");i[gt]=this,jn(e,this,i)};else return;r[Yt]=!!n[Yt],r[Ss]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ss]===e&&!n[Yt]){this.removeListener(t,n);break}}};Jo.exports={CloseEvent:qe,ErrorEvent:mt,Event:_e,EventTarget:Hf,MessageEvent:Jt};function jn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var _s=v((r_,Xo)=>{"use strict";var{tokenChars:Kt}=ft();function he(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Uf(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!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&&Kt[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&&Kt[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(s){if(Kt[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Kt[u]===1)l===-1&&(l=d);else if(u===34&&l!==-1)i=!1,c=d;else if(u===92)s=!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&&Kt[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);r&&(h=h.replace(/\\/g,""),r=!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 p=t.slice(l,c);return o===void 0?he(e,p,n):(a===void 0?he(n,p,!0):r?he(n,a,p.replace(/\\/g,"")):he(n,a,p),he(e,o,n)),e}function Wf(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Xo.exports={format:Wf,parse:Uf}});var Yn=v((o_,ca)=>{"use strict";var qf=require("events"),Gf=require("https"),jf=require("http"),ea=require("net"),$f=require("tls"),{randomBytes:zf,createHash:Vf}=require("crypto"),{Duplex:s_,Readable:i_}=require("stream"),{URL:bs}=require("url"),ke=Vt(),Yf=gs(),Jf=vs(),{isBlob:Kf}=ft(),{BINARY_TYPES:Qo,CLOSE_TIMEOUT:Xf,EMPTY_BUFFER:$n,GUID:Qf,kForOnEventAttribute:ws,kListener:Zf,kStatusCode:ep,kWebSocket:W,NOOP:ta}=ve(),{EventTarget:{addEventListener:tp,removeEventListener:np}}=Ko(),{format:rp,parse:sp}=_s(),{toBuffer:ip}=$t(),na=Symbol("kAborted"),Is=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],op=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,L=class t extends qf{constructor(e,n,r){super(),this._binaryType=Qo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$n,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),ra(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Qo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Yf({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Jf(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[W]=this,i[W]=this,e[W]=this,s.on("conclude",cp),s.on("drain",up),s.on("error",dp),s.on("message",fp),s.on("ping",pp),s.on("pong",hp),i.onerror=gp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",oa),e.on("data",Vn),e.on("end",aa),e.on("error",la),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[ke.extensionName]&&this._extensions[ke.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){Q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ia(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){As(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||$n,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){As(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||$n,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){As(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[ke.extensionName]||(s.compress=!1),this._sender.send(e||$n,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(L,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(L.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(L,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(L.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(L,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(L.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(L,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(L.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(L.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(L.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ws])return e[Zf];return null},set(e){for(let n of this.listeners(t))if(n[ws]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ws]:!0})}})});L.prototype.addEventListener=tp;L.prototype.removeEventListener=np;ca.exports=L;function ra(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Xf,protocolVersion:Is[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Is.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Is.join(", ")})`);let i;if(e instanceof bs)i=e;else try{i=new bs(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 f=new SyntaxError(l);if(t._redirects===0)throw f;zn(t,f);return}let u=o?443:80,c=zf(16).toString("base64"),d=o?Gf.request:jf.request,p=new Set,h;if(s.createConnection=s.createConnection||(o?lp:ap),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new ke(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=rp({[ke.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!op.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let f=s.path.split(":");s.socketPath=f[0],s.path=f[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[m,y]of Object.entries(f))r.headers[m.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,f||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Q(t,g,"Opening handshake has timed out")}),g.on("error",f=>{g===null||g[na]||(g=t._req=null,zn(t,f))}),g.on("response",f=>{let m=f.headers.location,y=f.statusCode;if(m&&s.followRedirects&&y>=300&&y<400){if(++t._redirects>s.maxRedirects){Q(t,g,"Maximum redirects exceeded");return}g.abort();let A;try{A=new bs(m,e)}catch{let w=new SyntaxError(`Invalid URL: ${m}`);zn(t,w);return}ra(t,A,n,r)}else t.emit("unexpected-response",g,f)||Q(t,g,`Unexpected server response: ${f.statusCode}`)}),g.on("upgrade",(f,m,y)=>{if(t.emit("upgrade",f),t.readyState!==L.CONNECTING)return;g=t._req=null;let A=f.headers.upgrade;if(A===void 0||A.toLowerCase()!=="websocket"){Q(t,m,"Invalid Upgrade header");return}let T=Vf("sha1").update(c+Qf).digest("base64");if(f.headers["sec-websocket-accept"]!==T){Q(t,m,"Invalid Sec-WebSocket-Accept header");return}let w=f.headers["sec-websocket-protocol"],C;if(w!==void 0?p.size?p.has(w)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":p.size&&(C="Server sent no subprotocol"),C){Q(t,m,C);return}w&&(t._protocol=w);let P=f.headers["sec-websocket-extensions"];if(P!==void 0){if(!h){Q(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let G;try{G=sp(P)}catch{Q(t,m,"Invalid Sec-WebSocket-Extensions header");return}let ye=Object.keys(G);if(ye.length!==1||ye[0]!==ke.extensionName){Q(t,m,"Server indicated an extension that was not requested");return}try{h.accept(G[ke.extensionName])}catch{Q(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ke.extensionName]=h}t.setSocket(m,y,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function zn(t,e){t._readyState=L.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function ap(t){return t.path=t.socketPath,ea.connect(t)}function lp(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ea.isIP(t.host)?"":t.host),$f.connect(t)}function Q(t,e,n){t._readyState=L.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Q),e.setHeader?(e[na]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(zn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function As(t,e,n){if(e){let r=Kf(e)?e.size:ip(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,r)}}function cp(t,e){let n=this[W];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[W]!==void 0&&(n._socket.removeListener("data",Vn),process.nextTick(sa,n._socket),t===1005?n.close():n.close(t,e))}function up(){let t=this[W];t.isPaused||t._socket.resume()}function dp(t){let e=this[W];e._socket[W]!==void 0&&(e._socket.removeListener("data",Vn),process.nextTick(sa,e._socket),e.close(t[ep])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Zo(){this[W].emitClose()}function fp(t,e){this[W].emit("message",t,e)}function pp(t){let e=this[W];e._autoPong&&e.pong(t,!this._isServer,ta),e.emit("ping",t)}function hp(t){this[W].emit("pong",t)}function sa(t){t.resume()}function gp(t){let e=this[W];e.readyState!==L.CLOSED&&(e.readyState===L.OPEN&&(e._readyState=L.CLOSING,ia(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ia(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function oa(){let t=this[W];if(this.removeListener("close",oa),this.removeListener("data",Vn),this.removeListener("end",aa),t._readyState=L.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[W]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Zo),t._receiver.on("finish",Zo))}function Vn(t){this[W]._receiver.write(t)||this.pause()}function aa(){let t=this[W];t._readyState=L.CLOSING,t._receiver.end(),this.end()}function la(){let t=this[W];this.removeListener("error",la),this.on("error",ta),t&&(t._readyState=L.CLOSING,this.destroy())}});var pa=v((l_,fa)=>{"use strict";var a_=Yn(),{Duplex:mp}=require("stream");function ua(t){t.emit("close")}function yp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function da(t){this.removeListener("error",da),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function vp(t,e){let n=!0,r=new mp({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(ua,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(ua,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",yp),r.on("error",da),r}fa.exports=vp});var ga=v((c_,ha)=>{"use strict";var{tokenChars:Sp}=ft();function _p(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Sp[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ha.exports={parse:_p}});var wa=v((d_,ba)=>{"use strict";var bp=require("events"),Jn=require("http"),{Duplex:u_}=require("stream"),{createHash:wp}=require("crypto"),ma=_s(),Ge=Vt(),Ip=ga(),Ap=Yn(),{CLOSE_TIMEOUT:Tp,GUID:xp,kWebSocket:Cp}=ve(),kp=/^[+/0-9A-Za-z]{22}==$/,ya=0,va=1,_a=2,Ts=class extends bp{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Tp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ap,...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=Jn.createServer((r,s)=>{let i=Jn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Rp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ya}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===_a){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xt,this);return}if(e&&this.once("close",e),this._state!==va)if(this._state=va,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(Xt,this):process.nextTick(Xt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Xt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Sa);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){je(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){je(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!kp.test(i)){je(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){je(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qt(n,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=Ip.parse(l)}catch{je(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 p=new Ge(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=ma.parse(c);h[Ge.extensionName]&&(p.accept(h[Ge.extensionName]),d[Ge.extensionName]=p)}catch{je(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={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(p,(h,g,f,m)=>{if(!h)return Qt(n,g||401,f,m);this.completeUpgrade(d,i,u,e,n,r,s)});return}if(!this.options.verifyClient(p))return Qt(n,401)}this.completeUpgrade(d,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Cp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ya)return Qt(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wp("sha1").update(n+xp).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),c._protocol=d)}if(e[Ge.extensionName]){let d=e[Ge.extensionName].params,p=ma.format({[Ge.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),c._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",ya),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(Kt,this)})),a(c,s)}};Sa.exports=ws;function Cp(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Kt(t){t._state=va,t.emit("close")}function ya(){this.destroy()}function Xt(t,e,n,r){n=n||Yn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Yn.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",Sa),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(Xt,this)})),a(c,s)}};ba.exports=Ts;function Rp(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Xt(t){t._state=_a,t.emit("close")}function Sa(){this.destroy()}function Qt(t,e,n,r){n=n||Jn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Jn.STATUS_CODES[e]}\r
4
4
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function Ge(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ge),t.emit("wsClientError",o,n,e)}else Xt(n,r,s,i)}});var As=v((r_,ba)=>{ba.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ke=v(je=>{var xs,Pp=[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];je.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};je.getSymbolTotalCodewords=function(e){return Pp[e]};je.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};je.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');xs=e};je.isKanjiModeEnabled=function(){return typeof xs<"u"};je.toSJIS=function(e){return xs(e)}});var Jn=v(ne=>{ne.L={bit:1};ne.M={bit:0};ne.Q={bit:3};ne.H={bit:2};function Mp(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ne.L;case"m":case"medium":return ne.M;case"q":case"quartile":return ne.Q;case"h":case"high":return ne.H;default:throw new Error("Unknown EC Level: "+t)}}ne.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ne.from=function(e,n){if(ne.isValid(e))return e;try{return Mp(e)}catch{return n}}});var Aa=v((o_,Ia)=>{function wa(){this.buffer=[],this.length=0}wa.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Ia.exports=wa});var Ca=v((a_,xa)=>{function Qt(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)}Qt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Qt.prototype.get=function(t,e){return this.data[t*this.size+e]};Qt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Qt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};xa.exports=Qt});var Ta=v(Kn=>{var Lp=ke().getSymbolSize;Kn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Lp(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Kn.getPositions=function(e){let n=[],r=Kn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var Ea=v(Ra=>{var Np=ke().getSymbolSize,ka=7;Ra.getPositions=function(e){let n=Np(e);return[[0,0],[n-ka,0],[0,n-ka]]}});var Pa=v(k=>{k.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var $e={N1:3,N2:3,N3:40,N4:10};k.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};k.from=function(e){return k.isValid(e)?parseInt(e,10):void 0};k.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?s++:(s>=5&&(r+=$e.N1+(s-5)),o=c,s=1),c=e.get(u,l),c===a?i++:(i>=5&&(r+=$e.N1+(i-5)),a=c,i=1)}s>=5&&(r+=$e.N1+(s-5)),i>=5&&(r+=$e.N1+(i-5))}return r};k.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*$e.N2};k.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*$e.N3};k.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*$e.N4};function Op(t,e,n){switch(t){case k.Patterns.PATTERN000:return(e+n)%2===0;case k.Patterns.PATTERN001:return e%2===0;case k.Patterns.PATTERN010:return n%3===0;case k.Patterns.PATTERN011:return(e+n)%3===0;case k.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case k.Patterns.PATTERN101:return e*n%2+e*n%3===0;case k.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case k.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}k.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Op(e,i,s))};k.getBestMask=function(e,n){let r=Object.keys(k.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),k.applyMask(o,e);let a=k.getPenaltyN1(e)+k.getPenaltyN2(e)+k.getPenaltyN3(e)+k.getPenaltyN4(e);k.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Ts=v(Cs=>{var Re=Jn(),Xn=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Qn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Cs.getBlocksCount=function(e,n){switch(n){case Re.L:return Xn[(e-1)*4+0];case Re.M:return Xn[(e-1)*4+1];case Re.Q:return Xn[(e-1)*4+2];case Re.H:return Xn[(e-1)*4+3];default:return}};Cs.getTotalCodewordsCount=function(e,n){switch(n){case Re.L:return Qn[(e-1)*4+0];case Re.M:return Qn[(e-1)*4+1];case Re.Q:return Qn[(e-1)*4+2];case Re.H:return Qn[(e-1)*4+3];default:return}}});var Ma=v(er=>{var Zt=new Uint8Array(512),Zn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Zt[n]=e,Zn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Zt[n]=Zt[n-255]})();er.log=function(e){if(e<1)throw new Error("log("+e+")");return Zn[e]};er.exp=function(e){return Zt[e]};er.mul=function(e,n){return e===0||n===0?0:Zt[Zn[e]+Zn[n]]}});var La=v(en=>{var ks=Ma();en.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=ks.mul(e[s],n[i]);return r};en.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=ks.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};en.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=en.mul(n,new Uint8Array([1,ks.exp(r)]));return n}});var Ba=v((h_,Oa)=>{var Na=La();function Rs(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Rs.prototype.initialize=function(e){this.degree=e,this.genPoly=Na.generateECPolynomial(this.degree)};Rs.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=Na.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Oa.exports=Rs});var Es=v(Da=>{Da.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Ps=v(be=>{var Fa="[0-9]+",Bp="[A-Z $%*+\\-./:]+",tn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";tn=tn.replace(/u/g,"\\u");var Dp="(?:(?![A-Z0-9 $%*+\\-./:]|"+tn+`)(?:.|[\r
8
- ]))+`;be.KANJI=new RegExp(tn,"g");be.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");be.BYTE=new RegExp(Dp,"g");be.NUMERIC=new RegExp(Fa,"g");be.ALPHANUMERIC=new RegExp(Bp,"g");var Fp=new RegExp("^"+tn+"$"),Hp=new RegExp("^"+Fa+"$"),Up=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");be.testKanji=function(e){return Fp.test(e)};be.testNumeric=function(e){return Hp.test(e)};be.testAlphanumeric=function(e){return Up.test(e)}});var Ee=v(B=>{var qp=Es(),Ms=Ps();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(!qp.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 Ms.testNumeric(e)?B.NUMERIC:Ms.testAlphanumeric(e)?B.ALPHANUMERIC:Ms.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 Wp(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 Wp(e)}catch{return n}}});var Ga=v(ze=>{var tr=ke(),Gp=Ts(),Ha=Jn(),Pe=Ee(),Ls=Es(),qa=7973,Ua=tr.getBCHDigit(qa);function jp(t,e,n){for(let r=1;r<=40;r++)if(e<=ze.getCapacity(r,n,t))return r}function Wa(t,e){return Pe.getCharCountIndicator(t,e)+4}function $p(t,e){let n=0;return t.forEach(function(r){let s=Wa(r.mode,e);n+=s+r.getBitsLength()}),n}function zp(t,e){for(let n=1;n<=40;n++)if($p(t,n)<=ze.getCapacity(n,e,Pe.MIXED))return n}ze.from=function(e,n){return Ls.isValid(e)?parseInt(e,10):n};ze.getCapacity=function(e,n,r){if(!Ls.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Pe.BYTE);let s=tr.getSymbolTotalCodewords(e),i=Gp.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Pe.MIXED)return o;let a=o-Wa(r,e);switch(r){case Pe.NUMERIC:return Math.floor(a/10*3);case Pe.ALPHANUMERIC:return Math.floor(a/11*2);case Pe.KANJI:return Math.floor(a/13);case Pe.BYTE:default:return Math.floor(a/8)}};ze.getBestVersionForData=function(e,n){let r,s=Ha.from(n,Ha.M);if(Array.isArray(e)){if(e.length>1)return zp(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return jp(r.mode,r.getLength(),s)};ze.getEncodedBits=function(e){if(!Ls.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;tr.getBCHDigit(n)-Ua>=0;)n^=qa<<tr.getBCHDigit(n)-Ua;return e<<12|n}});var Va=v(za=>{var Ns=ke(),$a=1335,Vp=21522,ja=Ns.getBCHDigit($a);za.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Ns.getBCHDigit(s)-ja>=0;)s^=$a<<Ns.getBCHDigit(s)-ja;return(r<<10|s)^Vp}});var Ja=v((__,Ya)=>{var Yp=Ee();function yt(t){this.mode=Yp.NUMERIC,this.data=t.toString()}yt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};yt.prototype.getLength=function(){return this.data.length};yt.prototype.getBitsLength=function(){return yt.getBitsLength(this.data.length)};yt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Ya.exports=yt});var Xa=v((b_,Ka)=>{var Jp=Ee(),Os=["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 vt(t){this.mode=Jp.ALPHANUMERIC,this.data=t}vt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};vt.prototype.getLength=function(){return this.data.length};vt.prototype.getBitsLength=function(){return vt.getBitsLength(this.data.length)};vt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Os.indexOf(this.data[n])*45;r+=Os.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Os.indexOf(this.data[n]),6)};Ka.exports=vt});var Za=v((w_,Qa)=>{var Kp=Ee();function St(t){this.mode=Kp.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}St.getBitsLength=function(e){return e*8};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Qa.exports=St});var tl=v((I_,el)=>{var Xp=Ee(),Qp=ke();function _t(t){this.mode=Xp.KANJI,this.data=t}_t.getBitsLength=function(e){return e*13};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Qp.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)}};el.exports=_t});var nl=v((A_,Bs)=>{"use strict";var nn={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=nn.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,f,g,h;!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,g=s[l],h=typeof s[l]>"u",(h||g>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=nn.single_source_shortest_paths(t,e,n);return nn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=nn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Bs<"u"&&(Bs.exports=nn)});var ul=v(bt=>{var C=Ee(),il=Ja(),ol=Xa(),al=Za(),ll=tl(),rn=Ps(),nr=ke(),Zp=nl();function rl(t){return unescape(encodeURIComponent(t)).length}function sn(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function cl(t){let e=sn(rn.NUMERIC,C.NUMERIC,t),n=sn(rn.ALPHANUMERIC,C.ALPHANUMERIC,t),r,s;return nr.isKanjiModeEnabled()?(r=sn(rn.BYTE,C.BYTE,t),s=sn(rn.KANJI,C.KANJI,t)):(r=sn(rn.BYTE_KANJI,C.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Ds(t,e){switch(e){case C.NUMERIC:return il.getBitsLength(t);case C.ALPHANUMERIC:return ol.getBitsLength(t);case C.KANJI:return ll.getBitsLength(t);case C.BYTE:return al.getBitsLength(t)}}function eh(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function th(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case C.NUMERIC:e.push([r,{data:r.data,mode:C.ALPHANUMERIC,length:r.length},{data:r.data,mode:C.BYTE,length:r.length}]);break;case C.ALPHANUMERIC:e.push([r,{data:r.data,mode:C.BYTE,length:r.length}]);break;case C.KANJI:e.push([r,{data:r.data,mode:C.BYTE,length:rl(r.data)}]);break;case C.BYTE:e.push([{data:r.data,mode:C.BYTE,length:rl(r.data)}])}}return e}function nh(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},r[c]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===u.mode?(r[f][c]=Ds(n[f].lastCount+u.length,u.mode)-Ds(n[f].lastCount,u.mode),n[f].lastCount+=u.length):(n[f]&&(n[f].lastCount=u.length),r[f][c]=Ds(u.length,u.mode)+4+C.getCharCountIndicator(u.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function sl(t,e){let n,r=C.getBestModeForData(t);if(n=C.from(e,r),n!==C.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+C.toString(n)+`.
10
- Suggested mode is: `+C.toString(r));switch(n===C.KANJI&&!nr.isKanjiModeEnabled()&&(n=C.BYTE),n){case C.NUMERIC:return new il(t);case C.ALPHANUMERIC:return new ol(t);case C.KANJI:return new ll(t);case C.BYTE:return new al(t)}}bt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(sl(r,null)):r.data&&n.push(sl(r.data,r.mode)),n},[])};bt.fromString=function(e,n){let r=cl(e,nr.isKanjiModeEnabled()),s=th(r),i=nh(s,n),o=Zp.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return bt.fromArray(eh(a))};bt.rawSplit=function(e){return bt.fromArray(cl(e,nr.isKanjiModeEnabled()))}});var Gs=v(dl=>{var sr=ke(),Fs=Jn(),rh=Aa(),sh=Ca(),ih=Ta(),oh=Ea(),qs=Pa(),Ws=Ts(),ah=Ba(),rr=Ga(),lh=Va(),ch=Ee(),Hs=ul();function uh(t,e){let n=t.size,r=oh.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function dh(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function fh(t,e){let n=ih.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function ph(t,e){let n=t.size,r=rr.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Us(t,e,n){let r=t.size,s=lh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function hh(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(s,a-l,u),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function gh(t,e,n){let r=new rh;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),ch.getCharCountIndicator(l.mode,t)),l.write(r)});let s=sr.getSymbolTotalCodewords(t),i=Ws.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return mh(r,t,e)}function mh(t,e,n){let r=sr.getSymbolTotalCodewords(e),s=Ws.getTotalCodewordsCount(e,n),i=r-s,o=Ws.getBlocksCount(e,n),a=r%o,l=o-a,u=Math.floor(r/o),c=Math.floor(i/o),d=c+1,f=u-c,g=new ah(f),h=0,p=new Array(o),m=new Array(o),y=0,w=new Uint8Array(t.buffer);for(let z=0;z<o;z++){let lt=z<l?c:d;p[z]=w.slice(h,h+lt),m[z]=g.encode(p[z]),h+=lt,y=Math.max(y,lt)}let A=new Uint8Array(r),x=0,T,W;for(T=0;T<y;T++)for(W=0;W<o;W++)T<p[W].length&&(A[x++]=p[W][T]);for(T=0;T<f;T++)for(W=0;W<o;W++)A[x++]=m[W][T];return A}function yh(t,e,n,r){let s;if(Array.isArray(t))s=Hs.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=Hs.rawSplit(t);u=rr.getBestVersionForData(c,n)}s=Hs.fromString(t,u||40)}else throw new Error("Invalid data");let i=rr.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
7
+ `+n)}function je(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,je),t.emit("wsClientError",o,n,e)}else Qt(n,r,s,i)}});var Cs=v((p_,Ia)=>{Ia.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Re=v($e=>{var ks,Np=[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];$e.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};$e.getSymbolTotalCodewords=function(e){return Np[e]};$e.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};$e.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ks=e};$e.isKanjiModeEnabled=function(){return typeof ks<"u"};$e.toSJIS=function(e){return ks(e)}});var Kn=v(ne=>{ne.L={bit:1};ne.M={bit:0};ne.Q={bit:3};ne.H={bit:2};function Op(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ne.L;case"m":case"medium":return ne.M;case"q":case"quartile":return ne.Q;case"h":case"high":return ne.H;default:throw new Error("Unknown EC Level: "+t)}}ne.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ne.from=function(e,n){if(ne.isValid(e))return e;try{return Op(e)}catch{return n}}});var xa=v((m_,Ta)=>{function Aa(){this.buffer=[],this.length=0}Aa.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++}};Ta.exports=Aa});var ka=v((y_,Ca)=>{function Zt(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)}Zt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Zt.prototype.get=function(t,e){return this.data[t*this.size+e]};Zt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Zt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ca.exports=Zt});var Ra=v(Xn=>{var Bp=Re().getSymbolSize;Xn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Bp(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Xn.getPositions=function(e){let n=[],r=Xn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var Ma=v(Pa=>{var Dp=Re().getSymbolSize,Ea=7;Pa.getPositions=function(e){let n=Dp(e);return[[0,0],[n-Ea,0],[0,n-Ea]]}});var La=v(k=>{k.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var ze={N1:3,N2:3,N3:40,N4:10};k.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};k.from=function(e){return k.isValid(e)?parseInt(e,10):void 0};k.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let u=0;u<n;u++){let c=e.get(l,u);c===o?s++:(s>=5&&(r+=ze.N1+(s-5)),o=c,s=1),c=e.get(u,l),c===a?i++:(i>=5&&(r+=ze.N1+(i-5)),a=c,i=1)}s>=5&&(r+=ze.N1+(s-5)),i>=5&&(r+=ze.N1+(i-5))}return r};k.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*ze.N2};k.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*ze.N3};k.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*ze.N4};function Fp(t,e,n){switch(t){case k.Patterns.PATTERN000:return(e+n)%2===0;case k.Patterns.PATTERN001:return e%2===0;case k.Patterns.PATTERN010:return n%3===0;case k.Patterns.PATTERN011:return(e+n)%3===0;case k.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case k.Patterns.PATTERN101:return e*n%2+e*n%3===0;case k.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case k.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}k.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Fp(e,i,s))};k.getBestMask=function(e,n){let r=Object.keys(k.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),k.applyMask(o,e);let a=k.getPenaltyN1(e)+k.getPenaltyN2(e)+k.getPenaltyN3(e)+k.getPenaltyN4(e);k.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Es=v(Rs=>{var Ee=Kn(),Qn=[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],Zn=[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];Rs.getBlocksCount=function(e,n){switch(n){case Ee.L:return Qn[(e-1)*4+0];case Ee.M:return Qn[(e-1)*4+1];case Ee.Q:return Qn[(e-1)*4+2];case Ee.H:return Qn[(e-1)*4+3];default:return}};Rs.getTotalCodewordsCount=function(e,n){switch(n){case Ee.L:return Zn[(e-1)*4+0];case Ee.M:return Zn[(e-1)*4+1];case Ee.Q:return Zn[(e-1)*4+2];case Ee.H:return Zn[(e-1)*4+3];default:return}}});var Na=v(tr=>{var en=new Uint8Array(512),er=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)en[n]=e,er[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)en[n]=en[n-255]})();tr.log=function(e){if(e<1)throw new Error("log("+e+")");return er[e]};tr.exp=function(e){return en[e]};tr.mul=function(e,n){return e===0||n===0?0:en[er[e]+er[n]]}});var Oa=v(tn=>{var Ps=Na();tn.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=Ps.mul(e[s],n[i]);return r};tn.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=Ps.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};tn.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=tn.mul(n,new Uint8Array([1,Ps.exp(r)]));return n}});var Fa=v((A_,Da)=>{var Ba=Oa();function Ms(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ms.prototype.initialize=function(e){this.degree=e,this.genPoly=Ba.generateECPolynomial(this.degree)};Ms.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=Ba.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Da.exports=Ms});var Ls=v(Ha=>{Ha.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Ns=v(we=>{var Ua="[0-9]+",Hp="[A-Z $%*+\\-./:]+",nn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";nn=nn.replace(/u/g,"\\u");var Up="(?:(?![A-Z0-9 $%*+\\-./:]|"+nn+`)(?:.|[\r
8
+ ]))+`;we.KANJI=new RegExp(nn,"g");we.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");we.BYTE=new RegExp(Up,"g");we.NUMERIC=new RegExp(Ua,"g");we.ALPHANUMERIC=new RegExp(Hp,"g");var Wp=new RegExp("^"+nn+"$"),qp=new RegExp("^"+Ua+"$"),Gp=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");we.testKanji=function(e){return Wp.test(e)};we.testNumeric=function(e){return qp.test(e)};we.testAlphanumeric=function(e){return Gp.test(e)}});var Pe=v(D=>{var jp=Ls(),Os=Ns();D.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};D.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};D.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};D.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};D.MIXED={bit:-1};D.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!jp.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};D.getBestModeForData=function(e){return Os.testNumeric(e)?D.NUMERIC:Os.testAlphanumeric(e)?D.ALPHANUMERIC:Os.testKanji(e)?D.KANJI:D.BYTE};D.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};D.isValid=function(e){return e&&e.bit&&e.ccBits};function $p(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return D.NUMERIC;case"alphanumeric":return D.ALPHANUMERIC;case"kanji":return D.KANJI;case"byte":return D.BYTE;default:throw new Error("Unknown mode: "+t)}}D.from=function(e,n){if(D.isValid(e))return e;try{return $p(e)}catch{return n}}});var $a=v(Ve=>{var nr=Re(),zp=Es(),Wa=Kn(),Me=Pe(),Bs=Ls(),Ga=7973,qa=nr.getBCHDigit(Ga);function Vp(t,e,n){for(let r=1;r<=40;r++)if(e<=Ve.getCapacity(r,n,t))return r}function ja(t,e){return Me.getCharCountIndicator(t,e)+4}function Yp(t,e){let n=0;return t.forEach(function(r){let s=ja(r.mode,e);n+=s+r.getBitsLength()}),n}function Jp(t,e){for(let n=1;n<=40;n++)if(Yp(t,n)<=Ve.getCapacity(n,e,Me.MIXED))return n}Ve.from=function(e,n){return Bs.isValid(e)?parseInt(e,10):n};Ve.getCapacity=function(e,n,r){if(!Bs.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Me.BYTE);let s=nr.getSymbolTotalCodewords(e),i=zp.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Me.MIXED)return o;let a=o-ja(r,e);switch(r){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)}};Ve.getBestVersionForData=function(e,n){let r,s=Wa.from(n,Wa.M);if(Array.isArray(e)){if(e.length>1)return Jp(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Vp(r.mode,r.getLength(),s)};Ve.getEncodedBits=function(e){if(!Bs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;nr.getBCHDigit(n)-qa>=0;)n^=Ga<<nr.getBCHDigit(n)-qa;return e<<12|n}});var Ja=v(Ya=>{var Ds=Re(),Va=1335,Kp=21522,za=Ds.getBCHDigit(Va);Ya.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Ds.getBCHDigit(s)-za>=0;)s^=Va<<Ds.getBCHDigit(s)-za;return(r<<10|s)^Kp}});var Xa=v((E_,Ka)=>{var Xp=Pe();function yt(t){this.mode=Xp.NUMERIC,this.data=t.toString()}yt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};yt.prototype.getLength=function(){return this.data.length};yt.prototype.getBitsLength=function(){return yt.getBitsLength(this.data.length)};yt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Ka.exports=yt});var Za=v((P_,Qa)=>{var Qp=Pe(),Fs=["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 vt(t){this.mode=Qp.ALPHANUMERIC,this.data=t}vt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};vt.prototype.getLength=function(){return this.data.length};vt.prototype.getBitsLength=function(){return vt.getBitsLength(this.data.length)};vt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Fs.indexOf(this.data[n])*45;r+=Fs.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Fs.indexOf(this.data[n]),6)};Qa.exports=vt});var tl=v((M_,el)=>{var Zp=Pe();function St(t){this.mode=Zp.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}St.getBitsLength=function(e){return e*8};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};el.exports=St});var rl=v((L_,nl)=>{var eh=Pe(),th=Re();function _t(t){this.mode=eh.KANJI,this.data=t}_t.getBitsLength=function(e){return e*13};_t.prototype.getLength=function(){return this.data.length};_t.prototype.getBitsLength=function(){return _t.getBitsLength(this.data.length)};_t.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=th.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)}};nl.exports=_t});var sl=v((N_,Hs)=>{"use strict";var rn={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=rn.PriorityQueue.make();i.push(e,0);for(var o,a,l,u,c,d,p,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],p=u+d,h=s[l],g=typeof s[l]>"u",(g||h>p)&&(s[l]=p,i.push(l,p),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var f=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(f)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=rn.single_source_shortest_paths(t,e,n);return rn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=rn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Hs<"u"&&(Hs.exports=rn)});var fl=v(bt=>{var x=Pe(),al=Xa(),ll=Za(),cl=tl(),ul=rl(),sn=Ns(),rr=Re(),nh=sl();function il(t){return unescape(encodeURIComponent(t)).length}function on(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function dl(t){let e=on(sn.NUMERIC,x.NUMERIC,t),n=on(sn.ALPHANUMERIC,x.ALPHANUMERIC,t),r,s;return rr.isKanjiModeEnabled()?(r=on(sn.BYTE,x.BYTE,t),s=on(sn.KANJI,x.KANJI,t)):(r=on(sn.BYTE_KANJI,x.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Us(t,e){switch(e){case x.NUMERIC:return al.getBitsLength(t);case x.ALPHANUMERIC:return ll.getBitsLength(t);case x.KANJI:return ul.getBitsLength(t);case x.BYTE:return cl.getBitsLength(t)}}function rh(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function sh(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case x.NUMERIC:e.push([r,{data:r.data,mode:x.ALPHANUMERIC,length:r.length},{data:r.data,mode:x.BYTE,length:r.length}]);break;case x.ALPHANUMERIC:e.push([r,{data:r.data,mode:x.BYTE,length:r.length}]);break;case x.KANJI:e.push([r,{data:r.data,mode:x.BYTE,length:il(r.data)}]);break;case x.BYTE:e.push([{data:r.data,mode:x.BYTE,length:il(r.data)}])}}return e}function ih(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let u=o[l],c=""+i+l;a.push(c),n[c]={node:u,lastCount:0},r[c]={};for(let d=0;d<s.length;d++){let p=s[d];n[p]&&n[p].node.mode===u.mode?(r[p][c]=Us(n[p].lastCount+u.length,u.mode)-Us(n[p].lastCount,u.mode),n[p].lastCount+=u.length):(n[p]&&(n[p].lastCount=u.length),r[p][c]=Us(u.length,u.mode)+4+x.getCharCountIndicator(u.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function ol(t,e){let n,r=x.getBestModeForData(t);if(n=x.from(e,r),n!==x.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+x.toString(n)+`.
10
+ Suggested mode is: `+x.toString(r));switch(n===x.KANJI&&!rr.isKanjiModeEnabled()&&(n=x.BYTE),n){case x.NUMERIC:return new al(t);case x.ALPHANUMERIC:return new ll(t);case x.KANJI:return new ul(t);case x.BYTE:return new cl(t)}}bt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(ol(r,null)):r.data&&n.push(ol(r.data,r.mode)),n},[])};bt.fromString=function(e,n){let r=dl(e,rr.isKanjiModeEnabled()),s=sh(r),i=ih(s,n),o=nh.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return bt.fromArray(rh(a))};bt.rawSplit=function(e){return bt.fromArray(dl(e,rr.isKanjiModeEnabled()))}});var zs=v(pl=>{var ir=Re(),Ws=Kn(),oh=xa(),ah=ka(),lh=Ra(),ch=Ma(),js=La(),$s=Es(),uh=Fa(),sr=$a(),dh=Ja(),fh=Pe(),qs=fl();function ph(t,e){let n=t.size,r=ch.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function hh(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function gh(t,e){let n=lh.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function mh(t,e){let n=t.size,r=sr.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Gs(t,e,n){let r=t.size,s=dh.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function yh(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),t.set(s,a-l,u),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function vh(t,e,n){let r=new oh;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),fh.getCharCountIndicator(l.mode,t)),l.write(r)});let s=ir.getSymbolTotalCodewords(t),i=$s.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Sh(r,t,e)}function Sh(t,e,n){let r=ir.getSymbolTotalCodewords(e),s=$s.getTotalCodewordsCount(e,n),i=r-s,o=$s.getBlocksCount(e,n),a=r%o,l=o-a,u=Math.floor(r/o),c=Math.floor(i/o),d=c+1,p=u-c,h=new uh(p),g=0,f=new Array(o),m=new Array(o),y=0,A=new Uint8Array(t.buffer);for(let G=0;G<o;G++){let ye=G<l?c:d;f[G]=A.slice(g,g+ye),m[G]=h.encode(f[G]),g+=ye,y=Math.max(y,ye)}let T=new Uint8Array(r),w=0,C,P;for(C=0;C<y;C++)for(P=0;P<o;P++)C<f[P].length&&(T[w++]=f[P][C]);for(C=0;C<p;C++)for(P=0;P<o;P++)T[w++]=m[P][C];return T}function _h(t,e,n,r){let s;if(Array.isArray(t))s=qs.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let c=qs.rawSplit(t);u=sr.getBestVersionForData(c,n)}s=qs.fromString(t,u||40)}else throw new Error("Invalid data");let i=sr.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
12
  Minimum version required to store current data is: `+i+`.
13
- `);let o=gh(e,n,s),a=sr.getSymbolSize(e),l=new sh(a);return uh(l,e),dh(l),fh(l,e),Us(l,n,0),e>=7&&ph(l,e),hh(l,o),isNaN(r)&&(r=qs.getBestMask(l,Us.bind(null,l,n))),qs.applyMask(r,l),Us(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}dl.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Fs.M,s,i;return typeof n<"u"&&(r=Fs.from(n.errorCorrectionLevel,Fs.M),s=rr.from(n.version),i=qs.from(n.maskPattern),n.toSJISFunc&&sr.setToSJISFunction(n.toSJISFunc)),yh(e,s,r,i)}});var js=v((T_,pl)=>{"use strict";var vh=require("util"),fl=require("stream"),le=pl.exports=function(){fl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};vh.inherits(le,fl);le.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))};le.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};le.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()))};le.prototype.destroySoon=le.prototype.end;le.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};le.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};le.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))};le.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};le.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 zs=v($s=>{"use strict";var Me=[{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]}];$s.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Me.length;a++){let l=Me[a],u=i*l.x.length,c=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};$s.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Me[r].x.length,i=(e-s)/Me[r].x.length*8+Me[r].x[s],o=n%Me[r].y.length,a=(n-o)/Me[r].y.length*8+Me[r].y[o];return i*4+a*t*4}}});var Vs=v((R_,hl)=>{"use strict";hl.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Ys=v((E_,ml)=>{"use strict";var Sh=zs(),_h=Vs();function gl(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var wt=ml.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Sh.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:gl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:gl(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};wt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};wt.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};wt.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};wt.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>s?e[o-r]:0,c=Math.floor((u+l)/2);e[o]=a+c}};wt.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>s?e[o-r]:0,c=o>s&&i?i[o-r]:0,d=_h(u,l,c);e[o]=a+d}};wt.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Sl=v((P_,vl)=>{"use strict";var bh=require("util"),yl=js(),wh=Ys(),Ih=vl.exports=function(t){yl.call(this);let e=[],n=this;this._filter=new wh(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};bh.inherits(Ih,yl)});var It=v((M_,_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 Xs=v((L_,bl)=>{"use strict";var Js=[];(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;Js[t]=e}})();var Ks=bl.exports=function(){this._crc=-1};Ks.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Js[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ks.prototype.crc32=function(){return this._crc^-1};Ks.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Js[(e^t[n])&255]^e>>>8;return e^-1}});var Qs=v((N_,wl)=>{"use strict";var F=It(),Ah=Xs(),q=wl.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[F.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[F.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[F.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[F.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[F.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[F.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(){}};q.prototype.start=function(){this.read(F.PNG_SIGNATURE.length,this._parseSignature.bind(this))};q.prototype._parseSignature=function(t){let e=F.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))};q.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==F.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Ah,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};q.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))};q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};q.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in F.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=F.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&F.COLORTYPE_PALETTE),color:!!(s&F.COLORTYPE_COLOR),alpha:!!(s&F.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};q.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()};q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===F.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===F.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===F.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/F.GAMMA_DIVISION),this._handleChunkEnd()};q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===F.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()};q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Zs=v(Al=>{"use strict";var Il=zs(),xh=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Ch=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Th(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,u,c,d,f,g;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,g=i>>4,n.push(g,f);break;case 2:c=i&3,d=i>>2&3,f=i>>4&3,g=i>>6&3,n.push(g,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,g=i>>7&1,n.push(g,f,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function kh(t,e,n,r,s,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);xh[r](e,s,d,i),i+=r}return i}function Rh(t,e,n,r,s,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=s.get(r),f=n(c,u,l);Ch[r](e,d,f,i)}s.resetAfterLine()}}Al.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Th(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let u=Math.pow(2,s)-1,c=0,d,f;if(o)d=Il.getImagePasses(n,r),f=Il.getInterlaceIterator(n,r);else{let g=0;f=function(){let h=g;return g+=4,h},d=[{width:n,height:r}]}for(let g=0;g<d.length;g++)s===8?c=kh(d[g],l,f,i,t,c):Rh(d[g],l,f,i,a,u);if(s===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var ei=v((B_,xl)=>{"use strict";function Eh(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function Ph(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function Mh(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let 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}}xl.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Eh(t,l,r,s,a):(o&&Ph(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Mh(t,l,r,s,n))),l}});var kl=v((D_,Tl)=>{"use strict";var Lh=require("util"),ti=require("zlib"),Cl=js(),Nh=Sl(),Oh=Qs(),Bh=Zs(),Dh=ei(),ge=Tl.exports=function(t){Cl.call(this),this._parser=new Oh(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()};Lh.inherits(ge,Cl);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=ti.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,ti.Z_MIN_CHUNK);this._inflate=ti.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Nh(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=Bh.dataToBitMap(t,this._bitmapInfo);e=Dh(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var El=v((F_,Rl)=>{"use strict";var re=It();Rl.exports=function(t,e,n,r){let s=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&h)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=re.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=re.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function g(){let h,p,m,y=o;switch(r.inputColorType){case re.COLORTYPE_COLOR_ALPHA:y=i[c+3],h=i[c],p=i[c+1],m=i[c+2];break;case re.COLORTYPE_COLOR:h=i[c],p=i[c+1],m=i[c+2];break;case re.COLORTYPE_ALPHA:y=i[c+1],h=i[c],p=h,m=h;break;case re.COLORTYPE_GRAYSCALE:h=i[c],p=h,m=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(y/=o,h=Math.min(Math.max(Math.round((1-y)*f.red+y*h),0),o),p=Math.min(Math.max(Math.round((1-y)*f.green+y*p),0),o),m=Math.min(Math.max(Math.round((1-y)*f.blue+y*m),0),o))),{red:h,green:p,blue:m,alpha:y}}for(let h=0;h<n;h++)for(let p=0;p<e;p++){let m=g(i,c);switch(r.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:r.bitDepth===8?(u[d]=m.red,u[d+1]=m.green,u[d+2]=m.blue,s&&(u[d+3]=m.alpha)):(u.writeUInt16BE(m.red,d),u.writeUInt16BE(m.green,d+2),u.writeUInt16BE(m.blue,d+4),s&&u.writeUInt16BE(m.alpha,d+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let y=(m.red+m.green+m.blue)/3;r.bitDepth===8?(u[d]=y,s&&(u[d+1]=m.alpha)):(u.writeUInt16BE(y,d),s&&u.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}c+=a,d+=l}return u}});var Ll=v((H_,Ml)=>{"use strict";var Pl=Vs();function Fh(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Hh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Uh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function qh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function Wh(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function Gh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function jh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=t[e+o]-(a+l>>1);r[s+o]=u}}function $h(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function zh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-Pl(a,l,u);r[s+o]=c}}function Vh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-Pl(o,a,l);s+=Math.abs(u)}return s}var Yh={0:Fh,1:Uh,2:Wh,3:jh,4:zh},Jh={0:Hh,1:qh,2:Gh,3:$h,4:Vh};Ml.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,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 g=0;g<i.length;g++){let h=Jh[i[g]](t,l,o,s);h<f&&(c=i[g],f=h)}}u[a]=c,a++,Yh[c](t,l,o,u,a,s),a+=o,l+=o}return u}});var ni=v((U_,Nl)=>{"use strict";var j=It(),Kh=Xs(),Xh=El(),Qh=Ll(),Zh=require("zlib"),Le=Nl.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||Zh.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:j.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:j.COLORTYPE_COLOR_ALPHA,[j.COLORTYPE_GRAYSCALE,j.COLORTYPE_COLOR,j.COLORTYPE_COLOR_ALPHA,j.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([j.COLORTYPE_GRAYSCALE,j.COLORTYPE_COLOR,j.COLORTYPE_COLOR_ALPHA,j.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")};Le.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Le.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Le.prototype.filterData=function(t,e,n){let r=Xh(t,e,n,this._options),s=j.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Qh(r,e,n,this._options,s)};Le.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(Kh.crc32(r.slice(4,r.length-4)),r.length-4),r};Le.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*j.GAMMA_DIVISION),0),this._packChunk(j.TYPE_gAMA,e)};Le.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(j.TYPE_IHDR,n)};Le.prototype.packIDAT=function(t){return this._packChunk(j.TYPE_IDAT,t)};Le.prototype.packIEND=function(){return this._packChunk(j.TYPE_IEND,null)}});var Fl=v((q_,Dl)=>{"use strict";var eg=require("util"),Ol=require("stream"),tg=It(),ng=ni(),Bl=Dl.exports=function(t){Ol.call(this);let e=t||{};this._packer=new ng(e),this._deflate=this._packer.createDeflate(),this.readable=!0};eg.inherits(Bl,Ol);Bl.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(tg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var jl=v((on,Gl)=>{"use strict";var Hl=require("assert").ok,At=require("zlib"),rg=require("util"),Ul=require("buffer").kMaxLength;function Ve(t){if(!(this instanceof Ve))return new Ve(t);t&&t.chunkSize<At.Z_MIN_CHUNK&&(t.chunkSize=At.Z_MIN_CHUNK),At.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 sg(t){return new Ve(t)}function ql(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ve.prototype._processChunk=function(t,e,n){if(typeof n=="function")return At.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(h){c=h});function d(h,p){if(r._hadError)return;let m=i-p;if(Hl(m>=0,"have should not go down"),m>0){let y=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=s-h,s=h,!0):!1}Hl(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw c;if(u>=Ul)throw ql(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ul.toString(16)+" bytes");let g=Buffer.concat(l,u);return ql(this),g};rg.inherits(Ve,At.Inflate);function ig(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=At.Z_FINISH),t._processChunk(e,n)}function Wl(t,e){return ig(new Ve(e),t)}Gl.exports=on=Wl;on.Inflate=Ve;on.createInflate=sg;on.inflateSync=Wl});var ri=v((W_,zl)=>{"use strict";var $l=zl.exports=function(t){this._buffer=t,this._reads=[]};$l.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};$l.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Yl=v(Vl=>{"use strict";var og=ri(),ag=Ys();Vl.process=function(t,e){let n=[],r=new og(t);return new ag(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Ql=v((j_,Xl)=>{"use strict";var Jl=!0,Kl=require("zlib"),lg=jl();Kl.deflateSync||(Jl=!1);var cg=ri(),ug=Yl(),dg=Qs(),fg=Zs(),pg=ei();Xl.exports=function(t,e){if(!Jl)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(x){n=x}let s;function i(x){s=x}function o(x){s.transColor=x}function a(x){s.palette=x}function l(){s.alpha=!0}let u;function c(x){u=x}let d=[];function f(x){d.push(x)}let g=new cg(t);if(new dg(e,{read:g.read.bind(g),error:r,metadata:i,gamma:c,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),g.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Kl.inflateSync(p);else{let T=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=lg(p,{chunkSize:T,maxLength:T})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let y=ug.process(m,s);p=null;let w=fg.dataToBitMap(y,s);y=null;let A=pg(w,s);return s.data=A,s.gamma=u||0,s}});var nc=v(($_,tc)=>{"use strict";var Zl=!0,ec=require("zlib");ec.deflateSync||(Zl=!1);var hg=It(),gg=ni();tc.exports=function(t,e){if(!Zl)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new gg(n),s=[];s.push(Buffer.from(hg.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=ec.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var rc=v(si=>{"use strict";var mg=Ql(),yg=nc();si.read=function(t,e){return mg(t,e||{})};si.write=function(t,e){return yg(t,e)}});var oc=v(ic=>{"use strict";var vg=require("util"),sc=require("stream"),Sg=kl(),_g=Fl(),bg=rc(),V=ic.PNG=function(t){sc.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 Sg(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 _g(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"))};vg.inherits(V,sc);V.sync=bg;V.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)};V.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};V.prototype.bitblt=function(t,e,n,r,s,i,o){return V.bitblt(this,t,e,n,r,s,i,o),this};V.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var an=v(Ye=>{function ac(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Ye.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:ac(e.color.dark||"#000000ff"),light:ac(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ye.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ye.getImageWidth=function(e,n){let r=Ye.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Ye.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=Ye.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,u=[r.color.light,r.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let f=(c*a+d)*4,g=r.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let h=Math.floor((c-l)/o),p=Math.floor((d-l)/o);g=u[i[h*s+p]?1:0]}e[f++]=g.r,e[f++]=g.g,e[f++]=g.b,e[f]=g.a}}});var lc=v(me=>{var wg=require("fs"),Ig=oc().PNG,ii=an();me.render=function(e,n){let r=ii.getOptions(n),s=r.rendererOpts,i=ii.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Ig(s);return ii.qrToImageData(o.data,e,r),o};me.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),me.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};me.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=me.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};me.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=wg.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,r)};me.renderToFileStream=function(e,n,r){me.render(n,r).pack().pipe(e)}});var cc=v(ir=>{var Ag=an(),xg={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Cg={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Tg(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}ir.render=function(t,e,n){let r=Ag.getOptions(e),s=xg;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Cg);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
- `);let u=Array(r.margin+1).join(s.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],g=o[(c+1)*i+d];a+=Tg(f,g,s)}a+=u+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};ir.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=ir.render(n,r);i.writeFile(e,o,s)}});var dc=v(uc=>{uc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),u=Array(2).join(o);a+=l+`
13
+ `);let o=vh(e,n,s),a=ir.getSymbolSize(e),l=new ah(a);return ph(l,e),hh(l),gh(l,e),Gs(l,n,0),e>=7&&mh(l,e),yh(l,o),isNaN(r)&&(r=js.getBestMask(l,Gs.bind(null,l,n))),js.applyMask(r,l),Gs(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}pl.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Ws.M,s,i;return typeof n<"u"&&(r=Ws.from(n.errorCorrectionLevel,Ws.M),s=sr.from(n.version),i=js.from(n.maskPattern),n.toSJISFunc&&ir.setToSJISFunction(n.toSJISFunc)),_h(e,s,r,i)}});var Vs=v((D_,gl)=>{"use strict";var bh=require("util"),hl=require("stream"),le=gl.exports=function(){hl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};bh.inherits(le,hl);le.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))};le.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};le.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()))};le.prototype.destroySoon=le.prototype.end;le.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};le.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};le.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))};le.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};le.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 Js=v(Ys=>{"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]}];Ys.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<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]<r;d++)u++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)c++;u>0&&c>0&&n.push({width:u,height:c,index:a})}return n};Ys.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Le[r].x.length,i=(e-s)/Le[r].x.length*8+Le[r].x[s],o=n%Le[r].y.length,a=(n-o)/Le[r].y.length*8+Le[r].y[o];return i*4+a*t*4}}});var Ks=v((H_,ml)=>{"use strict";ml.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Xs=v((U_,vl)=>{"use strict";var wh=Js(),Ih=Ks();function yl(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var wt=vl.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=wh.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:yl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:yl(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};wt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};wt.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};wt.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};wt.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>s?e[o-r]:0,c=Math.floor((u+l)/2);e[o]=a+c}};wt.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,u=o>s?e[o-r]:0,c=o>s&&i?i[o-r]:0,d=Ih(u,l,c);e[o]=a+d}};wt.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var bl=v((W_,_l)=>{"use strict";var Ah=require("util"),Sl=Vs(),Th=Xs(),xh=_l.exports=function(t){Sl.call(this);let e=[],n=this;this._filter=new Th(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Ah.inherits(xh,Sl)});var It=v((q_,wl)=>{"use strict";wl.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 ei=v((G_,Il)=>{"use strict";var Qs=[];(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;Qs[t]=e}})();var Zs=Il.exports=function(){this._crc=-1};Zs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Qs[(this._crc^t[e])&255]^this._crc>>>8;return!0};Zs.prototype.crc32=function(){return this._crc^-1};Zs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Qs[(e^t[n])&255]^e>>>8;return e^-1}});var ti=v((j_,Al)=>{"use strict";var H=It(),Ch=ei(),q=Al.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[H.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[H.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[H.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[H.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[H.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[H.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(){}};q.prototype.start=function(){this.read(H.PNG_SIGNATURE.length,this._parseSignature.bind(this))};q.prototype._parseSignature=function(t){let e=H.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))};q.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==H.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Ch,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};q.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))};q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};q.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in H.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=H.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&H.COLORTYPE_PALETTE),color:!!(s&H.COLORTYPE_COLOR),alpha:!!(s&H.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};q.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()};q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===H.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===H.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===H.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/H.GAMMA_DIVISION),this._handleChunkEnd()};q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===H.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()};q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ni=v(xl=>{"use strict";var Tl=Js(),kh=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Rh=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Eh(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,u,c,d,p,h;switch(e){default:throw new Error("unrecognised depth");case 16:p=t[r],r++,n.push((i<<8)+p);break;case 4:p=i&15,h=i>>4,n.push(h,p);break;case 2:c=i&3,d=i>>2&3,p=i>>4&3,h=i>>6&3,n.push(h,p,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,p=i>>6&1,h=i>>7&1,n.push(h,p,d,c,u,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function Ph(t,e,n,r,s,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);kh[r](e,s,d,i),i+=r}return i}function Mh(t,e,n,r,s,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=s.get(r),p=n(c,u,l);Rh[r](e,d,p,i)}s.resetAfterLine()}}xl.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Eh(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let u=Math.pow(2,s)-1,c=0,d,p;if(o)d=Tl.getImagePasses(n,r),p=Tl.getInterlaceIterator(n,r);else{let h=0;p=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)s===8?c=Ph(d[h],l,p,i,t,c):Mh(d[h],l,p,i,a,u);if(s===8){if(c!==t.length)throw new Error("extra data found")}else a.end();return l}});var ri=v((z_,Cl)=>{"use strict";function Lh(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let u=0;u<4;u++)e[i+u]=l[u];i+=4}}function Nh(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let u=0;u<4;u++)e[i+u]=0;i+=4}}function Oh(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let 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}}Cl.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Lh(t,l,r,s,a):(o&&Nh(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Oh(t,l,r,s,n))),l}});var El=v((V_,Rl)=>{"use strict";var Bh=require("util"),si=require("zlib"),kl=Vs(),Dh=bl(),Fh=ti(),Hh=ni(),Uh=ri(),ge=Rl.exports=function(t){kl.call(this),this._parser=new Fh(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()};Bh.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=si.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,si.Z_MIN_CHUNK);this._inflate=si.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ge.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Dh(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=Hh.dataToBitMap(t,this._bitmapInfo);e=Uh(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ml=v((Y_,Pl)=>{"use strict";var re=It();Pl.exports=function(t,e,n,r){let s=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let f=new ArrayBuffer(2);return new DataView(f).setInt16(0,256,!0),new Int16Array(f)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=re.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=re.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let u=Buffer.alloc(e*n*l),c=0,d=0,p=r.bgColor||{};p.red===void 0&&(p.red=o),p.green===void 0&&(p.green=o),p.blue===void 0&&(p.blue=o);function h(){let g,f,m,y=o;switch(r.inputColorType){case re.COLORTYPE_COLOR_ALPHA:y=i[c+3],g=i[c],f=i[c+1],m=i[c+2];break;case re.COLORTYPE_COLOR:g=i[c],f=i[c+1],m=i[c+2];break;case re.COLORTYPE_ALPHA:y=i[c+1],g=i[c],f=g,m=g;break;case re.COLORTYPE_GRAYSCALE:g=i[c],f=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(y/=o,g=Math.min(Math.max(Math.round((1-y)*p.red+y*g),0),o),f=Math.min(Math.max(Math.round((1-y)*p.green+y*f),0),o),m=Math.min(Math.max(Math.round((1-y)*p.blue+y*m),0),o))),{red:g,green:f,blue:m,alpha:y}}for(let g=0;g<n;g++)for(let f=0;f<e;f++){let m=h(i,c);switch(r.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:r.bitDepth===8?(u[d]=m.red,u[d+1]=m.green,u[d+2]=m.blue,s&&(u[d+3]=m.alpha)):(u.writeUInt16BE(m.red,d),u.writeUInt16BE(m.green,d+2),u.writeUInt16BE(m.blue,d+4),s&&u.writeUInt16BE(m.alpha,d+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let y=(m.red+m.green+m.blue)/3;r.bitDepth===8?(u[d]=y,s&&(u[d+1]=m.alpha)):(u.writeUInt16BE(y,d),s&&u.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}c+=a,d+=l}return u}});var Ol=v((J_,Nl)=>{"use strict";var Ll=Ks();function Wh(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function qh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Gh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function jh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function $h(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function zh(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function Vh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=t[e+o]-(a+l>>1);r[s+o]=u}}function Yh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Jh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,u=e>0&&o>=i?t[e+o-(n+i)]:0,c=t[e+o]-Ll(a,l,u);r[s+o]=c}}function Kh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,u=t[e+i]-Ll(o,a,l);s+=Math.abs(u)}return s}var Xh={0:Wh,1:Gh,2:$h,3:Vh,4:Jh},Qh={0:qh,1:jh,2:zh,3:Yh,4:Kh};Nl.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,u=Buffer.alloc((o+1)*n),c=i[0];for(let d=0;d<n;d++){if(i.length>1){let p=1/0;for(let h=0;h<i.length;h++){let g=Qh[i[h]](t,l,o,s);g<p&&(c=i[h],p=g)}}u[a]=c,a++,Xh[c](t,l,o,u,a,s),a+=o,l+=o}return u}});var ii=v((K_,Bl)=>{"use strict";var $=It(),Zh=ei(),eg=Ml(),tg=Ol(),ng=require("zlib"),Ne=Bl.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||ng.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:$.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:$.COLORTYPE_COLOR_ALPHA,[$.COLORTYPE_GRAYSCALE,$.COLORTYPE_COLOR,$.COLORTYPE_COLOR_ALPHA,$.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([$.COLORTYPE_GRAYSCALE,$.COLORTYPE_COLOR,$.COLORTYPE_COLOR_ALPHA,$.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 r=eg(t,e,n,this._options),s=$.COLORTYPE_TO_BPP_MAP[this._options.colorType];return tg(r,e,n,this._options,s)};Ne.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(Zh.crc32(r.slice(4,r.length-4)),r.length-4),r};Ne.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*$.GAMMA_DIVISION),0),this._packChunk($.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($.TYPE_IHDR,n)};Ne.prototype.packIDAT=function(t){return this._packChunk($.TYPE_IDAT,t)};Ne.prototype.packIEND=function(){return this._packChunk($.TYPE_IEND,null)}});var Ul=v((X_,Hl)=>{"use strict";var rg=require("util"),Dl=require("stream"),sg=It(),ig=ii(),Fl=Hl.exports=function(t){Dl.call(this);let e=t||{};this._packer=new ig(e),this._deflate=this._packer.createDeflate(),this.readable=!0};rg.inherits(Fl,Dl);Fl.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(sg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var zl=v((an,$l)=>{"use strict";var Wl=require("assert").ok,At=require("zlib"),og=require("util"),ql=require("buffer").kMaxLength;function Ye(t){if(!(this instanceof Ye))return new Ye(t);t&&t.chunkSize<At.Z_MIN_CHUNK&&(t.chunkSize=At.Z_MIN_CHUNK),At.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 ag(t){return new Ye(t)}function Gl(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ye.prototype._processChunk=function(t,e,n){if(typeof n=="function")return At.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],u=0,c;this.on("error",function(g){c=g});function d(g,f){if(r._hadError)return;let m=i-f;if(Wl(m>=0,"have should not go down"),m>0){let y=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,y.length>o&&(y=y.slice(0,o)),l.push(y),u+=y.length,o-=y.length,o===0)return!1}return(f===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),f===0?(a+=s-g,s=g,!0):!1}Wl(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),p=p||this._writeState;while(!this._hadError&&d(p[0],p[1]));if(this._hadError)throw c;if(u>=ql)throw Gl(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+ql.toString(16)+" bytes");let h=Buffer.concat(l,u);return Gl(this),h};og.inherits(Ye,At.Inflate);function lg(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=At.Z_FINISH),t._processChunk(e,n)}function jl(t,e){return lg(new Ye(e),t)}$l.exports=an=jl;an.Inflate=Ye;an.createInflate=ag;an.inflateSync=jl});var oi=v((Q_,Yl)=>{"use strict";var Vl=Yl.exports=function(t){this._buffer=t,this._reads=[]};Vl.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Vl.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 Kl=v(Jl=>{"use strict";var cg=oi(),ug=Xs();Jl.process=function(t,e){let n=[],r=new cg(t);return new ug(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var ec=v((e0,Zl)=>{"use strict";var Xl=!0,Ql=require("zlib"),dg=zl();Ql.deflateSync||(Xl=!1);var fg=oi(),pg=Kl(),hg=ti(),gg=ni(),mg=ri();Zl.exports=function(t,e){if(!Xl)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(w){n=w}let s;function i(w){s=w}function o(w){s.transColor=w}function a(w){s.palette=w}function l(){s.alpha=!0}let u;function c(w){u=w}let d=[];function p(w){d.push(w)}let h=new fg(t);if(new hg(e,{read:h.read.bind(h),error:r,metadata:i,gamma:c,palette:a,transColor:o,inflateData:p,simpleTransparency:l}).start(),h.process(),n)throw n;let f=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Ql.inflateSync(f);else{let C=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=dg(f,{chunkSize:C,maxLength:C})}if(f=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let y=pg.process(m,s);f=null;let A=gg.dataToBitMap(y,s);y=null;let T=mg(A,s);return s.data=T,s.gamma=u||0,s}});var sc=v((t0,rc)=>{"use strict";var tc=!0,nc=require("zlib");nc.deflateSync||(tc=!1);var yg=It(),vg=ii();rc.exports=function(t,e){if(!tc)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new vg(n),s=[];s.push(Buffer.from(yg.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=nc.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var ic=v(ai=>{"use strict";var Sg=ec(),_g=sc();ai.read=function(t,e){return Sg(t,e||{})};ai.write=function(t,e){return _g(t,e)}});var lc=v(ac=>{"use strict";var bg=require("util"),oc=require("stream"),wg=El(),Ig=Ul(),Ag=ic(),V=ac.PNG=function(t){oc.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 wg(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 Ig(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"))};bg.inherits(V,oc);V.sync=Ag;V.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)};V.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};V.prototype.bitblt=function(t,e,n,r,s,i,o){return V.bitblt(this,t,e,n,r,s,i,o),this};V.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var ln=v(Je=>{function cc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Je.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:cc(e.color.dark||"#000000ff"),light:cc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Je.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Je.getImageWidth=function(e,n){let r=Je.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Je.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=Je.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,u=[r.color.light,r.color.dark];for(let c=0;c<a;c++)for(let d=0;d<a;d++){let p=(c*a+d)*4,h=r.color.light;if(c>=l&&d>=l&&c<a-l&&d<a-l){let g=Math.floor((c-l)/o),f=Math.floor((d-l)/o);h=u[i[g*s+f]?1:0]}e[p++]=h.r,e[p++]=h.g,e[p++]=h.b,e[p]=h.a}}});var uc=v(me=>{var Tg=require("fs"),xg=lc().PNG,li=ln();me.render=function(e,n){let r=li.getOptions(n),s=r.rendererOpts,i=li.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new xg(s);return li.qrToImageData(o.data,e,r),o};me.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),me.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};me.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=me.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};me.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Tg.createWriteStream(e);a.on("error",o),a.on("close",o),me.renderToFileStream(a,n,r)};me.renderToFileStream=function(e,n,r){me.render(n,r).pack().pipe(e)}});var dc=v(or=>{var Cg=ln(),kg={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Rg={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Eg(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}or.render=function(t,e,n){let r=Cg.getOptions(e),s=kg;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Rg);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
+ `);let u=Array(r.margin+1).join(s.WW);a+=l;for(let c=0;c<i;c+=2){a+=u;for(let d=0;d<i;d++){let p=o[c*i+d],h=o[(c+1)*i+d];a+=Eg(p,h,s)}a+=u+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};or.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=or.render(n,r);i.writeFile(e,o,s)}});var pc=v(fc=>{fc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),u=Array(2).join(o);a+=l+`
16
16
  `;for(let c=0;c<r;++c){a+=o;for(let d=0;d<r;d++)a+=s[c*r+d]?i:o;a+=u+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var gc=v(hc=>{var kg="\x1B[47m",Rg="\x1B[40m",oi="\x1B[37m",ai="\x1B[30m",Je="\x1B[0m",Eg=kg+ai,Pg=Rg+oi,Mg=function(t,e,n){return{"00":Je+" "+t,"01":Je+e+"\u2584"+t,"02":Je+n+"\u2584"+t,10:Je+e+"\u2580"+t,11:" ",12:"\u2584",20:Je+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},fc=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},pc=function(t,e,n,r){return fc(t,e,n,r)+fc(t,e,n,r+1)};hc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Pg:Eg,u=Mg(o,i?ai:oi,i?oi:ai),c=Je+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let g=-1;g<r;g++)d+=u[pc(s,r,g,f)];d+=u[pc(s,r,r,f)]+c}return d+=Je,typeof n=="function"&&n(null,d),d}});var yc=v(mc=>{var Lg=dc(),Ng=gc();mc.render=function(t,e,n){return e&&e.small?Ng.render(t,e,n):Lg.render(t,e,n)}});var ci=v(Sc=>{var Og=an();function vc(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function li(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Bg(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?li("M",l+n,.5+u+n):li("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=li("h",o),o=0)):s++}return r}Sc.render=function(e,n,r){let s=Og.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+vc(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+vc(s.color.dark,"stroke")+' d="'+Bg(o,i,s.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
- `;return typeof r=="function"&&r(null,f),f}});var _c=v(or=>{var Dg=ci();or.render=Dg.render;or.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+or.render(n,r);i.writeFile(e,a,s)}});var bc=v(ar=>{var ui=an();function Fg(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 Hg(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}ar.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Hg()),s=ui.getOptions(s);let o=ui.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ui.qrToImageData(l.data,e,s),Fg(a,i,o),a.putImageData(l,0,0),i};ar.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=ar.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Ic=v(ln=>{var Ug=As(),di=Gs(),wc=bc(),qg=ci();function fi(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Ug())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,u){try{let c=di.create(n,r);l(t(c,e,r))}catch(c){u(c)}})}try{let l=di.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}ln.create=di.create;ln.toCanvas=fi.bind(null,wc.render);ln.toDataURL=fi.bind(null,wc.renderToDataURL);ln.toString=fi.bind(null,function(t,e,n){return qg.render(t,n)})});var Tc=v(Ne=>{var Ac=As(),pi=Gs(),Wg=lc(),xc=cc(),Gg=yc(),Cc=_c();function cn(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(Ac())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function jg(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function lr(t){switch(t){case"svg":return Cc;case"txt":case"utf8":return xc;case"png":case"image/png":default:return Wg}}function $g(t){switch(t){case"svg":return Cc;case"terminal":return Gg;case"utf8":default:return xc}}function un(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=pi.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=pi.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Ne.create=pi.create;Ne.toCanvas=Ic().toCanvas;Ne.toString=function(e,n,r){let s=cn(e,n,r),i=s.opts?s.opts.type:void 0,o=$g(i);return un(o.render,e,s)};Ne.toDataURL=function(e,n,r){let s=cn(e,n,r),i=lr(s.opts.type);return un(i.renderToDataURL,e,s)};Ne.toBuffer=function(e,n,r){let s=cn(e,n,r),i=lr(s.opts.type);return un(i.renderToBuffer,e,s)};Ne.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Ac())throw new Error("Too few arguments provided");let i=cn(n,r,s),o=i.opts.type||jg(e),l=lr(o).renderToFile.bind(null,e);return un(l,n,i)};Ne.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=cn(n,r,e.emit.bind(e,"error")),o=lr("png").renderToFileStream.bind(null,e);un(o,n,s)}});var Rc=v((i0,kc)=>{kc.exports=Tc()});var Yd=require("http");var Tp=ct(da(),1),kp=ct(fs(),1),Rp=ct(gs(),1),Ep=ct(Vn(),1),Is=ct(_a(),1);var oe=require("fs/promises"),Jd=require("crypto"),Gt=require("path"),Kd=require("os"),go=ct(Rc(),1);var Ke=require("child_process"),Tt=require("fs"),R=require("path"),pn=require("os");var mr=require("fs");var Ec=require("os"),$=require("path"),we=(0,$.join)((0,Ec.homedir)(),".vibelet"),cr=(0,$.join)(we,"logs"),ur=(0,$.join)(we,"data"),zg=(0,$.join)(we,"runtime"),o0=(0,$.join)(zg,"current"),Pc=(0,$.join)(we,"identity.json"),Mc=(0,$.join)(we,"pairings.json"),Lc=(0,$.join)(ur,"push-subscriptions.json"),dr=(0,$.join)(ur,"sessions.json"),xt=(0,$.join)(ur,"audit.jsonl"),hi=(0,$.join)(ur,"uploads"),fr=(0,$.join)(cr,"daemon.stdout.log"),pr=(0,$.join)(cr,"daemon.stderr.log"),Nc=(0,$.join)(we,"update-check.json"),gi=(0,$.join)(we,"pairing-qr.png");var hr={stdout:!1,stderr:!1};function Oc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Vg(t){return!t.destroyed&&t.writable!==!1}function Bc(t,e){if(hr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Vg(n))return hr[t]=!0,!1;try{return n.write(e,r=>{Oc(r)&&(hr[t]=!0)}),!0}catch(r){return Oc(r)&&(hr[t]=!0),!1}}function Ct(t){return Bc("stdout",t)}function gr(t){return Bc("stderr",t)}var Dc={debug:10,info:20,warn:30,error:40},Yg=process.env.VIBE_LOG_LEVEL||"info";function Jg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Kg(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Hc=!Jg()&&!Kg();if(Hc)try{(0,mr.mkdirSync)(cr,{recursive:!0})}catch{}function Fc(t,e,n){if(Dc[t]<Dc[Yg])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?gr(s+`
21
- `):Ct(s+`
22
- `),Hc){let i=t==="error"||t==="warn"?pr:fr;try{(0,mr.appendFileSync)(i,s+`
23
- `)}catch{}}}function Uc(t={}){function e(n,r,s){typeof r=="string"?Fc(n,t,r):Fc(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Uc({...t,...n})}}var L=Uc({module:"daemon"});var Xg=["fnm_multishells"],Qg=6e4,Oe=process.platform==="win32",Zg=L.child({module:"config"});function se(t){return Xg.some(e=>t.includes(e))}function em(t){if(!t||!se(t))return t;try{let e=(0,R.join)((0,Tt.realpathSync)((0,R.dirname)(t)),(0,R.basename)(t));if((0,Tt.existsSync)(e)&&!se(e))return e}catch{}return t}function tm(t){if(!t||!se(t))return t;try{let e=(0,Tt.realpathSync)(t);if(e&&!se(e))return e}catch{}return t}function vi(){return Oe?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var dn=null;function Wc(){if(dn&&dn.PATH&&!se(dn.PATH))return dn;for(let t of vi())try{let e=(0,Ke.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
- `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return n.PATH&&!se(n.PATH)&&(dn=n),n}catch{}return{}}function nm(t=Wc()){let e=(0,pn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Oe?(0,R.join)(e,"pnpm"):(0,R.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Oe?[(0,R.join)(e,".npm-global","bin"),(0,R.join)(e,".local","bin"),(0,R.join)(e,".claude","bin"),n,(0,R.join)(e,"AppData","Roaming","npm"),(0,R.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,R.join)(e,".npm-global","bin"),(0,R.join)(e,".local","bin"),(0,R.join)(e,".claude","bin"),n],i=r.split(R.delimiter).filter(Boolean).map(tm),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(R.delimiter)}function mi(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function yi(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Xe(){let t=Wc(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=nm(t),e.HOME||(e.HOME=(0,pn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Si(t){if(Oe)try{let n=(0,Ke.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function fn(t,e=3e3){try{return(0,Ke.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Xe(),...Oe?{shell:!0}:{}}).trim()||null}catch{return null}}function rm(t){for(let e of vi())try{let n=(0,Ke.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function sm(){let t=(0,pn.homedir)();return[(0,R.join)(t,".local","bin","claude"),(0,R.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,R.join)(t,".npm-global","bin","claude")]}function im(){if(Oe){let t=Si("claude");return t&&fn(t)?t:void 0}for(let t of sm())if(fn(t))return t;try{let t=(0,Ke.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Xe()}).trim();if(t&&!t.includes("cmux")&&fn(t))return t}catch{}}function om(){let t=(0,pn.homedir)(),e=[process.env.PNPM_HOME,(0,R.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,R.join)(t,".npm-global","bin","codex"),(0,R.join)(t,".local","bin","codex"),...e.map(n=>(0,R.join)(n,"codex"))]}function am(){if(Oe){let s=Si("codex");return s&&fn(s)?s:void 0}let t=s=>{let i=em(s);return fn(i)?i:void 0},e;for(let s of om()){let i=t(s);if(i){if(!se(i))return i;e=i}}try{let s=(0,Ke.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Xe()}).trim(),i=s?t(s):void 0;if(i){if(!se(i))return i;e=e??i}}catch{}let n=rm("codex"),r=n?t(n):void 0;if(r){if(!se(r))return r;e=e??r}return e}function Gc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>Qg||!(0,Tt.existsSync)(n)||se(n)){let o=t();n=o??e,r=i,Zg.info({name:e,path:n,transient:se(n),isBare:o==null},"binary resolved")}return n}}var lm=Gc(im,"claude"),cm=Gc(am,"codex");function um(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var qc=um();function dm(t,e){if(Oe)return{command:Si(t)??t,args:e};let n=vi()[0]??"/bin/zsh",r=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",r,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:qc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:qc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:yi("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:yi("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:mi("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:mi("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:mi("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:yi("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return lm()},get codexPath(){return cm()},isTransientPath:se,execViaLoginShell:dm,buildSanitizedEnv:Xe};var ro=require("crypto"),Cd=require("fs/promises");var su=require("child_process"),br=require("fs");var yr=require("fs"),zc=require("path");var J=require("fs");function fm(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function hn(t,e){if(!(0,J.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,J.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=fm(r,e.maxBytes,s,e.retainBytes),o=(0,J.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,J.readSync)(o,l,0,i,r-i);let u=0;if(r>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,J.ftruncateSync)(o,0),a.length>0&&(0,J.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,J.closeSync)(o)}}function jc(t){let e=[hn(t.auditPath,{maxBytes:t.auditMaxBytes}),hn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),hn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var $c=!1,pm=new Set(["ts","event","source","appEvent","level"]);function hm(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function gm(t={}){let e={};for(let[n,r]of Object.entries(t))pm.has(n)||(e[n]=r);return e}function mm(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...gm(n)}}function ym(){$c||((0,yr.mkdirSync)((0,zc.dirname)(xt),{recursive:!0}),$c=!0)}var _i=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(mm(e,n,r,s))}write(e){if(!hm()){ym();try{let n=JSON.stringify(e)+`
25
- `;hn(xt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,yr.appendFileSync)(xt,n)}catch{}}}},I=new _i;var Be=require("fs"),Vc=require("os"),gn=require("path"),Yc=require("crypto"),bi="claude-hook:",mn="x-vibelet-claude-hook-secret",yn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function vm(t,e){return`#!/usr/bin/env node
18
+ `,typeof n=="function"&&n(null,a),a}});var yc=v(mc=>{var Pg="\x1B[47m",Mg="\x1B[40m",ci="\x1B[37m",ui="\x1B[30m",Ke="\x1B[0m",Lg=Pg+ui,Ng=Mg+ci,Og=function(t,e,n){return{"00":Ke+" "+t,"01":Ke+e+"\u2584"+t,"02":Ke+n+"\u2584"+t,10:Ke+e+"\u2580"+t,11:" ",12:"\u2584",20:Ke+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},hc=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},gc=function(t,e,n,r){return hc(t,e,n,r)+hc(t,e,n,r+1)};mc.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Ng:Lg,u=Og(o,i?ui:ci,i?ci:ui),c=Ke+`
19
+ `+o,d=o;for(let p=-1;p<r+1;p+=2){for(let h=-1;h<r;h++)d+=u[gc(s,r,h,p)];d+=u[gc(s,r,r,p)]+c}return d+=Ke,typeof n=="function"&&n(null,d),d}});var Sc=v(vc=>{var Bg=pc(),Dg=yc();vc.render=function(t,e,n){return e&&e.small?Dg.render(t,e,n):Bg.render(t,e,n)}});var fi=v(bc=>{var Fg=ln();function _c(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function di(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Hg(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),u=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?di("M",l+n,.5+u+n):di("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=di("h",o),o=0)):s++}return r}bc.render=function(e,n,r){let s=Fg.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+_c(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+_c(s.color.dark,"stroke")+' d="'+Hg(o,i,s.margin)+'"/>',c='viewBox="0 0 '+a+" "+a+'"',p='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
20
+ `;return typeof r=="function"&&r(null,p),p}});var wc=v(ar=>{var Ug=fi();ar.render=Ug.render;ar.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+ar.render(n,r);i.writeFile(e,a,s)}});var Ic=v(lr=>{var pi=ln();function Wg(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 qg(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}lr.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=qg()),s=pi.getOptions(s);let o=pi.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return pi.qrToImageData(l.data,e,s),Wg(a,i,o),a.putImageData(l,0,0),i};lr.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=lr.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Tc=v(cn=>{var Gg=Cs(),hi=zs(),Ac=Ic(),jg=fi();function gi(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Gg())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,u){try{let c=hi.create(n,r);l(t(c,e,r))}catch(c){u(c)}})}try{let l=hi.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}cn.create=hi.create;cn.toCanvas=gi.bind(null,Ac.render);cn.toDataURL=gi.bind(null,Ac.renderToDataURL);cn.toString=gi.bind(null,function(t,e,n){return jg.render(t,n)})});var Rc=v(Oe=>{var xc=Cs(),mi=zs(),$g=uc(),Cc=dc(),zg=Sc(),kc=wc();function un(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(xc())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Vg(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function cr(t){switch(t){case"svg":return kc;case"txt":case"utf8":return Cc;case"png":case"image/png":default:return $g}}function Yg(t){switch(t){case"svg":return kc;case"terminal":return zg;case"utf8":default:return Cc}}function dn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=mi.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=mi.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Oe.create=mi.create;Oe.toCanvas=Tc().toCanvas;Oe.toString=function(e,n,r){let s=un(e,n,r),i=s.opts?s.opts.type:void 0,o=Yg(i);return dn(o.render,e,s)};Oe.toDataURL=function(e,n,r){let s=un(e,n,r),i=cr(s.opts.type);return dn(i.renderToDataURL,e,s)};Oe.toBuffer=function(e,n,r){let s=un(e,n,r),i=cr(s.opts.type);return dn(i.renderToBuffer,e,s)};Oe.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!xc())throw new Error("Too few arguments provided");let i=un(n,r,s),o=i.opts.type||Vg(e),l=cr(o).renderToFile.bind(null,e);return dn(l,n,i)};Oe.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=un(n,r,e.emit.bind(e,"error")),o=cr("png").renderToFileStream.bind(null,e);dn(o,n,s)}});var Pc=v((g0,Ec)=>{Ec.exports=Rc()});var Xd=require("http");var Ep=ct(pa(),1),Pp=ct(gs(),1),Mp=ct(vs(),1),Lp=ct(Yn(),1),xs=ct(wa(),1);var oe=require("fs/promises"),Qd=require("crypto"),jt=require("path"),Zd=require("os"),yo=ct(Pc(),1);var Xe=require("child_process"),Ct=require("fs"),R=require("path"),hn=require("os");var yr=require("fs");var Mc=require("os"),z=require("path"),Ie=(0,z.join)((0,Mc.homedir)(),".vibelet"),ur=(0,z.join)(Ie,"logs"),dr=(0,z.join)(Ie,"data"),Jg=(0,z.join)(Ie,"runtime"),m0=(0,z.join)(Jg,"current"),Lc=(0,z.join)(Ie,"identity.json"),Nc=(0,z.join)(Ie,"pairings.json"),Oc=(0,z.join)(dr,"push-subscriptions.json"),fr=(0,z.join)(dr,"sessions.json"),Tt=(0,z.join)(dr,"audit.jsonl"),yi=(0,z.join)(dr,"uploads"),pr=(0,z.join)(ur,"daemon.stdout.log"),hr=(0,z.join)(ur,"daemon.stderr.log"),Bc=(0,z.join)(Ie,"update-check.json"),vi=(0,z.join)(Ie,"pairing-qr.png");var gr={stdout:!1,stderr:!1};function Dc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Kg(t){return!t.destroyed&&t.writable!==!1}function Fc(t,e){if(gr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Kg(n))return gr[t]=!0,!1;try{return n.write(e,r=>{Dc(r)&&(gr[t]=!0)}),!0}catch(r){return Dc(r)&&(gr[t]=!0),!1}}function xt(t){return Fc("stdout",t)}function mr(t){return Fc("stderr",t)}var Hc={debug:10,info:20,warn:30,error:40},Xg=process.env.VIBE_LOG_LEVEL||"info";function Qg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Zg(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Wc=!Qg()&&!Zg();if(Wc)try{(0,yr.mkdirSync)(ur,{recursive:!0})}catch{}function Uc(t,e,n){if(Hc[t]<Hc[Xg])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?mr(s+`
21
+ `):xt(s+`
22
+ `),Wc){let i=t==="error"||t==="warn"?hr:pr;try{(0,yr.appendFileSync)(i,s+`
23
+ `)}catch{}}}function qc(t={}){function e(n,r,s){typeof r=="string"?Uc(n,t,r):Uc(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>qc({...t,...n})}}var N=qc({module:"daemon"});var em=["fnm_multishells"],tm=6e4,Be=process.platform==="win32",nm=300*1e3,rm=900*1e3,sm=N.child({module:"config"});function se(t){return em.some(e=>t.includes(e))}function im(t){if(!t||!se(t))return t;try{let e=(0,R.join)((0,Ct.realpathSync)((0,R.dirname)(t)),(0,R.basename)(t));if((0,Ct.existsSync)(e)&&!se(e))return e}catch{}return t}function om(t){if(!t||!se(t))return t;try{let e=(0,Ct.realpathSync)(t);if(e&&!se(e))return e}catch{}return t}function _i(){return Be?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var fn=null;function $c(){if(fn&&fn.PATH&&!se(fn.PATH))return fn;for(let t of _i())try{let e=(0,Xe.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
+ `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return n.PATH&&!se(n.PATH)&&(fn=n),n}catch{}return{}}function am(t=$c()){let e=(0,hn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Be?(0,R.join)(e,"pnpm"):(0,R.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Be?[(0,R.join)(e,".npm-global","bin"),(0,R.join)(e,".local","bin"),(0,R.join)(e,".claude","bin"),n,(0,R.join)(e,"AppData","Roaming","npm"),(0,R.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,R.join)(e,".npm-global","bin"),(0,R.join)(e,".local","bin"),(0,R.join)(e,".claude","bin"),n],i=r.split(R.delimiter).filter(Boolean).map(om),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(R.delimiter)}function Si(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function vr(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Qe(){let t=$c(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=am(t),e.HOME||(e.HOME=(0,hn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function bi(t){if(Be)try{let n=(0,Xe.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function pn(t,e=3e3){try{return(0,Xe.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Qe(),...Be?{shell:!0}:{}}).trim()||null}catch{return null}}function lm(t){for(let e of _i())try{let n=(0,Xe.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function cm(){let t=(0,hn.homedir)();return[(0,R.join)(t,".local","bin","claude"),(0,R.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,R.join)(t,".npm-global","bin","claude")]}function um(){if(Be){let t=bi("claude");return t&&pn(t)?t:void 0}for(let t of cm())if(pn(t))return t;try{let t=(0,Xe.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Qe()}).trim();if(t&&!t.includes("cmux")&&pn(t))return t}catch{}}function dm(){let t=(0,hn.homedir)(),e=[process.env.PNPM_HOME,(0,R.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,R.join)(t,".npm-global","bin","codex"),(0,R.join)(t,".local","bin","codex"),...e.map(n=>(0,R.join)(n,"codex"))]}function fm(){if(Be){let s=bi("codex");return s&&pn(s)?s:void 0}let t=s=>{let i=im(s);return pn(i)?i:void 0},e;for(let s of dm()){let i=t(s);if(i){if(!se(i))return i;e=i}}try{let s=(0,Xe.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Qe()}).trim(),i=s?t(s):void 0;if(i){if(!se(i))return i;e=e??i}}catch{}let n=lm("codex"),r=n?t(n):void 0;if(r){if(!se(r))return r;e=e??r}return e}function zc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>tm||!(0,Ct.existsSync)(n)||se(n)){let o=t();n=o??e,r=i,sm.info({name:e,path:n,transient:se(n),isBare:o==null},"binary resolved")}return n}}var pm=zc(um,"claude"),hm=zc(fm,"codex");function gm(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var Gc=gm(),Sr=vr("VIBE_TURN_STALL_TIMEOUT_MS",nm),jc=vr("VIBE_TURN_STALL_HARD_TIMEOUT_MS",Math.max(rm,Sr*3)),mm=Sr<=0||jc===0?0:Math.max(jc,Sr);function ym(t,e){if(Be)return{command:bi(t)??t,args:e};let n=_i()[0]??"/bin/zsh",r=`if ! command -v ${t} >/dev/null 2>&1; then echo "${t}: not found in login shell PATH=$PATH" >&2; exit 127; fi; exec ${t} "$@"`;return{command:n,args:["-lc",r,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:Gc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:Gc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:vr("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Sr,turnStallHardTimeoutMs:mm,auditMaxBytes:Si("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Si("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Si("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:vr("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return pm()},get codexPath(){return hm()},isTransientPath:se,execViaLoginShell:ym,buildSanitizedEnv:Qe};var io=require("crypto"),Rd=require("fs/promises");var au=require("child_process"),Ar=require("fs");var _r=require("fs"),Jc=require("path");var K=require("fs");function vm(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function gn(t,e){if(!(0,K.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,K.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=vm(r,e.maxBytes,s,e.retainBytes),o=(0,K.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,K.readSync)(o,l,0,i,r-i);let u=0;if(r>i){let c=l.indexOf(10);c>=0&&c+1<l.length&&(u=c+1)}a=l.subarray(u)}return(0,K.ftruncateSync)(o,0),a.length>0&&(0,K.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,K.closeSync)(o)}}function Vc(t){let e=[gn(t.auditPath,{maxBytes:t.auditMaxBytes}),gn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),gn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Yc=!1,Sm=new Set(["ts","event","source","appEvent","level"]);function _m(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function bm(t={}){let e={};for(let[n,r]of Object.entries(t))Sm.has(n)||(e[n]=r);return e}function wm(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...bm(n)}}function Im(){Yc||((0,_r.mkdirSync)((0,Jc.dirname)(Tt),{recursive:!0}),Yc=!0)}var wi=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(wm(e,n,r,s))}write(e){if(!_m()){Im();try{let n=JSON.stringify(e)+`
25
+ `;gn(Tt,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,_r.appendFileSync)(Tt,n)}catch{}}}},I=new wi;var De=require("fs"),Kc=require("os"),mn=require("path"),Xc=require("crypto"),Ii="claude-hook:",yn="x-vibelet-claude-hook-secret",vn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Am(t,e){return`#!/usr/bin/env node
26
26
  const http = require('http');
27
27
  const chunks = [];
28
28
  process.stdin.on('data', (chunk) => chunks.push(chunk));
@@ -36,16 +36,16 @@ process.stdin.on('end', () => {
36
36
  headers: {
37
37
  'Content-Type': 'application/json',
38
38
  'Content-Length': body.length,
39
- '${mn}': ${JSON.stringify(e)}
39
+ '${yn}': ${JSON.stringify(e)}
40
40
  }
41
41
  }, (res) => { res.resume(); });
42
42
  req.on('error', () => {});
43
43
  req.end(body);
44
44
  });
45
45
  process.stdin.resume();
46
- `}function Sm(t,e){return`#!/usr/bin/env node
46
+ `}function Tm(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
- const fallback = ${JSON.stringify(JSON.stringify(yn))};
48
+ const fallback = ${JSON.stringify(JSON.stringify(vn))};
49
49
  const chunks = [];
50
50
  process.stdin.on('data', (chunk) => chunks.push(chunk));
51
51
  process.stdin.on('end', () => {
@@ -58,7 +58,7 @@ process.stdin.on('end', () => {
58
58
  headers: {
59
59
  'Content-Type': 'application/json',
60
60
  'Content-Length': body.length,
61
- '${mn}': ${JSON.stringify(e)}
61
+ '${yn}': ${JSON.stringify(e)}
62
62
  }
63
63
  }, (res) => {
64
64
  const responseChunks = [];
@@ -79,48 +79,48 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function Jc(t,e){let n=(0,gn.join)((0,Vc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Yc.randomUUID)()}`);(0,Be.mkdirSync)(n,{recursive:!0});let r=(0,gn.join)(n,"settings.json"),s=(0,gn.join)(n,"session_hook_forwarder.cjs"),i=(0,gn.join)(n,"permission_hook_forwarder.cjs");return(0,Be.writeFileSync)(s,vm(t,e),"utf8"),(0,Be.writeFileSync)(i,Sm(t,e),"utf8"),(0,Be.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function vr(t){if(t)try{(0,Be.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Kc=require("os"),Qe=require("path"),Xc=require("fs/promises"),_m=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"]),bm=5e3,Qc="Generated file: ",Zc=`Generated files:
83
- `;function kt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function vn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function wi(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r?.[1]&&(e=r[1]),e}function Ze(t,e){let n=wi(t);return n?n.startsWith("~/")?(0,Qe.resolve)((0,Kc.homedir)(),n.slice(2)):(0,Qe.isAbsolute)(n)?n:e?(0,Qe.resolve)(e,n):n:""}function wm(t){return _m.has((0,Qe.extname)(wi(t)).toLowerCase())}function Rt(t){let e=wi(t);return e?!wm(e):!1}function Ie(t){let e=[...new Set(t.map(n=>Ze(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${Qc}${e[0]}`:`${Zc}${e.join(`
84
- `)}`}function eu(t){return typeof t!="string"?!1:t.startsWith(Qc)||t.startsWith(Zc)}function Im(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),r=new Set;for(let s of n){let i=kt(s[1]);if(!i)continue;let o=Ze(i,e);!o||!Rt(o)||r.add(o)}return[...r]}function Am(t){let e=kt(t);return e?e.toLowerCase():""}function xm(t,e){let n=kt(t?.file_path)??kt(t?.path);if(!n)return null;let r=Ze(n,e);return r&&Rt(r)?r:null}function Sr(t,e,n){return Am(t)!=="write"?null:xm(e,n)}function Cm(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 Tm(t){return/^\d+\t/m.test(t)}function _r(t,e){let n=typeof e=="string"?e.trim():"";if(n&&Cm(n))return!1;let r=vn(t);if(r?.type==="update"||r?.type==="replace"||r&&(Object.hasOwn(r,"oldString")||Object.hasOwn(r,"structuredPatch")||Object.hasOwn(r,"originalFile")||Object.hasOwn(r,"replaceAll")))return!1;if(typeof vn(r?.file)?.filePath=="string"||typeof r?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||Tm(n))return!0}return!1}function Ii(t,e){let n=vn(t);if(!n)return[];let r=new Set;if(n.type==="event_msg"){let s=vn(n.payload);if(s?.type==="image_generation_end"){let i=kt(s.saved_path);if(i){let o=Ze(i,e?.cwd);o&&Rt(o)&&r.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let s=vn(n.payload);if(s?.type==="function_call"&&s.name==="apply_patch"){let i=kt(s.arguments);if(i)for(let o of Im(i,e?.cwd))r.add(o)}}return[...r]}async function tu(t,e){let n=[...new Set(t.map(s=>Ze(s)).filter(Boolean))],r=[];for(let s of n)if(Rt(s))try{let i=await(0,Xc.stat)(s);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+bm<e)continue;r.push(s)}catch{}return r}var ie=L.child({module:"claude"}),iu="claude-permission-denial:",km=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Rm(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Ai(t){Rm()&&gr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
- `)}function Em(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
86
- `):""}function Pm(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Mm(t){if(typeof t=="string")return t;let e=Em(t);return e||(Pm(t)?"":JSON.stringify(t))}function Lm(t){return/requested permissions|haven't granted/i.test(t)}function nu(t){return t.replace(km,"").replace(/\s+/g," ").trim()}function Nm(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Om(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 Bm(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function ru(t){let e=nu(t.resultText??""),n=(t.stderrLines??[]).map(nu).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&Om(i));if(r)return Bm(r);let s=[e,...n].find(i=>!!i&&!Nm(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function wr(t){return t.startsWith(iu)}var Sn=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,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ie.info({sessionId:this.sessionId,cwd:e},"session initialized"),I.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),vr(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Jc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ie.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),Ai(`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=r;if(S.isTransientPath(i)||i==="claude"){let u=S.execViaLoginShell("claude",r);o=u.command,a=u.args}else o=i;this.proc=(0,su.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let c=u.message;u.code==="ENOENT"&&this.cwd&&!(0,br.existsSync)(this.cwd)&&(c=`Working directory does not exist: ${this.cwd}`),ie.error({sessionId:this.sessionId,error:c,cwd:this.cwd},"spawn error"),I.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:c}),this.handler?.({type:"error",sessionId:this.sessionId,message:c})}),this.buffer="",this.proc.stdout.on("data",u=>{this.buffer+=u.toString();let c=this.buffer.split(`
87
- `);this.buffer=c.pop();for(let d of c)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ie.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let c=u.toString().trim();c&&(ie.debug({sessionId:this.sessionId,stderr:c},"stderr"),this.lastStderr.push(c),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(u,c)=>{ie.info({sessionId:this.sessionId,exitCode:u,signal:c},"process exited");let d=this.interrupted;this.proc=null,vr(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):u&&u!==0&&!this.sawFinalResult&&(ie.error({sessionId:this.sessionId,exitCode:u,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:ru({stderrLines:this.lastStderr,exitCode:u})})),this.exitHandler?.(u)})}respondApproval(e,n){if(ie.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ie.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
88
- `),!0}setApprovalMode(e){this.approvalMode=e,ie.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ie.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,vr(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 r=e.session_id??"";r&&r!==this.sessionId&&(ie.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),I.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)){this.emittedToolCallIds.add(s.id);let i=s.input??{},o=Sr(s.name,i,this.cwd);this.toolCallContext.set(s.id,{toolName:s.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,br.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:i,toolCallId:s.id})}break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=typeof s.tool_use_id=="string"?s.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Mm(s.content);if(!s.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,br.existsSync)(o.generatedFilePath)){let l=Ie([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!s.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&_r(e.toolUseResult,a)){let l=Ie([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(s.is_error===!0&&i&&Lm(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 r=e.request;r?.subtype==="can_use_tool"&&(I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){Ai("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:ru({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,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}.`;I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${iu}${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}:void 0;Ai("Claude finished. Run `claude --continue` to continue on desktop."),I.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var cu=require("child_process"),uu=require("fs");var xi=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},_=new xi;var ou=require("node:fs"),Ci=require("node:path"),Dm="@vibelet/cli";function Fm(t){try{let e=JSON.parse((0,ou.readFileSync)(t,"utf8"));if(e.name===Dm&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Hm(){return"1.0.15"}var Et=Hm();var E=L.child({module:"codex"});function Um(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function qm(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 Y(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function P(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var Wm=new Set(["aborted","interrupted","cancelled","canceled"]);function Gm(t){let e=P(t);return e?e.toLowerCase():null}function jm(t){let e=P(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Ti(t){return t?P(t.itemId)??P(t.id)??P(t.callId)??P(t.call_id):null}function ki(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function du(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 $m(t){if(!Array.isArray(t))return null;for(let e of t){let n=Y(e);if(!n)continue;let r=P(n.id),s=Array.isArray(n.options)?n.options.map(l=>Y(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>P(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>du(l))??i[0],a=i.find(l=>fu(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function zm(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>Y(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>Y(o)).filter(o=>!!o).map(o=>P(o.label)).filter(o=>!!o)),n=e.some(s=>du(s)),r=e.some(s=>fu(s));return n&&r}function au(t){let e=jm(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:ki(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:ki(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=P(t.server),r=P(t.tool)??P(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:Y(t.arguments)??Y(t.input)??{}}:null}return null}function Vm(t,e){let n=P(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>Y(o)?.kind==="create"))return null;let i=Ze(n,e);return Rt(i)?i:null}function Ym(t){if(!Array.isArray(t))return"";for(let e of t){let n=Y(e);if(!n)continue;let r=P(n.question)??P(n.header);if(r)return r}return""}function lu(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 _n=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)||s==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,E.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,E.info({spawnCmd:i,args:o},"spawning");I.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,cu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,uu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),E.error({error:d,cwd:e},"spawn error"),I.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{E.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(E.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{E.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&E.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Et},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=lu(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,E.info({threadId:this.threadId},"thread resumed"),I.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??"",E.info({threadId:this.threadId},"thread created"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=lu(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,E.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{E.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,E.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return E.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
90
- `),!0}restorePendingApproval(e){let n=qm(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,E.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
82
+ `}function Qc(t,e){let n=(0,mn.join)((0,Kc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Xc.randomUUID)()}`);(0,De.mkdirSync)(n,{recursive:!0});let r=(0,mn.join)(n,"settings.json"),s=(0,mn.join)(n,"session_hook_forwarder.cjs"),i=(0,mn.join)(n,"permission_hook_forwarder.cjs");return(0,De.writeFileSync)(s,Am(t,e),"utf8"),(0,De.writeFileSync)(i,Tm(t,e),"utf8"),(0,De.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function br(t){if(t)try{(0,De.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Zc=require("os"),Ze=require("path"),eu=require("fs/promises"),xm=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"]),Cm=5e3,tu="Generated file: ",nu=`Generated files:
83
+ `;function kt(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Sn(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Ai(t){let e=t.trim().replace(/[.,!?;:,。!?;:、]+$/u,""),n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r?.[1]&&(e=r[1]),e}function et(t,e){let n=Ai(t);return n?n.startsWith("~/")?(0,Ze.resolve)((0,Zc.homedir)(),n.slice(2)):(0,Ze.isAbsolute)(n)?n:e?(0,Ze.resolve)(e,n):n:""}function km(t){return xm.has((0,Ze.extname)(Ai(t)).toLowerCase())}function Rt(t){let e=Ai(t);return e?!km(e):!1}function Ae(t){let e=[...new Set(t.map(n=>et(n)).filter(Boolean))];return e.length===0?"":e.length===1?`${tu}${e[0]}`:`${nu}${e.join(`
84
+ `)}`}function ru(t){return typeof t!="string"?!1:t.startsWith(tu)||t.startsWith(nu)}function Rm(t,e){let n=t.matchAll(/^\*\*\* Add File: (.+)$/gm),r=new Set;for(let s of n){let i=kt(s[1]);if(!i)continue;let o=et(i,e);!o||!Rt(o)||r.add(o)}return[...r]}function Em(t){let e=kt(t);return e?e.toLowerCase():""}function Pm(t,e){let n=kt(t?.file_path)??kt(t?.path);if(!n)return null;let r=et(n,e);return r&&Rt(r)?r:null}function wr(t,e,n){return Em(t)!=="write"?null:Pm(e,n)}function Mm(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 Lm(t){return/^\d+\t/m.test(t)}function Ir(t,e){let n=typeof e=="string"?e.trim():"";if(n&&Mm(n))return!1;let r=Sn(t);if(r?.type==="update"||r?.type==="replace"||r&&(Object.hasOwn(r,"oldString")||Object.hasOwn(r,"structuredPatch")||Object.hasOwn(r,"originalFile")||Object.hasOwn(r,"replaceAll")))return!1;if(typeof Sn(r?.file)?.filePath=="string"||typeof r?.filePath=="string")return!0;if(n){let i=n.toLowerCase();if(i.includes("created successfully")||i.includes("has been created")||Lm(n))return!0}return!1}function Ti(t,e){let n=Sn(t);if(!n)return[];let r=new Set;if(n.type==="event_msg"){let s=Sn(n.payload);if(s?.type==="image_generation_end"){let i=kt(s.saved_path);if(i){let o=et(i,e?.cwd);o&&Rt(o)&&r.add(o)}}}if(e?.includePatchCalls&&n.type==="response_item"){let s=Sn(n.payload);if(s?.type==="function_call"&&s.name==="apply_patch"){let i=kt(s.arguments);if(i)for(let o of Rm(i,e?.cwd))r.add(o)}}return[...r]}async function su(t,e){let n=[...new Set(t.map(s=>et(s)).filter(Boolean))],r=[];for(let s of n)if(Rt(s))try{let i=await(0,eu.stat)(s);if(Math.max(i.birthtimeMs||0,i.ctimeMs||0,i.mtimeMs||0)+Cm<e)continue;r.push(s)}catch{}return r}var ie=N.child({module:"claude"}),lu="claude-permission-denial:",Nm=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Om(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function xi(t){Om()&&mr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
85
+ `)}function Bm(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 Dm(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Fm(t){if(typeof t=="string")return t;let e=Bm(t);return e||(Dm(t)?"":JSON.stringify(t))}function Hm(t){return/requested permissions|haven't granted/i.test(t)}function iu(t){return t.replace(Nm,"").replace(/\s+/g," ").trim()}function Um(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Wm(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 qm(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function ou(t){let e=iu(t.resultText??""),n=(t.stderrLines??[]).map(iu).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&Wm(i));if(r)return qm(r);let s=[e,...n].find(i=>!!i&&!Um(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Tr(t){return t.startsWith(lu)}var _n=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,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ie.info({sessionId:this.sessionId,cwd:e},"session initialized"),I.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),br(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Qc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ie.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),xi(`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=r;if(S.isTransientPath(i)||i==="claude"){let u=S.execViaLoginShell("claude",r);o=u.command,a=u.args}else o=i;this.proc=(0,au.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let c=u.message;u.code==="ENOENT"&&this.cwd&&!(0,Ar.existsSync)(this.cwd)&&(c=`Working directory does not exist: ${this.cwd}`),ie.error({sessionId:this.sessionId,error:c,cwd:this.cwd},"spawn error"),I.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:c}),this.handler?.({type:"error",sessionId:this.sessionId,message:c})}),this.buffer="",this.proc.stdout.on("data",u=>{this.buffer+=u.toString();let c=this.buffer.split(`
87
+ `);this.buffer=c.pop();for(let d of c)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ie.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let c=u.toString().trim();c&&(ie.debug({sessionId:this.sessionId,stderr:c},"stderr"),this.lastStderr.push(c),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(u,c)=>{ie.info({sessionId:this.sessionId,exitCode:u,signal:c},"process exited");let d=this.interrupted;this.proc=null,br(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):u&&u!==0&&!this.sawFinalResult&&(ie.error({sessionId:this.sessionId,exitCode:u,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:ou({stderrLines:this.lastStderr,exitCode:u})})),this.exitHandler?.(u)})}respondApproval(e,n){if(ie.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ie.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
88
+ `),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ie.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ie.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,br(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 r=e.session_id??"";r&&r!==this.sessionId&&(ie.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),I.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)){this.emittedToolCallIds.add(s.id);let i=s.input??{},o=wr(s.name,i,this.cwd);this.toolCallContext.set(s.id,{toolName:s.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ar.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:i,toolCallId:s.id})}break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=typeof s.tool_use_id=="string"?s.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Fm(s.content);if(!s.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ar.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!s.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Ir(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(s.is_error===!0&&i&&Hm(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 r=e.request;r?.subtype==="can_use_tool"&&(I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){xi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:ou({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,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}.`;I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${lu}${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}:void 0;xi("Claude finished. Run `claude --continue` to continue on desktop."),I.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var fu=require("child_process"),pu=require("fs");var Ci=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();N.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},_=new Ci;var cu=require("node:fs"),ki=require("node:path"),Gm="@vibelet/cli";function jm(t){try{let e=JSON.parse((0,cu.readFileSync)(t,"utf8"));if(e.name===Gm&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function $m(){return"1.0.17"}var Et=$m();var E=N.child({module:"codex"});function zm(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 Vm(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 Y(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}var Ym=new Set(["aborted","interrupted","cancelled","canceled"]);function Jm(t){let e=M(t);return e?e.toLowerCase():null}function Km(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Ri(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function Ei(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function hu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function gu(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Xm(t){if(!Array.isArray(t))return null;for(let e of t){let n=Y(e);if(!n)continue;let r=M(n.id),s=Array.isArray(n.options)?n.options.map(l=>Y(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>hu(l))??i[0],a=i.find(l=>gu(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Qm(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>Y(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>Y(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(s=>hu(s)),r=e.some(s=>gu(s));return n&&r}function uu(t){let e=Km(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Ei(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Ei(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=M(t.server),r=M(t.tool)??M(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:Y(t.arguments)??Y(t.input)??{}}:null}return null}function Zm(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>Y(o)?.kind==="create"))return null;let i=et(n,e);return Rt(i)?i:null}function ey(t){if(!Array.isArray(t))return"";for(let e of t){let n=Y(e);if(!n)continue;let r=M(n.question)??M(n.header);if(r)return r}return""}function du(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 bn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)||s==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,E.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,E.info({spawnCmd:i,args:o},"spawning");I.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,fu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,pu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),E.error({error:d,cwd:e},"spawn error"),I.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 p of d)if(p.trim())try{this.handleRaw(JSON.parse(p))}catch{E.warn({linePreview:p.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(E.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{E.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&E.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let l=_.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Et},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=du(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,E.info({threadId:this.threadId},"thread resumed"),I.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??"",E.info({threadId:this.threadId},"thread created"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=du(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,E.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{E.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,E.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return E.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
90
+ `),!0}restorePendingApproval(e){let n=Vm(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,E.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=_.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
91
91
  `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),E.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
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=Y(e?.item)??e??null,r=Ti(n);if(!r)return null;let s=n?au(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?ki(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),I.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){E.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:Um(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!zm(o)){E.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=$m(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},Ym(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},P(r?.reason)??P(r?.description)??"");return}if(e==="item/permissions/requestApproval"){E.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}E.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(E.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=Y(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&E.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||E.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=Y(r?.item),i=Ti(s),o=s?au(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=Y(r?.item)??r,i=Ti(s),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Vm(o.input,this.cwd);if(a){let l=Ie([a]);l&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:i,output:l})}}i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=P(r?.reason)??P(Y(r?.turn)?.reason);E.info({threadId:this.threadId,reason:s},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=Y(r?.turn),i=Gm(s?.status),o=Y(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&Wm.has(i)){E.info({threadId:this.threadId,status:i},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}E.info({threadId:this.threadId,status:i??"completed"},"turn completed"),I.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&E.debug({method:n},"unhandled notification");break}}};var N=require("fs/promises"),Vi=require("fs"),Yi=require("readline"),O=require("path"),ue=require("os");var Jm=new Set(["New session","Resumed session","Untitled session"]),Km=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Xm(t){return t.replace(/\s+/g," ").trim()}function Ir(t){return typeof t!="string"?void 0:Xm(t)||void 0}function pu(t){let e=Ir(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function Pt(t){let e=Ir(t);return!e||Jm.has(e)||pu(e)}function Qm(t){for(let e of t.replace(/\r/g,"").split(`
94
- `)){let n=Ir(e);if(n&&!Zm(n)&&!ey(n))return n}}function Zm(t){return Km.some(e=>t.startsWith(e))}function ey(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function ty(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function Ri(t,e=80){if(typeof t!="string")return;let n=Qm(t);if(!n)return;let r=ty(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||pu(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function et(t,e){for(let n of t){let r=Ir(n);if(!(!r||Pt(r)))return r}return Ri(e)}var mu=require("child_process"),yu=require("util");var vu=(0,yu.promisify)(mu.execFile),Su=5e3,ny=2500,ry=3e3,_u=8,Ar=new Map,Ei=new Map,hu=null;function sy(t){let e=Ar.get(t);return e?Date.now()>e.expiresAt?(Ar.delete(t),null):e.value??void 0:null}function iy(t,e){if(e===void 0){Ar.delete(t);return}Ar.set(t,{value:e,expiresAt:Date.now()+Su})}async function oy(t){if(!t)return;if(hu)return hu(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await vu("git",["-C",t,...n],{env:Xe(),timeout:ny,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function ay(t){let e=sy(t);if(e!==null)return e;let n=Ei.get(t);if(n)return n;let r=oy(t).then(s=>(iy(t,s),s)).finally(()=>{Ei.delete(t)});return Ei.set(t,r),r}async function bu(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function wu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await bu(e,_u,async r=>{n.set(r,await ay(r))}),n}var Mi=new Map,Pi=new Map,gu=null;function ly(t,e){if(e===void 0){Mi.delete(t);return}Mi.set(t,{value:e,expiresAt:Date.now()+Su})}async function cy(t){if(t){if(gu)return gu(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await vu("git",["-C",t,"diff","HEAD","--shortstat"],{env:Xe(),timeout:ry,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function uy(t){let e=Mi.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=Pi.get(t);if(n)return n;let r=cy(t).then(s=>(ly(t,s),s)).finally(()=>{Pi.delete(t)});return Pi.set(t,r),r}async function Iu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await bu(e,_u,async r=>{n.set(r,await uy(r))}),n}var xu=require("child_process"),Tr=require("fs/promises"),tt=require("path"),Cu=require("os"),Tu=require("util");var dy=(0,Tu.promisify)(xu.execFile),Cr=L.child({module:"process-scanner"}),ku=5e3,fy=1500,py=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,hy=500,gy=15e3,wn=null,bn=null;function kr(){wn=null}var my=new Set(["sh","bash","zsh","fish"]),yy=new Set(["env","nohup","timeout","gtimeout"]),vy=new Set(["node","nodejs","bun","tsx"]),Sy=new Set(["-e","--eval","-p","--print"]),_y=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function by(t){return t.replace(/^['"]|['"]$/g,"")}function Ru(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(by)}function Au(t){let e=(0,tt.basename)(t);return e==="claude"||e==="codex"?e:null}function wy(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=Eu(Ru(e.trim()),!0);if(n)return n}return null}function Eu(t,e=!1){let n=0;for(;n<t.length;){let r=t[n],s=(0,tt.basename)(r);if(yy.has(s)){if(n+=1,s==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(s==="timeout"||s==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(my.has(s)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?wy(l):null}}return null}if(vy.has(s)){let o=n+1;for(;o<t.length;){let l=t[o];if(Sy.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,_y.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=Au(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=Au(r);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Li(t,e=!1){return Eu(Ru(t),e)}function Rr(t){let e=Li(t);return e?{agent:e.agent,args:e.args}:null}function Pu(t){return py.test(t)&&Li(t)!==null}function Iy(t,e){let n=Rr(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function Ay(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function xy(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function Cy(t,e){let n=Rr(e);if(!(!n||n.agent!==t))return t==="claude"?Ay(n.args):xy(n.args)}function xr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Ty(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function ky(t,e){let n=Li(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(r=>r.startsWith("--listen=")))}function Ry(t){let e=[...new Set(t.sessionFiles)].filter(i=>Ty(t.agent,i)),n=Iy(t.agent,t.command),r=Cy(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=Mt(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function Ey(t,e){let n=t,r=e;(xr(e.confidence)>xr(t.confidence)||xr(e.confidence)===xr(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function Ni(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Ey(s,n):n)}return[...e.values()]}function Py(t){try{return process.kill(t,0),!0}catch{return!1}}async function Er(t,e,n=fy){try{let{stdout:r}=await dy(t,e,{maxBuffer:8388608,timeout:n});return r}catch(r){let s=typeof r=="object"&&r!==null?{code:"code"in r?r.code:void 0,signal:"signal"in r?r.signal:void 0,killed:"killed"in r?r.killed:void 0}:{},i=String(r);return i.includes("ESRCH")||i.includes("No such process")?Cr.debug({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command skipped \u2014 process exited"):Cr.warn({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command failed"),""}}async function My(t){if(!t.sessionFilePath)return t;let e=await nt(t.sessionFilePath,t.agent);if(!e)return null;let n=await Bi(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function Ly(t){return process.platform==="win32"?"":(await Er("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
95
- `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Ny(t){if(process.platform==="win32")return[];let n=(await Er("lsof",["-p",String(t),"-Fn"])).split(`
96
- `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Oy(t){return t.split(`
97
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2];if(!Pu(s))return null;let i=Rr(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function By(){let t=await Er("ps",["-axo","pid=,command="],ku);return Oy(t)}async function Dy(){return(await Er("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],ku)).split(`
98
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!Pu(s))return null;let i=Rr(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function Fy(){return process.platform==="win32"?Dy():By()}async function Hy(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await Fy();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let r=n.filter(o=>Py(o.pid));t&&(t.aliveProcesses=r.length);let s=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(r.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await Ly(o.pid),sessionFiles:await Ny(o.pid)})));return t&&(t.lsofMs+=s()),t&&(t.snapshots=i.length),i}function Uy(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function qy(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,tt.join)((0,Cu.homedir)(),".claude","projects",Uy(e)),s=(await(0,Tr.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(s.length===0)return null;let i=null;if(await Promise.all(s.map(async l=>{let u=await(0,Tr.stat)((0,tt.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,tt.join)(n,i.name),a=Mt(t,o);return a?{sessionId:a,filePath:o}:null}return Lu(e)}catch{return null}}async function Wy(){let t={pgrepMs:0,lsofMs:0,fallbackMs:0,hydrateMs:0,totalMs:0,matchedProcesses:0,aliveProcesses:0,snapshots:0,directCandidates:0,fallbackLookups:0,fallbackHits:0,hydratedCandidates:0},e=_.startTimer("process.scan.total_ms"),n=await Hy(t),r=[],s=[];for(let c of n){let d=Ry(c);if(d){r.push(d);continue}ky(c.agent,c.command)&&s.push(c)}t.directCandidates=r.length,t.fallbackLookups=s.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(s.map(async c=>{let d=await qy(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...r,...o.filter(c=>c!==null)].map(c=>My(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Ni(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=hy||t.fallbackLookups>0)&&Cr.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"),wn={value:u,expiresAt:Date.now()+gy},u}async function Oi(){return wn&&Date.now()<wn.expiresAt?wn.value:bn||(bn=Wy().finally(()=>{bn=null}),bn)}async function Mu(t){try{return(await Oi()).some(n=>n.sessionId===t)}catch(e){return Cr.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var Bu=require("fs"),De=require("fs/promises"),Fi=require("os"),An=require("path");var In=L.child({module:"activity-watcher"}),Gy=12e4,jy=5e3,$y=6e4,Nu=5;function zy(){return(0,An.join)((0,Fi.homedir)(),".claude","projects")}function Vy(){return(0,An.join)((0,Fi.homedir)(),".codex","sessions")}async function Ou(t){try{return await(0,De.realpath)(t)}catch{return t}}function Pr(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Di=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 Ou(e?.claudeDir??zy()),r=await Ou(e?.codexDir??Vy());if(this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges(),e?.usePolling){let s=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},s);a.unref?.(),this.pollTimers.push(a)}}else for(let[s,i]of this.roots)this.startNativeWatch(s,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(s=>{In.warn({error:String(s)},"activity watcher rescan failed")})},$y),this.rescanTimer.unref?.(),In.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let r=(0,Bu.watch)(e,{recursive:!0,persistent:!0},(s,i)=>{if(!i)return;let o=(0,An.join)(e,i.toString());Pr(o,n)&&this.resolveFsEvent(n,o)});r.on("error",s=>{In.warn({error:String(s),root:e},"activity watcher error")}),this.watchers.push(r)}catch(r){In.warn({error:String(r),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let r=await(0,De.stat)(n).catch(()=>null);if(!r){this.handleUnlink(n);return}r.isFile()&&await this.handleFsChange(n,r.mtimeMs)}async pollScan(e,n){let r=await this.walkSessionFiles(n,Nu),s=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of r){if(!Pr(o,e))continue;s.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&&(s.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=Gy){let n=Date.now(),r=n-e,s=n-jy,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,Nu);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{Pr(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,De.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,An.join)(i,l.name);if(l.isDirectory()){await s(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,De.stat)(u).catch(()=>null);c&&r.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!Pr(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await nt(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,r),c.mtimeMs=Math.max(c.mtimeMs,s),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:r,mtimeMs:s}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,De.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){In.warn({error:String(n)},"activity listener failed")}}updateGauges(){_.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[],this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},Lt=new Di;var rt=L.child({module:"inventory"}),qu=6e3,Yy=1e4;function Jy(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function Ky(){return Lt.listActive().map(Jy)}var Wu={listScannedSessions:kn,listWatcherSessions:Ky,scanRunningSessions:Oi,searchSessionContent:Ju},ce=Xy(),Cn=null,Mr=0,Nr=0,Lr=0,Hi=0,Ui=new Set;function Xy(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Qy(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,branch:t.branch,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode,interruptReason:t.interruptReason})}function Zy(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 Du(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Qy).sort(),runningSessions:t.runningSessions.map(Zy).sort()})}function ev(){for(let t of Ui)try{t()}catch(e){rt.warn({error:String(e)},"session inventory backfill listener failed")}}function xn(){_.gauge("session.inventory.external_cached_sessions",ce.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",ce.runningSessions.length),_.gauge("session.inventory.backfill_inflight",Cn?1:0)}function Gu(t){return Ui.add(t),()=>{Ui.delete(t)}}function ju(){return{cachedSessions:ce.scannedSessions.length,runningSessions:ce.runningSessions.length,cacheAgeMs:ce.refreshedAt?Math.max(0,Date.now()-ce.refreshedAt):void 0,backfillInFlight:!!Cn,lastBackfillDurationMs:Lr||void 0,lastBackfillCompletedAt:Nr?new Date(Nr).toISOString():void 0,lastBackfillAppliedAt:Hi?new Date(Hi).toISOString():void 0}}xn();function $u(){return Lt.onActivity(()=>{Yu(Wu,qu)})}var Nt={daemonActive:3,externalRunning:2,idle:1},Fu={high:3,medium:2,low:1};function zu(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function tv(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||Nt[e.runtime.state]-Nt[t.runtime.state]||zu(t,e)}function nv(t,e){return Nt[e.state]>Nt[t.state]?e:Nt[e.state]<Nt[t.state]?t:Fu[e.confidence]>Fu[t.confidence]?e:t}function rv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function sv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function iv(t,e){return e?t?!(Pt(e)&&!Pt(t)):!0:!1}function qi(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function ov(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...qi(),...t.interruptReason?{needsAttention:!0}:{}},managed:t.managed,approvalMode:t.approvalMode,...t.interruptReason?{interruptReason:t.interruptReason}:{}}}function av(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 lv(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||!!t.interruptReason||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode,...t.interruptReason?{interruptReason:t.interruptReason}:{}}}function cv(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=iv(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=nv(s.runtime,n.runtime),u=s.sources.slice();for(let g of n.sources)u.includes(g)||u.push(g);let c=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),f=c?s.lastActivityAt:d?n.lastActivityAt:sv(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,branch:a,title:i,createdAt:rv(s.createdAt,n.createdAt),lastActivityAt:f,sources:u,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode,interruptReason:n.interruptReason??s.interruptReason})}}function uv(...t){let e=new Map;for(let n of t)cv(e,n);return[...e.values()]}function dv(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let u=(l.title??"").toLowerCase(),c=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",f=u.includes(o)||c.includes(o)||(d?d.includes(o):!1),g=s?.has(l.sessionId)??!1;if(!f&&!g)return!1}return!0});return r&&rt.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function fv(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Hu(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),u=uv(t.sessionRecords.map(ov),t.scannedSessions,t.runningSessions.map(w=>av(w,t.scannedAt)),t.activeSessions.map(lv)),c=t.deletedSessionIds?.size?u.filter(w=>!t.deletedSessionIds?.has(w.sessionId)):u,d=dv(c,r,s,i,o,a),f=d.filter(w=>w.runtime.state!=="idle"||w.managed).sort(tv),g=d.filter(w=>w.runtime.state==="idle"&&!w.managed).sort(zu),h=fv(g,n),p=g.slice(h,h+l),y=h+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:[...f,...p],nextCursor:y}}async function Uu(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([wu(e),Iu(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function Tn(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,u=c=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(c))};l=setTimeout(()=>{if(a)return;let c=Array.isArray(s)&&s.length>0;rt.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:c?s.length:0},c?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u(c?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(c=>{u(c)}).catch(c=>{a||rt.warn({source:t,error:String(c)},"session inventory source failed, using fallback"),u(n)})})}function pv(t=Date.now()){return ce.refreshedAt===0||t-ce.refreshedAt>=Yy}async function Vu(t,e){let[n,r]=await Promise.all([Tn("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),Tn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Ni([...n,...r])}async function hv(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([Tn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),Vu(t,e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Yu(t,e){if(Cn)return;let n=Mr,r=_.startTimer("session.inventory.backfill_latency_ms");Cn=hv(t,e).then(s=>{if(n!==Mr)return;let i=Du(ce);ce=s;let o=Du(s),a=r();Lr=a,Nr=Date.now(),xn(),i!==o&&(Hi=Date.now(),_.increment("session.inventory.backfill_applied"),rt.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),ev())}).catch(s=>{n===Mr&&(Lr=r(),Nr=Date.now(),xn(),rt.warn({error:String(s),durationMs:Lr},"session inventory external backfill failed"))}).finally(()=>{n===Mr&&(Cn=null,xn())}),xn()}async function Or(t){let e={...Wu,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??qu);if(!t.search){let c=_.startTimer("session.inventory.fast_path_latency_ms");pv()&&Yu(e,n);let d=ce,f=Hu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return c(),f;let g=await Uu(f);return c(),g}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([Tn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),Vu(e,n),Tn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);rt.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let u=Hu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?u:Uu(u)}var Ae=L.child({module:"scanner"});function Ji(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Ki=3e4,$i=Ji(Ki),zi=Ji(Ki),Dr=Ji(Ki),Wi=new Map,Gi=new Map,Br=null,st=24;function Ur(){$i.clear(),zi.clear(),Dr.clear()}function td(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function it(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}async function nd(){let t=(0,O.join)((0,ue.homedir)(),".codex","sessions"),e=await(0,N.readdir)(t).catch(()=>[]),n=[];for(let s of e){let i=(0,O.join)(t,s),o=await(0,N.readdir)(i).catch(()=>[]);for(let a of o){let l=(0,O.join)(i,a),u=await(0,N.readdir)(l).catch(()=>[]);for(let c of u){let d=(0,O.join)(l,c),f=await(0,N.readdir)(d).catch(()=>[]);for(let g of f)g.endsWith(".jsonl")&&n.push((0,O.join)(d,g))}}}let r=await it(n,st,async s=>{let i=await(0,N.stat)(s).catch(()=>null);return{path:s,mtimeMs:i?.mtimeMs??0}});return r.sort((s,i)=>i.mtimeMs-s.mtimeMs),r}function gv(t){let e=`codex-latest:${(0,ue.homedir)()}`,n=new Map;for(let r of t)n.has(r.cwd)||n.set(r.cwd,r.match);Dr.set(e,n)}function*rd(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
99
- `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var ji=512*1024,Ku=256*1024;async function sd(t,e){if(e<=ji)return(0,N.readFile)(t,"utf-8");let n=await(0,N.open)(t,"r");try{let r=Buffer.alloc(ji),{bytesRead:s}=await n.read(r,0,ji,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function mv(t,e){if(e<=Ku)return(0,N.readFile)(t,"utf-8");let n=await(0,N.open)(t,"r");try{let r=Math.max(0,e-Ku),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Xu(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function yv(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function vv(t){return t?.type==="permission-mode"?Xu(t.permissionMode):Xu(t?.permissionMode)}function Sv(t){if(t?.type==="turn_context")return yv(t.payload)}async function id(t,e,n){let r,s=await mv(t,n);for(let i of s.split(`
100
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?vv(o):Sv(o);a&&(r=a)}return r}function Xi(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"?Xi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function qr(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 _v=["<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 bv(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?_v.some(r=>n.startsWith(r)):!1}function Wr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=qr(t.message.content);return bv(t,e)?"":e}function wv(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function Iv(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
93
+ `)}resolveToolContext(e){let n=Y(e?.item)??e??null,r=Ri(n);if(!r)return null;let s=n?uu(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?Ei(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),I.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){E.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:zm(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},M(r?.reason)??M(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},M(r?.reason)??M(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Qm(o)){E.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Xm(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},ey(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},M(r?.reason)??M(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},M(r?.reason)??M(r?.description)??"");return}if(e==="item/permissions/requestApproval"){E.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}E.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(E.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=Y(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&E.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||E.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=Y(r?.item),i=Ri(s),o=s?uu(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=Y(r?.item)??r,i=Ri(s),o=i?this.toolContextByCallId.get(i):null;if(i&&o?.toolName==="Patch"&&this.handler){let a=Zm(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"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=M(r?.reason)??M(Y(r?.turn)?.reason);E.info({threadId:this.threadId,reason:s},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=Y(r?.turn),i=Jm(s?.status),o=Y(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&Ym.has(i)){E.info({threadId:this.threadId,status:i},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}E.info({threadId:this.threadId,status:i??"completed"},"turn completed"),I.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&E.debug({method:n},"unhandled notification");break}}};var O=require("fs/promises"),Ji=require("fs"),Ki=require("readline"),B=require("path"),ue=require("os");var ty=new Set(["New session","Resumed session","Untitled session"]),ny=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function ry(t){return t.replace(/\s+/g," ").trim()}function xr(t){return typeof t!="string"?void 0:ry(t)||void 0}function mu(t){let e=xr(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function Pt(t){let e=xr(t);return!e||ty.has(e)||mu(e)}function sy(t){for(let e of t.replace(/\r/g,"").split(`
94
+ `)){let n=xr(e);if(n&&!iy(n)&&!oy(n))return n}}function iy(t){return ny.some(e=>t.startsWith(e))}function oy(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function ay(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function Pi(t,e=80){if(typeof t!="string")return;let n=sy(t);if(!n)return;let r=ay(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||mu(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function tt(t,e){for(let n of t){let r=xr(n);if(!(!r||Pt(r)))return r}return Pi(e)}var Su=require("child_process"),_u=require("util");var bu=(0,_u.promisify)(Su.execFile),wu=5e3,ly=2500,cy=3e3,Iu=8,Cr=new Map,Mi=new Map,yu=null;function uy(t){let e=Cr.get(t);return e?Date.now()>e.expiresAt?(Cr.delete(t),null):e.value??void 0:null}function dy(t,e){if(e===void 0){Cr.delete(t);return}Cr.set(t,{value:e,expiresAt:Date.now()+wu})}async function fy(t){if(!t)return;if(yu)return yu(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await bu("git",["-C",t,...n],{env:Qe(),timeout:ly,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function py(t){let e=uy(t);if(e!==null)return e;let n=Mi.get(t);if(n)return n;let r=fy(t).then(s=>(dy(t,s),s)).finally(()=>{Mi.delete(t)});return Mi.set(t,r),r}async function Au(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function Tu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Au(e,Iu,async r=>{n.set(r,await py(r))}),n}var Ni=new Map,Li=new Map,vu=null;function hy(t,e){if(e===void 0){Ni.delete(t);return}Ni.set(t,{value:e,expiresAt:Date.now()+wu})}async function gy(t){if(t){if(vu)return vu(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await bu("git",["-C",t,"diff","HEAD","--shortstat"],{env:Qe(),timeout:cy,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function my(t){let e=Ni.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=Li.get(t);if(n)return n;let r=gy(t).then(s=>(hy(t,s),s)).finally(()=>{Li.delete(t)});return Li.set(t,r),r}async function xu(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Au(e,Iu,async r=>{n.set(r,await my(r))}),n}var ku=require("child_process"),Er=require("fs/promises"),nt=require("path"),Ru=require("os"),Eu=require("util");var yy=(0,Eu.promisify)(ku.execFile),Rr=N.child({module:"process-scanner"}),Pu=5e3,vy=1500,Sy=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,_y=500,by=15e3,In=null,wn=null;function Pr(){In=null}var wy=new Set(["sh","bash","zsh","fish"]),Iy=new Set(["env","nohup","timeout","gtimeout"]),Ay=new Set(["node","nodejs","bun","tsx"]),Ty=new Set(["-e","--eval","-p","--print"]),xy=new Set(["-r","--require","--import","--loader","--experimental-loader","--env-file","--input-type"]);function Cy(t){return t.replace(/^['"]|['"]$/g,"")}function Mu(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Cy)}function Cu(t){let e=(0,nt.basename)(t);return e==="claude"||e==="codex"?e:null}function ky(t){for(let e of t.split(/&&|\|\||;|\n/)){let n=Lu(Mu(e.trim()),!0);if(n)return n}return null}function Lu(t,e=!1){let n=0;for(;n<t.length;){let r=t[n],s=(0,nt.basename)(r);if(Iy.has(s)){if(n+=1,s==="env")for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n+=1;else if(s==="timeout"||s==="gtimeout"){for(;n<t.length&&t[n].startsWith("-");){let o=t[n];n+=1,o==="-k"&&n<t.length&&(n+=1)}n<t.length&&(n+=1)}continue}if(wy.has(s)){for(let o=n+1;o<t.length;o+=1){let a=t[o];if(a==="-c"||a==="-lc"||a==="-ic"||a==="-xc"||a==="-ec"||a==="-xec"){let l=t[o+1];return l?ky(l):null}}return null}if(Ay.has(s)){let o=n+1;for(;o<t.length;){let l=t[o];if(Ty.has(l))return null;if(l==="--"){o+=1;break}if(!l.startsWith("-"))break;o+=1,xy.has(l)&&o<t.length&&(o+=1)}if(o>=t.length)return null;let a=Cu(t[o]);return a?{agent:a,args:t.slice(o+1),viaWrapper:!0}:null}let i=Cu(r);return i?{agent:i,args:t.slice(n+1),viaWrapper:e}:null}return null}function Oi(t,e=!1){return Lu(Mu(t),e)}function Mr(t){let e=Oi(t);return e?{agent:e.agent,args:e.args}:null}function Nu(t){return Sy.test(t)&&Oi(t)!==null}function Ry(t,e){let n=Mr(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function Ey(t){if(t.includes("--dangerously-skip-permissions"))return"autoApprove";for(let e=0;e<t.length;e+=1){let n=t[e],r=t[e+1],s=n==="--permission-mode"?r:n.startsWith("--permission-mode=")?n.slice(18):void 0;if(s==="plan")return"plan";if(s==="acceptEdits")return"acceptEdits";if(s==="default")return"normal"}}function Py(t){if(t.includes("--dangerously-bypass-approvals-and-sandbox"))return"autoApprove"}function My(t,e){let n=Mr(e);if(!(!n||n.agent!==t))return t==="claude"?Ey(n.args):Py(n.args)}function kr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Ly(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Ny(t,e){let n=Oi(e);return!n||n.agent!==t||n.viaWrapper?!1:t==="claude"?!n.args.includes("--continue")&&!n.args.includes("-c"):!(n.args[0]==="app-server"&&!n.args.includes("--listen")&&!n.args.some(r=>r.startsWith("--listen=")))}function Oy(t){let e=[...new Set(t.sessionFiles)].filter(i=>Ly(t.agent,i)),n=Ry(t.agent,t.command),r=My(t.agent,t.command);if(n)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"high",...r?{approvalMode:r}:{},...e.length===1?{sessionFilePath:e[0]}:{}};if(e.length!==1)return null;let s=Mt(t.agent,e[0]);return s?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:s,confidence:"medium",...r?{approvalMode:r}:{},sessionFilePath:e[0]}:null}function By(t,e){let n=t,r=e;(kr(e.confidence)>kr(t.confidence)||kr(e.confidence)===kr(t.confidence)&&e.pid!==void 0&&t.pid!==void 0&&e.pid<t.pid)&&(n=e,r=t);let s=n.approvalMode??r.approvalMode;return{...n,cwd:n.cwd||r.cwd,...s?{approvalMode:s}:{},title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath,isResponding:n.isResponding??r.isResponding}}function Bi(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?By(s,n):n)}return[...e.values()]}function Dy(t){try{return process.kill(t,0),!0}catch{return!1}}async function Lr(t,e,n=vy){try{let{stdout:r}=await yy(t,e,{maxBuffer:8388608,timeout:n});return r}catch(r){let s=typeof r=="object"&&r!==null?{code:"code"in r?r.code:void 0,signal:"signal"in r?r.signal:void 0,killed:"killed"in r?r.killed:void 0}:{},i=String(r);return i.includes("ESRCH")||i.includes("No such process")?Rr.debug({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command skipped \u2014 process exited"):Rr.warn({file:t,args:e,timeoutMs:n,error:i,...s},"process scan command failed"),""}}async function Fy(t){if(!t.sessionFilePath)return t;let e=await rt(t.sessionFilePath,t.agent);if(!e)return null;let n=await Fi(t.sessionFilePath,t.agent),r=e.approvalMode??t.approvalMode;return{...t,cwd:t.cwd||e.cwd,...r?{approvalMode:r}:{},title:t.title??e.title,isResponding:n.isResponding}}async function Hy(t){return process.platform==="win32"?"":(await Lr("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
95
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Uy(t){if(process.platform==="win32")return[];let n=(await Lr("lsof",["-p",String(t),"-Fn"])).split(`
96
+ `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}function Wy(t){return t.split(`
97
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2];if(!Nu(s))return null;let i=Mr(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function qy(){let t=await Lr("ps",["-axo","pid=,command="],Pu);return Wy(t)}async function Gy(){return(await Lr("wmic",["process","get","ProcessId,CommandLine","/FORMAT:CSV"],Pu)).split(`
98
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.split(",");if(n.length<3)return null;let r=Number(n[n.length-1]),s=n.slice(1,n.length-1).join(",");if(!Number.isFinite(r)||r===0||!Nu(s))return null;let i=Mr(s);return i?{pid:r,command:s,agent:i.agent}:null}).filter(e=>!!e)}async function jy(){return process.platform==="win32"?Gy():qy()}async function $y(t){let e=_.startTimer("process.scan.pgrep_ms"),n=await jy();t&&(t.pgrepMs+=e()),t&&(t.matchedProcesses=n.length);let r=n.filter(o=>Dy(o.pid));t&&(t.aliveProcesses=r.length);let s=_.startTimer("process.scan.lsof_ms"),i=await Promise.all(r.map(async o=>({pid:o.pid,agent:o.agent,command:o.command,cwd:await Hy(o.pid),sessionFiles:await Uy(o.pid)})));return t&&(t.lsofMs+=s()),t&&(t.snapshots=i.length),i}function zy(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Vy(t,e){if(!e)return null;try{if(t==="claude"){let n=(0,nt.join)((0,Ru.homedir)(),".claude","projects",zy(e)),s=(await(0,Er.readdir)(n).catch(()=>[])).filter(l=>l.endsWith(".jsonl"));if(s.length===0)return null;let i=null;if(await Promise.all(s.map(async l=>{let u=await(0,Er.stat)((0,nt.join)(n,l)).catch(()=>null);u&&(!i||u.mtimeMs>i.mtimeMs)&&(i={name:l,mtimeMs:u.mtimeMs})})),!i)return null;let o=(0,nt.join)(n,i.name),a=Mt(t,o);return a?{sessionId:a,filePath:o}:null}return Bu(e)}catch{return null}}async function Yy(){let t={pgrepMs:0,lsofMs:0,fallbackMs:0,hydrateMs:0,totalMs:0,matchedProcesses:0,aliveProcesses:0,snapshots:0,directCandidates:0,fallbackLookups:0,fallbackHits:0,hydratedCandidates:0},e=_.startTimer("process.scan.total_ms"),n=await $y(t),r=[],s=[];for(let c of n){let d=Oy(c);if(d){r.push(d);continue}Ny(c.agent,c.command)&&s.push(c)}t.directCandidates=r.length,t.fallbackLookups=s.length;let i=_.startTimer("process.scan.fallback_ms"),o=await Promise.all(s.map(async c=>{let d=await Vy(c.agent,c.cwd);return d?{agent:c.agent,pid:c.pid,cwd:c.cwd,command:c.command,sessionId:d.sessionId,confidence:"low",sessionFilePath:d.filePath}:null}));t.fallbackMs=i(),t.fallbackHits=o.filter(c=>c!==null).length;let a=_.startTimer("process.scan.hydrate_ms"),l=await Promise.all([...r,...o.filter(c=>c!==null)].map(c=>Fy(c)));t.hydrateMs=a(),t.hydratedCandidates=l.filter(c=>c!==null).length;let u=Bi(l.filter(c=>c!==null));return t.totalMs=e(),(t.totalMs>=_y||t.fallbackLookups>0)&&Rr.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"),In={value:u,expiresAt:Date.now()+by},u}async function Di(){return In&&Date.now()<In.expiresAt?In.value:wn||(wn=Yy().finally(()=>{wn=null}),wn)}async function Ou(t){try{return(await Di()).some(n=>n.sessionId===t)}catch(e){return Rr.warn({sessionId:t,error:String(e)},"isSessionProcessAlive failed, treating as not alive"),!1}}var Hu=require("fs"),Fe=require("fs/promises"),Ui=require("os"),Tn=require("path");var An=N.child({module:"activity-watcher"}),Jy=12e4,Ky=5e3,Xy=6e4,Du=5;function Qy(){return(0,Tn.join)((0,Ui.homedir)(),".claude","projects")}function Zy(){return(0,Tn.join)((0,Ui.homedir)(),".codex","sessions")}async function Fu(t){try{return await(0,Fe.realpath)(t)}catch{return t}}function Nr(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Hi=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 Fu(e?.claudeDir??Qy()),r=await Fu(e?.codexDir??Zy());if(this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges(),e?.usePolling){let s=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},s);a.unref?.(),this.pollTimers.push(a)}}else for(let[s,i]of this.roots)this.startNativeWatch(s,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(s=>{An.warn({error:String(s)},"activity watcher rescan failed")})},Xy),this.rescanTimer.unref?.(),An.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let r=(0,Hu.watch)(e,{recursive:!0,persistent:!0},(s,i)=>{if(!i)return;let o=(0,Tn.join)(e,i.toString());Nr(o,n)&&this.resolveFsEvent(n,o)});r.on("error",s=>{An.warn({error:String(s),root:e},"activity watcher error")}),this.watchers.push(r)}catch(r){An.warn({error:String(r),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let r=await(0,Fe.stat)(n).catch(()=>null);if(!r){this.handleUnlink(n);return}r.isFile()&&await this.handleFsChange(n,r.mtimeMs)}async pollScan(e,n){let r=await this.walkSessionFiles(n,Du),s=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of r){if(!Nr(o,e))continue;s.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&&(s.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=Jy){let n=Date.now(),r=n-e,s=n-Ky,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,Du);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{Nr(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,Fe.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let u=(0,Tn.join)(i,l.name);if(l.isDirectory()){await s(u,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let c=await(0,Fe.stat)(u).catch(()=>null);c&&r.push({filePath:u,mtimeMs:c.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!Nr(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await rt(n,e);if(!l)return;let u=`${e}:${l.sessionId}`,c=this.entries.get(u);if(c){c.lastActivityMs=Math.max(c.lastActivityMs,r),c.mtimeMs=Math.max(c.mtimeMs,s),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:r,mtimeMs:s}),this.filePathIndex.set(n,u)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,Fe.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){An.warn({error:String(n)},"activity listener failed")}}updateGauges(){_.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[],this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},Lt=new Hi;var st=N.child({module:"inventory"}),ju=6e3,ev=1e4;function tv(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function nv(){return Lt.listActive().map(tv)}var $u={listScannedSessions:Rn,listWatcherSessions:nv,scanRunningSessions:Di,searchSessionContent:Qu},ce=rv(),Cn=null,Or=0,Dr=0,Br=0,Wi=0,qi=new Set;function rv(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function sv(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 iv(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 Uu(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(sv).sort(),runningSessions:t.runningSessions.map(iv).sort()})}function ov(){for(let t of qi)try{t()}catch(e){st.warn({error:String(e)},"session inventory backfill listener failed")}}function xn(){_.gauge("session.inventory.external_cached_sessions",ce.scannedSessions.length),_.gauge("session.inventory.external_running_sessions",ce.runningSessions.length),_.gauge("session.inventory.backfill_inflight",Cn?1:0)}function zu(t){return qi.add(t),()=>{qi.delete(t)}}function Vu(){return{cachedSessions:ce.scannedSessions.length,runningSessions:ce.runningSessions.length,cacheAgeMs:ce.refreshedAt?Math.max(0,Date.now()-ce.refreshedAt):void 0,backfillInFlight:!!Cn,lastBackfillDurationMs:Br||void 0,lastBackfillCompletedAt:Dr?new Date(Dr).toISOString():void 0,lastBackfillAppliedAt:Wi?new Date(Wi).toISOString():void 0}}xn();function Yu(){return Lt.onActivity(()=>{Xu($u,ju)})}var Nt={daemonActive:3,externalRunning:2,idle:1},Wu={high:3,medium:2,low:1};function Ju(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function av(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||Nt[e.runtime.state]-Nt[t.runtime.state]||Ju(t,e)}function lv(t,e){return Nt[e.state]>Nt[t.state]?e:Nt[e.state]<Nt[t.state]?t:Wu[e.confidence]>Wu[t.confidence]?e:t}function cv(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function uv(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function dv(t,e){return e?t?!(Pt(e)&&!Pt(t)):!0:!1}function Gi(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function fv(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:{...Gi(),...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 pv(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 hv(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 gv(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=dv(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=lv(s.runtime,n.runtime),u=s.sources.slice();for(let h of n.sources)u.includes(h)||u.push(h);let c=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),p=c?s.lastActivityAt:d?n.lastActivityAt:uv(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,model:n.model??s.model,branch:a,title:i,createdAt:cv(s.createdAt,n.createdAt),lastActivityAt:p,sources:u,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode,lastUsage:n.lastUsage??s.lastUsage,interruptReason:n.interruptReason??s.interruptReason,stallWarning:n.stallWarning??s.stallWarning})}}function mv(...t){let e=new Map;for(let n of t)gv(e,n);return[...e.values()]}function yv(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let u=(l.title??"").toLowerCase(),c=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",p=u.includes(o)||c.includes(o)||(d?d.includes(o):!1),h=s?.has(l.sessionId)??!1;if(!p&&!h)return!1}return!0});return r&&st.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function vv(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function qu(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),u=mv(t.sessionRecords.map(fv),t.scannedSessions,t.runningSessions.map(A=>pv(A,t.scannedAt)),t.activeSessions.map(hv)),c=t.deletedSessionIds?.size?u.filter(A=>!t.deletedSessionIds?.has(A.sessionId)):u,d=yv(c,r,s,i,o,a),p=d.filter(A=>A.runtime.state!=="idle"||A.managed).sort(av),h=d.filter(A=>A.runtime.state==="idle"&&!A.managed).sort(Ju),g=vv(h,n),f=h.slice(g,g+l),y=g+f.length<h.length&&f.length>0?{lastActivityAt:f[f.length-1].lastActivityAt,sessionId:f[f.length-1].sessionId}:void 0;return{sessions:n?f:[...p,...f],nextCursor:y}}async function Gu(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([Tu(e),xu(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function kn(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,u=c=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(c))};l=setTimeout(()=>{if(a)return;let c=Array.isArray(s)&&s.length>0;st.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:c?s.length:0},c?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),u(c?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(c=>{u(c)}).catch(c=>{a||st.warn({source:t,error:String(c)},"session inventory source failed, using fallback"),u(n)})})}function Sv(t=Date.now()){return ce.refreshedAt===0||t-ce.refreshedAt>=ev}async function Ku(t,e){let[n,r]=await Promise.all([kn("watcher.running_sessions",()=>t.listWatcherSessions(),[],e),kn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return Bi([...n,...r])}async function _v(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([kn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),Ku(t,e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function Xu(t,e){if(Cn)return;let n=Or,r=_.startTimer("session.inventory.backfill_latency_ms");Cn=_v(t,e).then(s=>{if(n!==Or)return;let i=Uu(ce);ce=s;let o=Uu(s),a=r();Br=a,Dr=Date.now(),xn(),i!==o&&(Wi=Date.now(),_.increment("session.inventory.backfill_applied"),st.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),ov())}).catch(s=>{n===Or&&(Br=r(),Dr=Date.now(),xn(),st.warn({error:String(s),durationMs:Br},"session inventory external backfill failed"))}).finally(()=>{n===Or&&(Cn=null,xn())}),xn()}async function Fr(t){let e={...$u,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??ju);if(!t.search){let c=_.startTimer("session.inventory.fast_path_latency_ms");Sv()&&Xu(e,n);let d=ce,p=qu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return c(),p;let h=await Gu(p);return c(),h}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([kn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),Ku(e,n),kn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);st.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let u=qu({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?u:Gu(u)}var Te=N.child({module:"scanner"});function Xi(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var Qi=3e4,Vi=Xi(Qi),Yi=Xi(Qi),Ur=Xi(Qi),ji=new Map,$i=new Map,Hr=null,it=24;function Gr(){Vi.clear(),Yi.clear(),Ur.clear()}function sd(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function ot(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}async function id(){let t=(0,B.join)((0,ue.homedir)(),".codex","sessions"),e=await(0,O.readdir)(t).catch(()=>[]),n=[];for(let s of e){let i=(0,B.join)(t,s),o=await(0,O.readdir)(i).catch(()=>[]);for(let a of o){let l=(0,B.join)(i,a),u=await(0,O.readdir)(l).catch(()=>[]);for(let c of u){let d=(0,B.join)(l,c),p=await(0,O.readdir)(d).catch(()=>[]);for(let h of p)h.endsWith(".jsonl")&&n.push((0,B.join)(d,h))}}}let r=await ot(n,it,async s=>{let i=await(0,O.stat)(s).catch(()=>null);return{path:s,mtimeMs:i?.mtimeMs??0}});return r.sort((s,i)=>i.mtimeMs-s.mtimeMs),r}function bv(t){let e=`codex-latest:${(0,ue.homedir)()}`,n=new Map;for(let r of t)n.has(r.cwd)||n.set(r.cwd,r.match);Ur.set(e,n)}function*od(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
99
+ `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var zi=512*1024,Zu=256*1024;async function ad(t,e){if(e<=zi)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let r=Buffer.alloc(zi),{bytesRead:s}=await n.read(r,0,zi,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function wv(t,e){if(e<=Zu)return(0,O.readFile)(t,"utf-8");let n=await(0,O.open)(t,"r");try{let r=Math.max(0,e-Zu),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function ed(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Iv(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function Av(t){return t?.type==="permission-mode"?ed(t.permissionMode):ed(t?.permissionMode)}function Tv(t){if(t?.type==="turn_context")return Iv(t.payload)}async function ld(t,e,n){let r,s=await wv(t,n);for(let i of s.split(`
100
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?Av(o):Tv(o);a&&(r=a)}return r}function Zi(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 cd(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Zi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function jr(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 xv=["<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 Cv(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?xv.some(r=>n.startsWith(r)):!1}function $r(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=jr(t.message.content);return Cv(t,e)?"":e}function kv(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function Rv(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
101
101
  `):""}).filter(Boolean).join(`
102
- `):""}function Av(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(`
103
- `):""}function xv(t){if(typeof t=="string")return t;let e=Av(t);return e||(Array.isArray(t)&&t.length>0&&t.every(r=>r&&typeof r=="object"&&r.type==="tool_reference")?"":JSON.stringify(t))}function Cv(t){let e=Iv(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 ad(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Fr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:qi()}}function Mt(t,e){let n=(0,O.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 Tv(t,e){let n=await sd(t,e),r=rd(n,64),s="",i="",o,a,l;for(let u of r){let c;try{c=JSON.parse(u)}catch{continue}if(!s&&typeof c.cwd=="string"&&(s=c.cwd),!i&&typeof c.sessionId=="string"&&(i=c.sessionId),o||(o=et([c.customTitle,c.summary])),!l){let d=Wr(c),f=et([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Mt("claude",t)||(0,O.basename)(t,".jsonl"),cwd:s,title:o??l??et([],a),approvalMode:await id(t,"claude",e)}:null}async function kv(t,e){let n=await sd(t,e),r=rd(n,96),s="",i="",o,a,l;for(let u of r){let c;try{c=JSON.parse(u)}catch{continue}if(s||(s=c.payload?.cwd??c.cwd??""),i||(i=c.payload?.id??c.id??""),o||(o=et([c.payload?.title,c.title])),!l){let d=od(c),f=d&&!ad(d)?et([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Mt("codex",t)||(0,O.basename)(t,".jsonl"),cwd:s,title:o??l??et([],a),approvalMode:await id(t,"codex",e)}:null}async function nt(t,e){let n=await(0,N.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Tv(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await kv(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Qu(t,e){let n=(0,O.join)((0,ue.homedir)(),".claude","projects");try{let r;t?r=[td(t)]:r=(await(0,N.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let s=[];for(let l of r){let u=(0,O.join)(n,l),c=await(0,N.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&s.push((0,O.join)(u,d))}let i=await it(s,st,async l=>{let u=await(0,N.stat)(l).catch(()=>null);return{path:l,mtimeMs:u?.mtimeMs??0}});return i.sort((l,u)=>u.mtimeMs-l.mtimeMs),(await it(i,st,async l=>{let u=await nt(l.path,"claude");return u&&e&&e.push(Fr(u)),u})).filter(l=>l!==null).map(l=>Fr(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Ae.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Zu(t,e){try{let n=await nd(),r=await it(n,st,async i=>{let o=await nt(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Fr(o)),o});return gv(r.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),r.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Fr(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Ae.warn({error:String(n)},"failed to list codex sessions"),[]}}async function Lu(t){if(!t)return null;let e=`codex-latest:${(0,ue.homedir)()}`,n=Dr.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Br||(Br=(async()=>{let i=await nd(),o=await it(i,st,async l=>{let u=await nt(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 Dr.set(e,a),a})().finally(()=>{Br=null}));let s=(await Br).get(t);return s?{sessionId:s.sessionId,filePath:s.path}:null}async function kn(t,e,n){let s=`list:${(0,ue.homedir)()}:${t??"all"}:${e??""}`,i=$i.get(s);if(i)return i;let o=Wi.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Qu(e,n);else if(t==="codex")l=await Zu(e,n);else{let[u,c]=await Promise.all([Qu(e,n),Zu(e,n)]);l=[...u,...c].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return $i.set(s,l),l})();return Wi.set(s,a),a.finally(()=>Wi.delete(s)),a}async function Ju(t,e){let r=`search:${(0,ue.homedir)()}:${t}:${e??"all"}`,s=zi.get(r);if(s)return s;let i=Gi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function u(){let d=(0,O.join)((0,ue.homedir)(),".claude","projects");try{let f=await(0,N.readdir)(d,{withFileTypes:!0}),g=[];for(let p of f){if(!p.isDirectory())continue;let m=(0,O.join)(d,p.name),y=await(0,N.readdir)(m).catch(()=>[]);for(let w of y)w.endsWith(".jsonl")&&g.push((0,O.join)(m,w))}let h=await it(g,st,p=>ed(p,l,"claude"));for(let p of h)p&&a.add(p)}catch(f){Ae.warn({error:String(f)},"failed to search claude files")}}async function c(){let d=(0,O.join)((0,ue.homedir)(),".codex","sessions");try{let f=[];async function g(p){let m=await(0,N.readdir)(p,{withFileTypes:!0}).catch(()=>[]);for(let y of m){let w=(0,O.join)(p,y.name);y.isDirectory()?await g(w):y.name.endsWith(".jsonl")&&f.push(w)}}await g(d);let h=await it(f,st,p=>ed(p,l,"codex"));for(let p of h)p&&a.add(p)}catch(f){Ae.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await u():e==="codex"?await c():await Promise.all([u(),c()]),zi.set(r,a),a})();return Gi.set(r,o),o.finally(()=>Gi.delete(r)),o}async function ed(t,e,n){let r=(0,Vi.createReadStream)(t,{encoding:"utf-8"}),s=(0,Yi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Rv:Ev,o="",a=!1;try{for await(let l of s){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{s.close(),r.destroy()}return a?o||Mt(n,t):null}function Rv(t){return t?.type==="user"&&t.message?.role==="user"?Wr(t):t?.type==="assistant"&&t.message?.role==="assistant"?qr(t.message.content):""}function Ev(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Xi(t.payload.content)}let e=od(t);return e||""}async function Hr(t,e){let n=(0,Vi.createReadStream)(t,{encoding:"utf-8"}),r=(0,Yi.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function ld(t,e){let n=(0,O.join)((0,ue.homedir)(),".claude","projects"),r=e?td(e):null,s=await(0,N.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,O.join)(n,o,`${t}.jsonl`);if((await(0,N.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Qi(t,e,n){if(e==="claude")return ld(t,n);let r=(0,O.join)((0,ue.homedir)(),".codex","sessions");return ud(r,t)}function Pv(t){if(t?.type==="user"&&t.message?.role==="user")return wv(t.message.content)?{kind:"toolResult",...Cv(t)?{interrupted:!0}:{}}:Wr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=qr(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 Mv(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 Bi(t,e){if(e!=="claude")return{};let n=null;try{await Hr(t,r=>{let s=Pv(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Ae.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Mv(n)}async function Zi(t,e,n){let r=await Qi(t,e,n);return r?Bi(r,e):{}}function Lv(t){if(typeof t?.timestamp!="string")return null;let e=Date.parse(t.timestamp);return Number.isFinite(e)?e:null}async function cd(t,e,n,r){if(e!=="codex"||!r||r<=0)return[];let s=await Qi(t,e,n);if(!s)return[];let i=[];try{await Hr(s,l=>{let u=Lv(l);u!=null&&u<r||i.push(...Ii(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Ae.warn({filePath:s,error:String(l)},"failed to read generated file notices"),[]}let o=await tu(i,r),a=Ie(o);return a?[a]:[]}async function Rn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"){let a=r[r.length-1];if(a?.role==="assistant"&&!eu(a.content)){r[r.length-1]=i;return}}r.push(i)};if(e==="claude")try{let i=await ld(t,n);if(i){let o=new Map;await Hr(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=Sr(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"||u.is_error===!0)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=xv(u.content);if(!_r(a.toolUseResult,f))continue;let g=Ie([d]);g&&s({role:"assistant",content:g})}let l=Wr(a);l&&s({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=qr(a.message.content);l&&s({role:"assistant",content:l})}})}}catch(i){Ae.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await Qi(t,e,n);i&&await Hr(i,o=>{let a=Ii(o,{cwd:n,includePatchCalls:!0}),l=Ie(a);if(l&&s({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=Xi(o.payload.content);c&&(u==="user"&&ad(c)||s({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Ae.warn({error:String(i)},"failed to read codex session history")}return r}async function ud(t,e){try{let n=await(0,N.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,O.join)(t,r.name);if(r.isDirectory()){let i=await ud(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Ae.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Ot=require("fs"),hd=require("path");var Nv=500,dd=200;function fd(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=dd?e:e.slice(-dd)}function Ov(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 Bv(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))typeof n!="string"||n.length===0||typeof r!="string"||r.length===0||n===r||(e[n]=r);return e}function Dv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Fv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),n}function pd(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:fd(t.acceptedClientMessageIds),interruptedClientMessageIds:fd(t.interruptedClientMessageIds),pendingApproval:Dv(t.pendingApproval),interruptReason:Fv(t.interruptReason)}}function Hv(t){if(Array.isArray(t))return{records:t.map(pd),deletedSessionIds:[],sessionAliases:{}};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(pd):[],deletedSessionIds:Ov(e.deletedSessionIds),sessionAliases:Bv(e.sessionAliases)}}return{records:[],deletedSessionIds:[],sessionAliases:{}}}var Gr=class{records;deletedSessionIds;sessionAliases;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds),this.sessionAliases=new Map(Object.entries(e.sessionAliases))}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,r=new Set;for(;!r.has(n);){r.add(n);let s=this.sessionAliases.get(n);if(!s||s===n)break;n=s}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(r=>r.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let r=this.resolveSessionId(n);if(!r||e===r){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,r),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(s=>s.sessionId!==e&&s.sessionId!==n);let r=[];for(let[s,i]of this.sessionAliases)(s===e||s===n||i===n)&&(this.sessionAliases.delete(s),r.push(s));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let s of r)this.deletedSessionIds.add(s);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()},Nv)}loadFromDisk(){try{let e=(0,Ot.readFileSync)(dr,"utf-8");return Hv(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[],sessionAliases:{}}}saveToDisk(){(0,Ot.mkdirSync)((0,hd.dirname)(dr),{recursive:!0}),(0,Ot.writeFileSync)(dr,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases)},null,2))}};var Bt=require("path"),gd=require("os");function jr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Bt.join)((0,gd.homedir)(),t.slice(2)):t}function Uv(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function eo(t,e){let n=jr(Uv(t));if(!n||(0,Bt.isAbsolute)(n))return n;let r=jr(e??"");return r?(0,Bt.resolve)(r,n):n}var md={approvalRequestV1:"vibelet.approvalRequest.v1"};var Dt=require("fs"),yd=require("path");function qv(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function Wv(t){try{let e=(0,Dt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(qv):[]}catch{return[]}}function En(t,e){(0,Dt.mkdirSync)((0,yd.dirname)(t),{recursive:!0}),(0,Dt.writeFileSync)(t,JSON.stringify(e,null,2)+`
104
- `,"utf8")}var $r=class{constructor(e=Lc){this.pushSubscriptionsPath=e;this.records=Wv(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],En(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,En(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,En(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&En(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],En(this.pushSubscriptionsPath,this.records)}};var K=L.child({module:"push"}),Gv="https://exp.host/--/api/v2/push/send",jv="https://exp.host/--/api/v2/push/getReceipts",$v=[0,1e3,3e3],Pn=new $r;function zv(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 Vv(t){return new Promise(e=>{setTimeout(e,t)})}function vd(t){return t==="DeviceNotRegistered"}function Yv(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function Jv(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function Kv(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function Xv(t,e,n,r){let s=new Map(t);for(let i of $v){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(jv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(c){K.error({error:String(c),count:s.size},"push receipt request failed");return}if(!o.ok){K.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){K.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=Kv(a,s);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 g=r.unregisterToken(c);K.info({token:c,errorCode:f,removed:g},"push token removed after receipt rejection")}}s=new Map(l.map(c=>[c,s.get(c)]))}s.size>0&&K.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function Qv(t){let e=t?.pushStore??Pn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??Vv;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let u=l.map(c=>({to:c,sound:"default",title:i,body:o,data:a,badge:1,priority:"high",_contentAvailable:!0,...zv(a)&&a.eventType==="approval_request"?{categoryId:md.approvalRequestV1}:{}}));try{let c=await n(Gv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok){K.error({status:c.status,statusText:c.statusText},"push send failed");return}let d=await c.json().catch(()=>null);if(!d){K.error({count:u.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:g}=Yv(d,l),h=Jv(d,l);for(let{token:p,ticket:m}of g){let y=m.details?.error;if(K.error({token:p,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),vd(y)){let w=e.unregisterToken(p);K.info({token:p,errorCode:y,removed:w},"push token removed after ticket rejection")}}f.length>0&&(K.debug({count:f.length},"push sent"),e.markSent(f)),h.size>0&&await Xv(h,n,r,e)}catch(c){K.error({error:String(c)},"push send error")}}}function to(t,e){Pn.register(t,e),K.info({deviceId:t,token:e,total:Pn.count()},"push token registered")}function no(t,e){let n=Pn.unregister(t,e);K.info({deviceId:t,token:e,total:Pn.count(),removed:n},"push token unregistered")}var zr=Qv();var b=L.child({module:"manager"}),Zv="Done.",eS="Approval required",Sd=180,Ft=200,tS="Agent \u5361\u4F4F",nS="Agent \u5D29\u6E83",_d=200;function bd(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),r=e%60;return r===0?`${n} \u5206\u949F`:`${n} \u5206 ${r} \u79D2`}function Td(t){if(!t)return;let e=t.trim();if(e)return e.length>_d?`${e.slice(0,_d-1)}\u2026`:e}function rS(t,e,n){let r=bd(t),s=bd(e),i=Td(n),o=i?`
105
- \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${i}"\u3002`:"";return{kind:"stall_timeout",at:new Date().toISOString(),humanText:`Agent \u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${s} \u9608\u503C\u540E\u88AB\u81EA\u52A8\u505C\u6B62\u3002${o}`,...i?{lastPrompt:i}:{},idleMs:t}}function sS(t,e){let n=Td(e),r=n?`
106
- \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${r}`,...n?{lastPrompt:n}:{},exitCode:t}}function xe(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>Ft&&e.splice(0,e.length-Ft));return e}function Vr(t){return t?.length?{acceptedClientMessageIds:xe(t)}:{}}function X(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:xe(t.acceptedClientMessageIds),interruptedClientMessageIds:xe(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0,interruptReason:t.interruptReason}}function wd(t){t.managed||(t.managed=!0)}function Id(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&wr(e)}function Ad(t,e,n){return{sessionId:t,agent:e,...n}}function iS(t){return t.startsWith(bi)}function xd(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 Yr=class{constructor(e=zr,n=Mu){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=Gu(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new Gr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs,r=S.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(b.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;b.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:o.agent}),I.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a});let l=rS(a,r,o.lastUserMessage);o.interruptReason=l,this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"session.interrupted_notice",sessionId:o.sessionId,reason:l}),this.pushSender(tS,this.buildPushBody(`${o.title||o.sessionId}: ${l.lastPrompt??""}`.trim()),{sessionId:o.sessionId,agent:o.agent,eventType:"agent_stalled"}),this.touchSession(o.sessionId),this.store.upsert(X(o)),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(b.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:o.agent}),I.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){b.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(b.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!Id(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){I.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}b.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender(eS,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"&&wr(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:b.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),o.type==="session.done"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),I.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;_.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&Id(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",l||(e.pendingApproval=void 0),a){let u=sS(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u}),this.pushSender(nS,this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim()),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert(X(e)),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(X(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&cd(e.sessionId,e.agent,e.cwd,n).then(r=>{for(let s of r)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:s})}).catch(r=>{b.warn({sessionId:e.sessionId,error:String(r)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof _n&&s&&n.setModel(s),e!=="claude"||!(n instanceof Sn))return;let i=r??(0,ro.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=yn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&iS(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),yn;if(r.approvalMode==="autoApprove")return xd(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return yn;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,ro.randomUUID)()}`,c=r.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,f,g=new Promise(h=>{f=h});return r.pendingClaudeHookApprovals.set(u,{requestId:u,promise:g,resolve:h=>{r.pendingClaudeHookApprovals.delete(u),f(h)}}),r.pendingApproval={requestId:u,toolName:i,input:a,description:d},I.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:u,toolName:i,input:a,description:d}),g}async resolveReconnectSession(e,n,r){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,u=r?.title??"",c=r?.createdAt??s,d=r?.lastActivityAt??s,f=xe(r?.acceptedClientMessageIds),g=xe(r?.interruptedClientMessageIds),h=r?.isResponding,p=r?.interruptReason,m=r?"memory":"client",y=this.store.find(e);if(y)i=y.agent,o=y.cwd||o,a=y.approvalMode??a,l=y.pendingApproval??l,u=y.title||u,c=y.createdAt||c,d=y.lastActivityAt||d,f=xe(y.acceptedClientMessageIds,f),g=xe(y.interruptedClientMessageIds,g),p=p??y.interruptReason,m="record";else if(!r){let A=(await kn(n??i)).find(x=>x.sessionId===e);A&&(i=A.agent,o=A.cwd||o,u=A.title??u,c=A.createdAt,d=A.lastActivityAt,h=A.runtime.isResponding??h,m="scanner")}if(!i&&n&&(i=n,m=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:u,createdAt:c,lastActivityAt:d,acceptedClientMessageIds:f,interruptedClientMessageIds:g,source:m,managed:r?.managed??y?.managed,isResponding:h||void 0,...p?{interruptReason:p}:{}}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Ad(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Ad(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(X(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<=Sd?n:`${n.slice(0,Math.max(1,Sd-3)).trimEnd()}...`:Zv}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(X(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;_.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{}});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 r=n?{...n}:{};return e.remapped&&(r.sessionId=e.resolvedSessionId,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}buildSessionResponseData(e,n,r){let s=r?{...r}:{};return n&&n!==e.requestedSessionId&&(s.sessionId=n,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s: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 kn(e,n)}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.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);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Or({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=jr(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Cd.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return b.info({sessionId:u.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(l){b.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),u=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let h=`pending_${Date.now()}`;b.info({sessionId:h,agent:r,cwd:s},"session created (pending codex startup)"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:h,agent:r,cwd:s,approvalMode:i});let p={sessionId:h,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(h,p),this.registerClaudeHookSession(p),this.store.upsert(X(p)),this.updateGauges(),Ur(),kr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:h}),this.startPendingCodexSession(p,e);return}let c=_.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=c();b.info({sessionId:d,agent:r,spawnMs:f},"session created"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let g={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,g),this.registerClaudeHookSession(g),this.store.upsert(X(g)),this.updateGauges(),Ur(),kr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(g,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){b.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){let a=this.resolveSessionRef(r);if(r=a.resolvedSessionId,this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(r);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let g=await Rn(r,s,l.cwd),h=this.annotateHistoryMessages(g,l.acceptedClientMessageIds,l.interruptedClientMessageIds),p=this.currentPartialReplyText(l);if(g.length>0||p||l.approvalMode||l.pendingApproval){let m={type:"session.history",sessionId:r,messages:h,...Vr(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:p,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval};e.readyState===1&&e.send(JSON.stringify(m))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:r}));return}let u=this.store.find(r),c=i||u?.cwd||"",d=o??u?.approvalMode,f=u?.title??"Resumed session";try{let g=_.startTimer("driver.spawn"),h=this.createDriver(s),p=this.configureDriverBeforeStart(s,h),m=this.canResumeDriverSession(s,r),y=await h.start(c,m?r:void 0,d),w=g();b.info({sessionId:y,agent:s,spawnMs:w},"session resumed"),_.increment("session.resume",{agent:s}),I.emit("session.resume",{sessionId:y,agent:s,cwd:c});let A={sessionId:y,agent:s,cwd:c,approvalMode:d,driver:h,clients:new Set([e]),title:f,createdAt:u?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:u?.acceptedClientMessageIds??[],interruptedClientMessageIds:u?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,claudeHookSecret:p,pendingClaudeHookApprovals:new Map};this.sessions.set(y,A),this.rememberSessionAlias(r,y),this.registerClaudeHookSession(A),this.store.upsert(X(A)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(A,s," (resumed)",e),this.restoreDriverPendingApproval(h,A.pendingApproval);let T=await Rn(m?r:y,s,c),W=this.annotateHistoryMessages(T,A.acceptedClientMessageIds,A.interruptedClientMessageIds);if(T.length>0||A.pendingApproval){b.info({sessionId:r,historyCount:T.length},"sending history messages");let z={type:"session.history",sessionId:y,messages:W,...Vr(A.acceptedClientMessageIds),approvalMode:d,pendingApproval:A.pendingApproval};e.readyState===1&&e.send(JSON.stringify(z))}this.reply(e,n,!0,this.buildSessionResponseData(a,y,{sessionId:y}))}catch(g){this.reply(e,n,!1,void 0,String(g))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Ft&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Ft))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Ft&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Ft))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let 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];s.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)}async sendMessage(e,n,r,s,i,o,a,l){let u=this.resolveSessionRef(r);if(r=u.resolvedSessionId,this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let h=await this.resolveReconnectSession(r,i,c);if(!h){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:h.agent,source:h.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:h.agent,source:h.source}),I.emit("session.reconnect",{sessionId:r,agent:h.agent,source:h.source});try{let p=this.createDriver(h.agent),m=this.configureDriverBeforeStart(h.agent,p,c?.claudeHookSecret),y=this.canResumeDriverSession(h.agent,r),w=await p.start(h.cwd,y?r:void 0,h.approvalMode);this.restoreDriverPendingApproval(p,h.pendingApproval),c?(c.approvalMode=h.approvalMode,c.pendingApproval=h.pendingApproval,c.driver=p,c.active=!0,c.clients.add(e),c.lastActivityAt=h.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=xe(c.acceptedClientMessageIds,h.acceptedClientMessageIds),c.interruptedClientMessageIds=xe(c.interruptedClientMessageIds,h.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=m??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,w&&w!==c.sessionId&&this.remapSessionId(c,w)):(c={sessionId:w,agent:h.agent,cwd:h.cwd,approvalMode:h.approvalMode,driver:p,clients:new Set([e]),title:h.title,createdAt:h.createdAt,lastActivityAt:h.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:h.acceptedClientMessageIds,interruptedClientMessageIds:h.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:h.managed,pendingApproval:h.pendingApproval,claudeHookSecret:m,pendingClaudeHookApprovals:new Map,interruptReason:h.interruptReason},this.sessions.set(w,c),this.rememberSessionAlias(r,w)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,h.agent," (reconnected)"),this.store.upsert(X(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),r=c.sessionId}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:r,clientMessageId:o,duplicate:!0}));return}if(b.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),I.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),wd(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert(X(c)),this.noteInventoryChanged("session_updated")),Pt(c.title)){let h=Ri(s,50);h&&h!==c.title&&(c.title=h),this.store.upsert(X(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let d=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]),f=a?.length?a.map(h=>{let p=h.lastIndexOf("."),m=p>=0?h.slice(p).toLowerCase():"";return`[Attached ${d.has(m)?"image":"file"}: ${h}]`}).join(`
107
- `):"",g=f?s?`${s}
102
+ `):""}function Ev(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(`
103
+ `):""}function Pv(t){if(typeof t=="string")return t;let e=Ev(t);return e||(Array.isArray(t)&&t.length>0&&t.every(r=>r&&typeof r=="object"&&r.type==="tool_reference")?"":JSON.stringify(t))}function Mv(t){let e=Rv(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 ud(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Wr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Gi()}}function Mt(t,e){let n=(0,B.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 Lv(t,e){let n=await ad(t,e),r=od(n,64),s="",i="",o,a,l;for(let u of r){let c;try{c=JSON.parse(u)}catch{continue}if(!s&&typeof c.cwd=="string"&&(s=c.cwd),!i&&typeof c.sessionId=="string"&&(i=c.sessionId),o||(o=tt([c.customTitle,c.summary])),!l){let d=$r(c),p=tt([],d);p&&(a=d,l=p)}if(s&&(o||l))break}return s?{sessionId:i||Mt("claude",t)||(0,B.basename)(t,".jsonl"),cwd:s,title:o??l??tt([],a),approvalMode:await ld(t,"claude",e)}:null}async function Nv(t,e){let n=await ad(t,e),r=od(n,96),s="",i="",o,a,l;for(let u of r){let c;try{c=JSON.parse(u)}catch{continue}if(s||(s=c.payload?.cwd??c.cwd??""),i||(i=c.payload?.id??c.id??""),o||(o=tt([c.payload?.title,c.title])),!l){let d=cd(c),p=d&&!ud(d)?tt([],d):void 0;p&&(a=d,l=p)}if(s&&(o||l))break}return s?{sessionId:i||Mt("codex",t)||(0,B.basename)(t,".jsonl"),cwd:s,title:o??l??tt([],a),approvalMode:await ld(t,"codex",e)}:null}async function rt(t,e){let n=await(0,O.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Lv(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await Nv(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function td(t,e){let n=(0,B.join)((0,ue.homedir)(),".claude","projects");try{let r;t?r=[sd(t)]:r=(await(0,O.readdir)(n,{withFileTypes:!0})).filter(u=>u.isDirectory()).map(u=>u.name);let s=[];for(let l of r){let u=(0,B.join)(n,l),c=await(0,O.readdir)(u).catch(()=>[]);for(let d of c)d.endsWith(".jsonl")&&s.push((0,B.join)(u,d))}let i=await ot(s,it,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 ot(i,it,async l=>{let u=await rt(l.path,"claude");return u&&e&&e.push(Wr(u)),u})).filter(l=>l!==null).map(l=>Wr(l)).sort((l,u)=>u.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Te.warn({error:String(r)},"failed to list claude sessions"),[]}}async function nd(t,e){try{let n=await id(),r=await ot(n,it,async i=>{let o=await rt(i.path,"codex");return o&&e&&(!t||o.cwd===t)&&e.push(Wr(o)),o});return bv(r.map((i,o)=>i?{cwd:i.cwd,match:{path:n[o].path,mtimeMs:n[o].mtimeMs,sessionId:i.sessionId}}:null).filter(i=>i!==null)),r.filter(i=>i!==null).filter(i=>!t||i.cwd===t).map(i=>Wr(i)).sort((i,o)=>o.lastActivityAt.localeCompare(i.lastActivityAt))}catch(n){return Te.warn({error:String(n)},"failed to list codex sessions"),[]}}async function Bu(t){if(!t)return null;let e=`codex-latest:${(0,ue.homedir)()}`,n=Ur.get(e);if(n){let i=n.get(t);return i?{sessionId:i.sessionId,filePath:i.path}:null}Hr||(Hr=(async()=>{let i=await id(),o=await ot(i,it,async l=>{let u=await rt(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 Ur.set(e,a),a})().finally(()=>{Hr=null}));let s=(await Hr).get(t);return s?{sessionId:s.sessionId,filePath:s.path}:null}async function Rn(t,e,n){let s=`list:${(0,ue.homedir)()}:${t??"all"}:${e??""}`,i=Vi.get(s);if(i)return i;let o=ji.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await td(e,n);else if(t==="codex")l=await nd(e,n);else{let[u,c]=await Promise.all([td(e,n),nd(e,n)]);l=[...u,...c].sort((d,p)=>p.lastActivityAt.localeCompare(d.lastActivityAt))}return Vi.set(s,l),l})();return ji.set(s,a),a.finally(()=>ji.delete(s)),a}async function Qu(t,e){let r=`search:${(0,ue.homedir)()}:${t}:${e??"all"}`,s=Yi.get(r);if(s)return s;let i=$i.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function u(){let d=(0,B.join)((0,ue.homedir)(),".claude","projects");try{let p=await(0,O.readdir)(d,{withFileTypes:!0}),h=[];for(let f of p){if(!f.isDirectory())continue;let m=(0,B.join)(d,f.name),y=await(0,O.readdir)(m).catch(()=>[]);for(let A of y)A.endsWith(".jsonl")&&h.push((0,B.join)(m,A))}let g=await ot(h,it,f=>rd(f,l,"claude"));for(let f of g)f&&a.add(f)}catch(p){Te.warn({error:String(p)},"failed to search claude files")}}async function c(){let d=(0,B.join)((0,ue.homedir)(),".codex","sessions");try{let p=[];async function h(f){let m=await(0,O.readdir)(f,{withFileTypes:!0}).catch(()=>[]);for(let y of m){let A=(0,B.join)(f,y.name);y.isDirectory()?await h(A):y.name.endsWith(".jsonl")&&p.push(A)}}await h(d);let g=await ot(p,it,f=>rd(f,l,"codex"));for(let f of g)f&&a.add(f)}catch(p){Te.warn({error:String(p)},"failed to search codex files")}}return e==="claude"?await u():e==="codex"?await c():await Promise.all([u(),c()]),Yi.set(r,a),a})();return $i.set(r,o),o.finally(()=>$i.delete(r)),o}async function rd(t,e,n){let r=(0,Ji.createReadStream)(t,{encoding:"utf-8"}),s=(0,Ki.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Ov:Bv,o="",a=!1;try{for await(let l of s){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{s.close(),r.destroy()}return a?o||Mt(n,t):null}function Ov(t){return t?.type==="user"&&t.message?.role==="user"?$r(t):t?.type==="assistant"&&t.message?.role==="assistant"?jr(t.message.content):""}function Bv(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Zi(t.payload.content)}let e=cd(t);return e||""}async function qr(t,e){let n=(0,Ji.createReadStream)(t,{encoding:"utf-8"}),r=(0,Ki.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function dd(t,e){let n=(0,B.join)((0,ue.homedir)(),".claude","projects"),r=e?sd(e):null,s=await(0,O.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,B.join)(n,o,`${t}.jsonl`);if((await(0,O.stat)(a).catch(()=>null))?.isFile())return a}return null}async function eo(t,e,n){if(e==="claude")return dd(t,n);let r=(0,B.join)((0,ue.homedir)(),".codex","sessions");return pd(r,t)}function Dv(t){if(t?.type==="user"&&t.message?.role==="user")return kv(t.message.content)?{kind:"toolResult",...Mv(t)?{interrupted:!0}:{}}:$r(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=jr(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 Fv(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 Fi(t,e){if(e!=="claude")return{};let n=null;try{await qr(t,r=>{let s=Dv(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Te.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Fv(n)}async function to(t,e,n){let r=await eo(t,e,n);return r?Fi(r,e):{}}function Hv(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,r){if(e!=="codex"||!r||r<=0)return[];let s=await eo(t,e,n);if(!s)return[];let i=[];try{await qr(s,l=>{let u=Hv(l);u!=null&&u<r||i.push(...Ti(l,{cwd:n,includePatchCalls:!1}))})}catch(l){return l.code!=="ENOENT"&&Te.warn({filePath:s,error:String(l)},"failed to read generated file notices"),[]}let o=await su(i,r),a=Ae(o);return a?[a]:[]}async function En(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"){let a=r[r.length-1];if(a?.role==="assistant"&&!ru(a.content)){r[r.length-1]=i;return}}r.push(i)};if(e==="claude")try{let i=await dd(t,n);if(i){let o=new Map;await qr(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=wr(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"||u.is_error===!0)continue;let c=typeof u.tool_use_id=="string"?u.tool_use_id:"",d=c?o.get(c):void 0;if(!d)continue;let p=Pv(u.content);if(!Ir(a.toolUseResult,p))continue;let h=Ae([d]);h&&s({role:"assistant",content:h})}let l=$r(a);l&&s({role:"user",content:l})}else if(a.type==="assistant"&&a.message?.role==="assistant"){let l=jr(a.message.content);l&&s({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 eo(t,e,n);i&&await qr(i,o=>{let a=Ti(o,{cwd:n,includePatchCalls:!0}),l=Ae(a);if(l&&s({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=Zi(o.payload.content);c&&(u==="user"&&ud(c)||s({role:u,content:c},{coalesceConsecutiveAssistant:!0}))})}catch(i){Te.warn({error:String(i)},"failed to read codex session history")}return r}async function pd(t,e){try{let n=await(0,O.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,B.join)(t,r.name);if(r.isDirectory()){let i=await pd(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Te.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Ot=require("fs"),yd=require("path");var Uv=500,hd=200;function gd(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 Wv(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 qv(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))typeof n!="string"||n.length===0||typeof r!="string"||r.length===0||n===r||(e[n]=r);return e}function Gv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function jv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(e.kind!=="stall_timeout"&&e.kind!=="driver_crash"||typeof e.at!="string"||!e.at||typeof e.humanText!="string"||!e.humanText)return;let n={kind:e.kind,at:e.at,humanText:e.humanText};return typeof e.lastPrompt=="string"&&e.lastPrompt&&(n.lastPrompt=e.lastPrompt),typeof e.idleMs=="number"&&Number.isFinite(e.idleMs)&&(n.idleMs=e.idleMs),typeof e.exitCode=="number"&&Number.isFinite(e.exitCode)&&(n.exitCode=e.exitCode),n}function $v(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 zv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=Number(e.inputTokens),r=Number(e.outputTokens);if(!(!Number.isFinite(n)||!Number.isFinite(r)))return{inputTokens:n,outputTokens:r}}function md(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:gd(t.acceptedClientMessageIds),interruptedClientMessageIds:gd(t.interruptedClientMessageIds),pendingApproval:Gv(t.pendingApproval),lastUsage:zv(t.lastUsage),interruptReason:jv(t.interruptReason),stallWarning:$v(t.stallWarning)}}function Vv(t){if(Array.isArray(t))return{records:t.map(md),deletedSessionIds:[],sessionAliases:{}};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(md):[],deletedSessionIds:Wv(e.deletedSessionIds),sessionAliases:qv(e.sessionAliases)}}return{records:[],deletedSessionIds:[],sessionAliases:{}}}var zr=class{records;deletedSessionIds;sessionAliases;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds),this.sessionAliases=new Map(Object.entries(e.sessionAliases))}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}resolveSessionId(e){let n=e,r=new Set;for(;!r.has(n);){r.add(n);let s=this.sessionAliases.get(n);if(!s||s===n)break;n=s}return n}find(e){let n=this.resolveSessionId(e);return this.records.find(r=>r.sessionId===n)}isDeleted(e){let n=this.resolveSessionId(e);return this.deletedSessionIds.has(e)||this.deletedSessionIds.has(n)}upsert(e){this.deletedSessionIds.delete(e.sessionId),this.sessionAliases.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}addAlias(e,n){if(!e||!n)return;let r=this.resolveSessionId(n);if(!r||e===r){this.sessionAliases.delete(e),this.deletedSessionIds.delete(e),this.scheduleSave();return}this.deletedSessionIds.delete(e),this.sessionAliases.set(e,r),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(s=>s.sessionId!==e&&s.sessionId!==n);let r=[];for(let[s,i]of this.sessionAliases)(s===e||s===n||i===n)&&(this.sessionAliases.delete(s),r.push(s));this.deletedSessionIds.add(n),e!==n&&this.deletedSessionIds.add(e);for(let s of r)this.deletedSessionIds.add(s);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()},Uv)}loadFromDisk(){try{let e=(0,Ot.readFileSync)(fr,"utf-8");return Vv(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[],sessionAliases:{}}}saveToDisk(){(0,Ot.mkdirSync)((0,yd.dirname)(fr),{recursive:!0}),(0,Ot.writeFileSync)(fr,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds],sessionAliases:Object.fromEntries(this.sessionAliases)},null,2))}};var Bt=require("path"),vd=require("os");function Vr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Bt.join)((0,vd.homedir)(),t.slice(2)):t}function Yv(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function no(t,e){let n=Vr(Yv(t));if(!n||(0,Bt.isAbsolute)(n))return n;let r=Vr(e??"");return r?(0,Bt.resolve)(r,n):n}var Sd={approvalRequestV1:"vibelet.approvalRequest.v1"};var Dt=require("fs"),_d=require("path");function Jv(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function Kv(t){try{let e=(0,Dt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Jv):[]}catch{return[]}}function Pn(t,e){(0,Dt.mkdirSync)((0,_d.dirname)(t),{recursive:!0}),(0,Dt.writeFileSync)(t,JSON.stringify(e,null,2)+`
104
+ `,"utf8")}var Yr=class{constructor(e=Oc){this.pushSubscriptionsPath=e;this.records=Kv(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],Pn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,Pn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,Pn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&Pn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],Pn(this.pushSubscriptionsPath,this.records)}};var X=N.child({module:"push"}),Xv="https://exp.host/--/api/v2/push/send",Qv="https://exp.host/--/api/v2/push/getReceipts",Zv=[0,1e3,3e3],Mn=new Yr;function eS(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 tS(t){return new Promise(e=>{setTimeout(e,t)})}function bd(t){return t==="DeviceNotRegistered"}function nS(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function rS(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function sS(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function iS(t,e,n,r){let s=new Map(t);for(let i of Zv){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Qv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(c){X.error({error:String(c),count:s.size},"push receipt request failed");return}if(!o.ok){X.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){X.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:u}=sS(a,s);for(let{token:c,receipt:d}of u){let p=d.details?.error;if(X.error({token:c,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),bd(p)){let h=r.unregisterToken(c);X.info({token:c,errorCode:p,removed:h},"push token removed after receipt rejection")}}s=new Map(l.map(c=>[c,s.get(c)]))}s.size>0&&X.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function oS(t){let e=t?.pushStore??Mn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??tS;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let u=l.map(c=>({to:c,sound:"default",title:i,body:o,data:a,badge:1,priority:"high",_contentAvailable:!0,...eS(a)&&a.eventType==="approval_request"?{categoryId:Sd.approvalRequestV1}:{}}));try{let c=await n(Xv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!c.ok){X.error({status:c.status,statusText:c.statusText},"push send failed");return}let d=await c.json().catch(()=>null);if(!d){X.error({count:u.length},"push send returned unreadable response");return}let{successfulTokens:p,ticketErrors:h}=nS(d,l),g=rS(d,l);for(let{token:f,ticket:m}of h){let y=m.details?.error;if(X.error({token:f,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),bd(y)){let A=e.unregisterToken(f);X.info({token:f,errorCode:y,removed:A},"push token removed after ticket rejection")}}p.length>0&&(X.debug({count:p.length},"push sent"),e.markSent(p)),g.size>0&&await iS(g,n,r,e)}catch(c){X.error({error:String(c)},"push send error")}}}function ro(t,e){Mn.register(t,e),X.info({deviceId:t,token:e,total:Mn.count()},"push token registered")}function so(t,e){let n=Mn.unregister(t,e);X.info({deviceId:t,token:e,total:Mn.count(),removed:n},"push token unregistered")}var Jr=oS();var b=N.child({module:"manager"}),aS="Done.",lS="Approval required",wd=180,Ft=200,cS=6e4,Id=9e4,uS="Agent \u5361\u4F4F",dS="Agent \u5D29\u6E83",Ad=200;function Ht(t){let e=Math.round(t/1e3);if(e<60)return`${e} \u79D2`;let n=Math.floor(e/60),r=e%60;return r===0?`${n} \u5206\u949F`:`${n} \u5206 ${r} \u79D2`}function Ed(t){if(!t)return;let e=t.trim();if(e)return e.length>Ad?`${e.slice(0,Ad-1)}\u2026`:e}function fS(t,e,n,r){let s=Ht(t),i=Ht(n),o=Ht(e),a=Ed(r),l=a?`
105
+ \u6700\u540E\u7684\u8BF7\u6C42\u662F\uFF1A"${a}"\u3002`:"",u=n>e?`Agent \u957F\u65F6\u95F4\u6CA1\u6709\u8F93\u51FA\u3002\u5DF2 ${s} \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 ${s} \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}}function pS(t,e,n){let r=Ht(t),s=Ht(e),i=n>0?Ht(n):void 0;return{at:new Date().toISOString(),humanText:i?`Agent \u53EF\u80FD\u5361\u4F4F\u4E86\u3002\u5DF2 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${s} \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 ${r} \u6CA1\u6709\u8F93\u51FA\uFF0C\u8D85\u8FC7 ${s} \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,...n>0?{hardTimeoutMs:n}:{}}}function hS(t,e){let n=Ed(e),r=n?`
106
+ \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${r}`,...n?{lastPrompt:n}:{},exitCode:t}}function xe(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>Ft&&e.splice(0,e.length-Ft));return e}function Kr(t){return t?.length?{acceptedClientMessageIds:xe(t)}:{}}function J(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,model:t.model,acceptedClientMessageIds:xe(t.acceptedClientMessageIds),interruptedClientMessageIds:xe(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}}function Td(t){t.managed||(t.managed=!0)}function xd(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Tr(e)}function Cd(t,e,n){return{sessionId:t,agent:e,...n}}function gS(t){return t.startsWith(Ii)}function kd(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 Xr=class{constructor(e=Jr,n=Ou){this.pushSender=e;this.externalProcessPresenceCheck=n;this.removeInventoryBackfillListener=zu(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.updateGauges(),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new zr;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(),cS),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=this.advanceWatchdogClock(Date.now(),"sweep"),n=S.idleTimeoutMs,r=S.turnStallTimeoutMs,s=S.turnStallHardTimeoutMs;if(n<=0&&r<=0)return;let i=3600*1e3;for(let[o,a]of this.sessions){if(!a.active&&!a.driver){if(a.clients.size===0){let u=e-a.lastActivityTs;u>=i&&(b.info({sessionId:a.sessionId,inactiveMs:u},"removing inactive session from memory"),_.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(a),this.sessions.delete(o))}continue}if(!a.active||!a.driver)continue;let l=e-a.lastActivityTs;if(a.isResponding){if(r<=0||a.pendingApproval||l<r)continue;let u=this.getRespondingLivenessHint(a),c=s>0&&l>=s,d=u==="dead";if(!d&&!c){if(!a.stallWarningAt){let g=pS(l,r,s);a.stallWarningAt=e,a.stallWarning=g,this.updateGauges(),b.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:r,turnStallHardTimeoutMs:s,livenessHint:u},"responding session exceeded soft stall threshold; waiting before forced stop"),_.increment("driver.stall_warning",{agent:a.agent}),I.emit("driver.stall_warning",{sessionId:a.sessionId,agent:a.agent,idleMs:l,hardTimeoutMs:s||void 0}),this.broadcast(a.sessionId,{type:"session.stall_warning",sessionId:a.sessionId,warning:g}),this.store.upsert(J(a)),this.noteInventoryChanged("session_updated")}continue}let p=d||s<=0?r:s;b.warn({sessionId:a.sessionId,agent:a.agent,inactiveMs:l,turnStallTimeoutMs:r,turnStallHardTimeoutMs:s,livenessHint:u},"stopping stalled driver"),_.increment("driver.stall_timeout",{agent:a.agent}),I.emit("driver.stall_timeout",{sessionId:a.sessionId,agent:a.agent,idleMs:l});let h=fS(l,r,p,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="",this.updateGauges(),this.broadcast(a.sessionId,{type:"session.interrupted_notice",sessionId:a.sessionId,reason:h}),this.pushSender(uS,this.buildPushBody(`${a.title||a.sessionId}: ${h.lastPrompt??""}`.trim()),{sessionId:a.sessionId,agent:a.agent,eventType:"agent_stalled"}),this.touchSession(a.sessionId),this.store.upsert(J(a)),this.noteInventoryChanged("session_updated");continue}a.pendingApproval||n<=0||l<n||(b.info({sessionId:a.sessionId,agent:a.agent,idleMs:l,timeoutMs:n},"stopping idle driver"),_.increment("driver.idle_timeout",{agent:a.agent}),I.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,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){b.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(b.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.done"&&o.usage&&(e.lastUsage=o.usage),o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!xd(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){I.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}b.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender(lS,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"&&Tr(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:b.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry"));let a=this.clearStallWarning(e);this.touchSession(e.sessionId,o.type!=="text.delta"||a),(a||o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),o.type==="session.done"&&this.emitGeneratedFileNoticesForCompletedTurn(e),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}b.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),I.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o});let a=o!==0&&o!==null;_.increment("driver.exit",{agent:n,abnormal:a?"true":"false"});let l=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&xd(e)));if(this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.clearStallWarning(e),l||(e.pendingApproval=void 0),a){let u=hS(o,e.lastUserMessage);e.interruptReason=u,this.broadcast(e.sessionId,{type:"session.interrupted_notice",sessionId:e.sessionId,reason:u}),this.pushSender(dS,this.buildPushBody(`${e.title||e.sessionId}: ${u.lastPrompt??""}`.trim()),{sessionId:e.sessionId,agent:e.agent,eventType:"agent_crashed"})}this.updateGauges(),this.touchSession(e.sessionId),this.store.upsert(J(e)),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.forget(i),this.store.addAlias(i,n),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(J(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,e.lastTurnStartedAt=Date.now(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}emitGeneratedFileNoticesForCompletedTurn(e){let n=e.lastTurnStartedAt;e.lastTurnStartedAt=void 0,!(e.agent!=="codex"||!n)&&fd(e.sessionId,e.agent,e.cwd,n).then(r=>{for(let s of r)this.broadcast(e.sessionId,{type:"tool.result",sessionId:e.sessionId,toolCallId:`generated-file-${Date.now()}`,output:s})}).catch(r=>{b.warn({sessionId:e.sessionId,error:String(r)},"failed to read generated-file notices")})}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=_.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof bn&&s&&n.setModel(s),e!=="claude"||!(n instanceof _n))return;let i=r??(0,io.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,i),i}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=vn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&gS(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),vn;if(r.approvalMode==="autoApprove")return kd(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return vn;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=`${Ii}${l.trim()||(0,io.randomUUID)()}`,c=r.pendingClaudeHookApprovals.get(u);if(c)return c.promise;let d=`Claude requested permissions to use ${i}.`,p,h=new Promise(g=>{p=g});return r.pendingClaudeHookApprovals.set(u,{requestId:u,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(u),p(g)}}),r.pendingApproval={requestId:u,toolName:i,input:a,description:d},I.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:u,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(e=this.resolveSessionRef(e).resolvedSessionId,this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.model,u=r?.pendingApproval,c=r?.title??"",d=r?.createdAt??s,p=r?.lastActivityAt??s,h=r?.lastUsage,g=xe(r?.acceptedClientMessageIds),f=xe(r?.interruptedClientMessageIds),m=r?.isResponding,y=r?.interruptReason,A=r?.stallWarning,T=r?"memory":"client",w=this.store.find(e);if(w)i=w.agent,o=w.cwd||o,a=w.approvalMode??a,l=w.model??l,u=w.pendingApproval??u,c=w.title||c,d=w.createdAt||d,p=w.lastActivityAt||p,h=w.lastUsage??h,g=xe(w.acceptedClientMessageIds,g),f=xe(w.interruptedClientMessageIds,f),y=y??w.interruptReason,A=A??w.stallWarning,T="record";else if(!r){let P=(await Rn(n??i)).find(G=>G.sessionId===e);P&&(i=P.agent,o=P.cwd||o,c=P.title??c,d=P.createdAt,p=P.lastActivityAt,m=P.runtime.isResponding??m,T="scanner")}if(!i&&n&&(i=n,T=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,model:l,pendingApproval:u,title:c,createdAt:d,lastActivityAt:p,lastUsage:h,acceptedClientMessageIds:g,interruptedClientMessageIds:f,source:T,managed:r?.managed??w?.managed,isResponding:m||void 0,...y?{interruptReason:y}:{},...A?{stallWarning:A}:{}}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Cd(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Cd(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(J(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=wd?n:`${n.slice(0,Math.max(1,wd-3)).trimEnd()}...`:aS}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}currentWatchdogTime(){return this.advanceWatchdogClock(Date.now(),"activity")}getRespondingLivenessHint(e){return e.driver?.getRespondingLivenessHint?.()??"unknown"}clearStallWarning(e){return!e.stallWarning&&!e.stallWarningAt?!1:(e.stallWarning=void 0,e.stallWarningAt=void 0,this.updateGauges(),!0)}advanceWatchdogClock(e,n){let r=Math.max(0,e-this.lastWatchdogWallClockMs);return this.lastWatchdogWallClockMs=e,r<=0?this.watchdogNowMs:r>Id?(n==="sweep"&&b.warn({elapsedWallMs:r,toleratedGapMs:Id},"watchdog gap detected; discounting paused wall-clock time"),this.watchdogNowMs):(this.watchdogNowMs+=r,this.watchdogNowMs)}touchSession(e,n=!0){let r=Date.now(),s=new Date(r).toISOString(),i=this.advanceWatchdogClock(r,"activity"),o=this.sessions.get(e);if(o){o.lastActivityAt=s,o.lastActivityTs=i,n&&this.store.upsert(J(o));return}let a=this.store.find(e);a&&this.store.upsert({...a,lastActivityAt:s})}updateGauges(){let e=0,n=0;for(let r of this.sessions.values())r.active&&e++,r.stallWarning&&n++;_.gauge("session.active",e),_.gauge("session.stall_warning_active",n)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,model:n.model,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,lastUsage:n.lastUsage,...n.pendingApproval||n.stallWarning?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed,...n.interruptReason?{interruptReason:n.interruptReason}:{},...n.stallWarning?{stallWarning:n.stallWarning}:{}});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}resolveSessionRef(e){let n=this.store.resolveSessionId(e);return{requestedSessionId:e,resolvedSessionId:n,remapped:n!==e}}buildResolvedSessionResponseData(e,n){let r=n?{...n}:{};return e.remapped&&(r.sessionId=e.resolvedSessionId,r.oldSessionId=e.requestedSessionId),Object.keys(r).length>0?r:void 0}buildSessionResponseData(e,n,r){let s=r?{...r}:{};return n&&n!==e.requestedSessionId&&(s.sessionId=n,s.oldSessionId=e.requestedSessionId),Object.keys(s).length>0?s: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 Rn(e,n)}async handle(e,n){switch(b.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.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);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){b.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Fr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Vr(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Rd.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let u=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(u)return b.info({sessionId:u.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,u.sessionId,r,s,i);b.info("continue mode: no previous sessions found, creating new")}catch(l){b.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),u=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;b.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let f={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(g,f),this.registerClaudeHookSession(f),this.store.upsert(J(f)),this.updateGauges(),Gr(),Pr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(f,e);return}let c=_.startTimer("driver.spawn"),d=await l.start(s,void 0,i),p=c();b.info({sessionId:d,agent:r,spawnMs:p},"session created"),_.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let h={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:u,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(J(h)),this.updateGauges(),Gr(),Pr(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){b.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){let a=this.resolveSessionRef(r);if(r=a.resolvedSessionId,this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(r);if(l&&l.active){l.clients.add(e),this.touchSession(l.sessionId),this.noteInventoryChanged("session_updated");let h=await En(r,s,l.cwd),g=this.annotateHistoryMessages(h,l.acceptedClientMessageIds,l.interruptedClientMessageIds),f=this.currentPartialReplyText(l);if(h.length>0||f||l.approvalMode||l.pendingApproval||l.stallWarning){let m={type:"session.history",sessionId:r,messages:g,...Kr(l.acceptedClientMessageIds),isResponding:l.isResponding||void 0,partialReplyText:f,approvalMode:l.approvalMode,pendingApproval:l.pendingApproval,stallWarning:l.stallWarning};e.readyState===1&&e.send(JSON.stringify(m))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(a,{sessionId:r}));return}let u=this.store.find(r),c=i||u?.cwd||"",d=o??u?.approvalMode,p=u?.title??"Resumed session";try{let h=_.startTimer("driver.spawn"),g=this.createDriver(s),f=this.configureDriverBeforeStart(s,g),m=this.canResumeDriverSession(s,r),y=await g.start(c,m?r:void 0,d),A=h();b.info({sessionId:y,agent:s,spawnMs:A},"session resumed"),_.increment("session.resume",{agent:s}),I.emit("session.resume",{sessionId:y,agent:s,cwd:c});let T={sessionId:y,agent:s,cwd:c,approvalMode:d,model:u?.model,driver:g,clients:new Set([e]),title:p,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,bufferedPrompts:[],startupToken:0,managed:u?.managed,pendingApproval:u?.pendingApproval,stallWarning:u?.stallWarning,claudeHookSecret:f,pendingClaudeHookApprovals:new Map};this.sessions.set(y,T),this.rememberSessionAlias(r,y),this.registerClaudeHookSession(T),this.store.upsert(J(T)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(T,s," (resumed)",e),this.restoreDriverPendingApproval(g,T.pendingApproval);let C=await En(m?r:y,s,c),P=this.annotateHistoryMessages(C,T.acceptedClientMessageIds,T.interruptedClientMessageIds);if(C.length>0||T.pendingApproval||T.stallWarning){b.info({sessionId:r,historyCount:C.length},"sending history messages");let G={type:"session.history",sessionId:y,messages:P,...Kr(T.acceptedClientMessageIds),approvalMode:d,pendingApproval:T.pendingApproval,stallWarning:T.stallWarning};e.readyState===1&&e.send(JSON.stringify(G))}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>Ft&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Ft))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Ft&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Ft))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let 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];s.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)}async sendMessage(e,n,r,s,i,o,a,l){let u=this.resolveSessionRef(r);if(r=u.resolvedSessionId,this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),_.increment("session.reconnect",{agent:f.agent,source:f.source}),I.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let m=this.createDriver(f.agent),y=this.configureDriverBeforeStart(f.agent,m,c?.claudeHookSecret),A=this.canResumeDriverSession(f.agent,r),T=await m.start(f.cwd,A?r:void 0,f.approvalMode);this.restoreDriverPendingApproval(m,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.model=f.model,c.pendingApproval=f.pendingApproval,c.driver=m,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastUsage=f.lastUsage,c.lastActivityTs=this.currentWatchdogTime(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=xe(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.interruptedClientMessageIds=xe(c.interruptedClientMessageIds,f.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=y??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map,T&&T!==c.sessionId&&this.remapSessionId(c,T)):(c={sessionId:T,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,model:f.model,driver:m,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,lastUsage:f.lastUsage,active:!0,lastActivityTs:this.currentWatchdogTime(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,interruptedClientMessageIds:f.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:y,pendingClaudeHookApprovals:new Map,interruptReason:f.interruptReason},this.sessions.set(T,c),this.rememberSessionAlias(r,T)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(J(c)),this.updateGauges(),this.noteInventoryChanged("session_updated"),r=c.sessionId}catch(m){this.reply(e,n,!1,void 0,`Failed to reconnect: ${m}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,this.buildResolvedSessionResponseData(u,{sessionId:r,clientMessageId:o,duplicate:!0}));return}b.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),I.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),Td(c),c.interruptReason&&(c.interruptReason=void 0,this.store.upsert(J(c)),this.noteInventoryChanged("session_updated"));let d=this.clearStallWarning(c);if(Pt(c.title)){let f=Pi(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(J(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId),d&&this.noteInventoryChanged("session_updated");let p=new Set([".png",".jpg",".jpeg",".gif",".webp",".heic",".heif",".bmp",".svg"]),h=a?.length?a.map(f=>{let m=f.lastIndexOf("."),y=m>=0?f.slice(m).toLowerCase():"";return`[Attached ${p.has(y)?"image":"file"}: ${f}]`}).join(`
107
+ `):"",g=h?s?`${s}
108
108
 
109
- ${f}`:f:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(g),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}));return}if(c.isResponding){c.bufferedPrompts.push(g),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}));return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(g,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}))}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let u=this.getDeletedSessionIds(),c;try{c=await Or({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:u})}catch(g){b.warn({error:String(g)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}c={...c,inventoryVersion:this.inventoryVersion};let d;if(o&&!u.has(o)){let g=o;o=this.resolveSessionRef(o).resolvedSessionId;let h=a??c.sessions.find(y=>y.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let m=await this.resolveReconnectSession(o,h,p);if(m){let y=await Rn(o,m.agent,p?.cwd??m.cwd),w=this.annotateHistoryMessages(y,p?.acceptedClientMessageIds??m.acceptedClientMessageIds,p?.interruptedClientMessageIds??m.interruptedClientMessageIds),A=p?{}:await Zi(o,m.agent,m.cwd),x=!p&&!!A.isResponding,T=x?await this.externalProcessPresenceCheck(o):!1,W=x&&!T?{}:A,z=p?.interruptReason??m.interruptReason;d={sessionId:o,agent:m.agent,messages:w,...Vr(p?.acceptedClientMessageIds??m.acceptedClientMessageIds),isResponding:p?.isResponding??W.isResponding??(x&&!T?void 0:m.isResponding),...T?{externallyResponding:!0}:{},partialReplyText:p?this.currentPartialReplyText(p):W.partialReplyText,approvalMode:p?.approvalMode??m.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{},...z?{interruptReason:z}:{}},g!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:g})}}let f=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,inventoryVersion:c.inventoryVersion,...d?{activeSession:d}:{},...f.length>0?{pendingApprovals:f}:{}}})}catch(u){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(u)}`)}}async approve(e,n,r,s,i){let o=this.resolveSessionRef(r);r=o.resolvedSessionId;let a=this.sessions.get(r),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(s);if(a&&u){a.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(xd(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:r}));return}let c=a?.syntheticApprovalRetries[s];if(a&&c&&wr(s)){delete a.syntheticApprovalRetries[s],a.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:r})),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(I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!a.driver.respondApproval(s,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:r}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(X(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.resolveSessionRef(r);r=i.resolvedSessionId;let o=this.sessions.get(r);if(!o){let l=this.store.find(r);l?(s===null?delete l.approvalMode:l.approvalMode=s,this.store.upsert(l),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:l.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:s,sessionId:r}));return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=s,this.store.upsert(X(o)),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:o.agent,oldMode:a,newMode:s},"approval mode changed"),o.driver&&o.driver.setApprovalMode(s),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:s,sessionId:r}))}interrupt(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("session.interrupt",{sessionId:r,agent:i.agent}),!i.driver){(i.isResponding||i.bufferedPrompts.length>0)&&(b.info({sessionId:r,agent:i.agent},"interrupting driverless session with stale responding state"),i.bufferedPrompts=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,i.pendingApproval=void 0,this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}));return}if(i.startupInProgress){let o=i.isResponding||i.bufferedPrompts.length>0;b.info({sessionId:r,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session"),i.bufferedPrompts=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,i.pendingApproval=void 0,o&&this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}clearInterrupt(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r),o=this.store.find(r);if(!i&&!o?.interruptReason){this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}));return}let a=!1;i?.interruptReason&&(i.interruptReason=void 0,a=!0),i?this.store.upsert(X(i)):o?.interruptReason&&(this.store.upsert({...o,interruptReason:void 0}),a=!0),a&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}stopSession(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:i.agent},"stopping session"),I.emit("session.stop",{sessionId:r,agent:i.agent}),wd(i);let o=i.isResponding||i.bufferedPrompts.length>0||i.startupInProgress;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",i.pendingApproval=void 0,i.startupInProgress=!1,i.bufferedPrompts=[],i.startupToken+=1,o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}deleteSession(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);i&&(b.info({sessionId:r,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.bufferedPrompts=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(r)),I.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Ur(),kr(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}async sendHistory(e,n,r,s){let i=this.resolveSessionRef(r);r=i.resolvedSessionId;let o=this.sessions.get(r),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(r)){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(r)?.cwd??"",u=this.store.find(r),c=await Rn(r,s,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),f=a||o?{}:await Zi(r,s,l),g=!a&&!!f.isResponding,h=g?await this.externalProcessPresenceCheck(r):!1,p=h?!0:void 0,m=g&&!h?{}:f,y=a?.isResponding??m.isResponding,w=a?this.currentPartialReplyText(a):m.partialReplyText;b.info({sessionId:r,historyCount:c.length,isResponding:y,externallyResponding:p,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let A={type:"session.history",sessionId:r,messages:d,...Vr(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:p,partialReplyText:w,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(A));let x=o?.interruptReason??u?.interruptReason;if(x&&e.readyState===1){let T={type:"session.interrupted_notice",sessionId:r,reason:x};e.send(JSON.stringify(T))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:r}))}async listSessions(e,n,r,s,i,o=50,a,l){try{let u=await Or({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...u,inventoryVersion:this.inventoryVersion})}catch(u){this.reply(e,n,!1,void 0,String(u))}}createDriver(e){switch(e){case"claude":return new Sn;case"codex":return new _n;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(s),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(u,c,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function so(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var kd=require("child_process");function oS(t,e){return(0,kd.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function aS(t){let e=t.split(`
110
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Rd(t,e=oS){let n;try{n=aS(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var Ht=require("fs"),io=require("os"),Pd=require("crypto"),Md=require("path");function Ld(t){return(0,Pd.randomBytes)(t).toString("base64url")}function lS(){return`d_${Ld(12)}`}function cS(){return(0,io.hostname)()}function uS(){let t=(0,io.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function dS(t){return{daemonId:lS(),daemonSecret:Ld(32),displayName:cS(),canonicalHost:uS(),port:t,createdAt:new Date().toISOString()}}function Ed(t,e){(0,Ht.mkdirSync)((0,Md.dirname)(e),{recursive:!0}),(0,Ht.writeFileSync)(e,JSON.stringify(t,null,2)+`
111
- `,"utf8")}function Nd(t,e=Pc){try{let r=(0,Ht.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,Ed(i,e)),i}}catch{}let n=dS(t);return Ed(n,e),n}var Ut=require("crypto"),qt=require("fs"),Bd=require("path");function oo(t){return(0,Ut.randomBytes)(t).toString("base64url")}function ao(t){return(0,Ut.createHash)("sha256").update(t).digest("hex")}function Od(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Ut.timingSafeEqual)(n,r)}function fS(t){try{let e=(0,qt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function Mn(t,e){(0,qt.mkdirSync)((0,Bd.dirname)(t),{recursive:!0}),(0,qt.writeFileSync)(t,JSON.stringify(e,null,2)+`
112
- `,"utf8")}var Jr=class{constructor(e=Mc){this.pairingsPath=e;this.records=fS(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${oo(8)}`,s=oo(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=oo(32),i={deviceId:e,deviceName:n,tokenHash:ao(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Mn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=ao(n);return Od(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),Mn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=ao(e),s=this.records.find(i=>!i.revokedAt&&Od(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),Mn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Mn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Mn(this.pairingsPath,this.records)}};function ot(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function pS(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function lo(t,e){return pS(t)??e}function Kr(t,e){return!!(t&&e&&t===e)}function co(t,e,n,r=!0){return t?Kr(t,e)?!0:!!n(t,r):!1}var Hd=require("child_process"),Ud=require("fs");function Xr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function uo(t){if(!Xr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function hS(t){if(!Xr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function gS(t){if(!Xr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function mS(t){if(!Xr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function Qr(t){return!!t&&!hS(t)&&!gS(t)}function de(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function fo(t){return de(t.replace(/^https?:\/\//,""))??t}function yS(t,e){return(t??[]).map(n=>de(n)).filter(n=>!!n).filter(n=>Qr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function vS(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 SS(t){let e=fo(t);return uo(e)||e.endsWith(".ts.net")}function _S(t){let e=fo(t);return mS(e)||e.endsWith(".local")}function bS(t){return fo(t).endsWith(".trycloudflare.com")}function Dd(t,e){return SS(t)?"tailscale":_S(t)?"local_network":e?"configured_host":"fallback"}function qd(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}:${r.secure===!0?"secure":"plain"}`;e.has(s)||(e.add(s),n.push(r))}return n}function wS(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function IS(t){try{let e=new URL(t),n=de(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=bS(n);return{kind:"relay",host:n,port:s,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function AS(t,e,n){let r=de(t)||"localhost",s=yS(e,r);return qd([{kind:"direct",host:r,port:n,source:Dd(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:Dd(i,!1),stability:"stable"}))])}function Wd(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function xS(t){let e=[],n=[];for(let[r,s]of Object.entries(t))if(s&&vS(r))for(let i of s)i.internal||i.family!=="IPv4"||Qr(i.address)&&(uo(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Fd(t){let e=JSON.parse(t),n=de(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>de(o)).filter(o=>!!o).filter(o=>uo(o)&&Qr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Gd(t=Hd.execFileSync,e=Ud.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(r=>typeof r=="string"&&r.length>0).filter(r=>e(r));for(let r of n)try{let s=t("tailscale",["--socket",r,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Fd(s)}catch{}try{let r=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Fd(r)}catch{return{fallbackHosts:[]}}}function jd(t){let e=AS(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?IS(t.relayUrl):null,r=qd([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:de(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:wS(r),port:s.port,connections:r}}function $d(t){let e=de(t.canonicalHost),n=de(t.configuredCanonicalHost)||de(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...xS(t.interfaces)].map(s=>de(s)).filter(s=>!!s).filter(s=>Qr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function zd(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 G=L.child({module:"daemon"}),Ln=L.child({module:"ws"});function CS(){try{let t=JSON.parse(require("fs").readFileSync(Nc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var H=Nd(S.port),Z=new Yr((t,e,n)=>zr(t,e,{daemonId:H.daemonId,canonicalHost:Nn().canonicalHost,...n??{}})),pe=new Jr,es=new Set,Fe=new WeakMap,Vd=!1,Xd=Date.now(),Wt=null,Zr=null,TS=1e3;function kS(){let t=Gd();return $d({canonicalHost:H.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Wd(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Kd.networkInterfaces)()})}function Nn(){let t=Date.now();if(Zr&&Zr.expiresAt>t)return Zr.value;let e=kS(),n=jd({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:H.port,relayUrl:S.relayUrl});return Zr={value:n,expiresAt:t+TS},n}function RS(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 ES(t){let e=JSON.stringify(RS(t));await(0,oe.mkdir)(we,{recursive:!0}),await go.default.toFile(gi,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await go.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});Ct(`
109
+ ${h}`:h:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(g),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}));return}if(c.isResponding){c.bufferedPrompts.push(g),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}));return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.lastTurnStartedAt=Date.now(),this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(g,c.model),this.reply(e,n,!0,this.buildSessionResponseData(u,r,o?{sessionId:r,clientMessageId:o}:{sessionId:r}))}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let u=this.getDeletedSessionIds(),c;try{c=await Fr({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:u})}catch(h){b.warn({error:String(h)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}c={...c,inventoryVersion:this.inventoryVersion};let d;if(o&&!u.has(o)){let h=o;o=this.resolveSessionRef(o).resolvedSessionId;let g=a??c.sessions.find(y=>y.sessionId===o)?.agent,f=this.sessions.get(o);f&&f.clients.add(e);let m=await this.resolveReconnectSession(o,g,f);if(m){let y=await En(o,m.agent,f?.cwd??m.cwd),A=this.annotateHistoryMessages(y,f?.acceptedClientMessageIds??m.acceptedClientMessageIds,f?.interruptedClientMessageIds??m.interruptedClientMessageIds),T=f?{}:await to(o,m.agent,m.cwd),w=!f&&!!T.isResponding,C=w?await this.externalProcessPresenceCheck(o):!1,P=w&&!C?{}:T,G=f?.interruptReason??m.interruptReason,ye=f?.stallWarning??m.stallWarning;d={sessionId:o,agent:m.agent,messages:A,...Kr(f?.acceptedClientMessageIds??m.acceptedClientMessageIds),isResponding:f?.isResponding??P.isResponding??(w&&!C?void 0:m.isResponding),...C?{externallyResponding:!0}:{},partialReplyText:f?this.currentPartialReplyText(f):P.partialReplyText,approvalMode:f?.approvalMode??m.approvalMode,...f?.pendingApproval?{pendingApproval:f.pendingApproval}:{},...G?{interruptReason:G}:{},...ye?{stallWarning:ye}:{}},h!==o&&this.reply(e,`id_update_${Date.now()}`,!0,{sessionId:o,oldSessionId:h})}}let p=this.collectReconnectPendingApprovals();_.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,inventoryVersion:c.inventoryVersion,...d?{activeSession:d}:{},...p.length>0?{pendingApprovals:p}:{}}})}catch(u){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(u)}`)}}async approve(e,n,r,s,i){let o=this.resolveSessionRef(r);r=o.resolvedSessionId;let a=this.sessions.get(r),l=a?.pendingApproval,u=a?.pendingClaudeHookApprovals.get(s);if(a&&u){a.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),u.resolve(kd(i)),a.isResponding=!0,this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:r}));return}let c=a?.syntheticApprovalRetries[s];if(a&&c&&Tr(s)){delete a.syntheticApprovalRetries[s],a.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(o,{sessionId:r})),i&&await this.retrySyntheticClaudeApproval(a,c);return}if(a&&!a.driver&&l)try{await this.reviveSessionForApproval(a)}catch(p){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(p)}`);return}if(!a?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!a.driver.respondApproval(s,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:r}))}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.lastTurnStartedAt=Date.now(),e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(J(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.resolveSessionRef(r);r=i.resolvedSessionId;let o=this.sessions.get(r);if(!o){let l=this.store.find(r);l?(s===null?delete l.approvalMode:l.approvalMode=s,this.store.upsert(l),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:l.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:s,sessionId:r}));return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let a=o.approvalMode;o.approvalMode=s,this.store.upsert(J(o)),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:o.agent,oldMode:a,newMode:s},"approval mode changed"),o.driver&&o.driver.setApprovalMode(s),this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{approvalMode:s,sessionId:r}))}interrupt(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("session.interrupt",{sessionId:r,agent:i.agent}),!i.driver){(i.isResponding||i.bufferedPrompts.length>0)&&(b.info({sessionId:r,agent:i.agent},"interrupting driverless session with stale responding state"),i.bufferedPrompts=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,i.pendingApproval=void 0,this.clearStallWarning(i),this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId})),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}));return}if(i.startupInProgress){let o=i.isResponding||i.bufferedPrompts.length>0;b.info({sessionId:r,agent:i.agent,hadBufferedTurn:o},"interrupting pending startup session"),i.bufferedPrompts=[],i.isResponding=!1,i.currentReplyText="",i.lastUserMessage=void 0,i.pendingApproval=void 0,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r})),o&&this.broadcast(i.sessionId,{type:"session.interrupted",sessionId:i.sessionId});return}i.driver.interrupt(),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}clearInterrupt(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r),o=this.store.find(r);if(!i&&!o?.interruptReason){this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}));return}let a=!1;i?.interruptReason&&(i.interruptReason=void 0,a=!0),i?this.store.upsert(J(i)):o?.interruptReason&&(this.store.upsert({...o,interruptReason:void 0}),a=!0),a&&this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}stopSession(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:i.agent},"stopping session"),I.emit("session.stop",{sessionId:r,agent:i.agent}),Td(i);let o=i.isResponding||i.bufferedPrompts.length>0||i.startupInProgress;this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,i.isResponding=!1,i.currentReplyText="",i.pendingApproval=void 0,i.startupInProgress=!1,i.bufferedPrompts=[],i.startupToken+=1,this.clearStallWarning(i),o&&this.markLatestAcceptedClientMessageInterrupted(i),this.updateGauges(),this.touchSession(i.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}deleteSession(e,n,r){let s=this.resolveSessionRef(r);r=s.resolvedSessionId;let i=this.sessions.get(r);i&&(b.info({sessionId:r,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.startupInProgress=!1,i.bufferedPrompts=[],i.startupToken+=1,this.unregisterClaudeHookSession(i),this.sessions.delete(r)),I.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Gr(),Pr(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0,this.buildResolvedSessionResponseData(s,{sessionId:r}))}async sendHistory(e,n,r,s){let i=this.resolveSessionRef(r);r=i.resolvedSessionId;let o=this.sessions.get(r),a=o?.active?o:void 0;if(!o&&this.isDeletedSession(r)){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(r)?.cwd??"",u=this.store.find(r),c=await En(r,s,l),d=this.annotateHistoryMessages(c,o?.acceptedClientMessageIds??u?.acceptedClientMessageIds,o?.interruptedClientMessageIds??u?.interruptedClientMessageIds),p=a||o?{}:await to(r,s,l),h=!a&&!!p.isResponding,g=h?await this.externalProcessPresenceCheck(r):!1,f=g?!0:void 0,m=h&&!g?{}:p,y=a?.isResponding??m.isResponding,A=a?this.currentPartialReplyText(a):m.partialReplyText;b.info({sessionId:r,historyCount:c.length,isResponding:y,externallyResponding:f,approvalMode:o?.approvalMode??u?.approvalMode},"sending history");let T={type:"session.history",sessionId:r,messages:d,...Kr(o?.acceptedClientMessageIds??u?.acceptedClientMessageIds),isResponding:y,externallyResponding:f,partialReplyText:A,approvalMode:o?.approvalMode??u?.approvalMode,pendingApproval:o?.pendingApproval??u?.pendingApproval,stallWarning:o?.stallWarning??u?.stallWarning};e.readyState===1&&e.send(JSON.stringify(T));let w=o?.interruptReason??u?.interruptReason;if(w&&e.readyState===1){let C={type:"session.interrupted_notice",sessionId:r,reason:w};e.send(JSON.stringify(C))}this.reply(e,n,!0,this.buildResolvedSessionResponseData(i,{sessionId:r}))}async listSessions(e,n,r,s,i,o=50,a,l){try{let u=await Fr({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...u,inventoryVersion:this.inventoryVersion})}catch(u){this.reply(e,n,!1,void 0,String(u))}}createDriver(e){switch(e){case"claude":return new _n;case"codex":return new bn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let u of i)u.readyState===1?(u.send(s),a++):l++;if(l>0&&_.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let u=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(u,c,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function oo(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Pd=require("child_process");function mS(t,e){return(0,Pd.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function yS(t){let e=t.split(`
110
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Md(t,e=mS){let n;try{n=yS(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var Ut=require("fs"),ao=require("os"),Nd=require("crypto"),Od=require("path");function Bd(t){return(0,Nd.randomBytes)(t).toString("base64url")}function vS(){return`d_${Bd(12)}`}function SS(){return(0,ao.hostname)()}function _S(){let t=(0,ao.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function bS(t){return{daemonId:vS(),daemonSecret:Bd(32),displayName:SS(),canonicalHost:_S(),port:t,createdAt:new Date().toISOString()}}function Ld(t,e){(0,Ut.mkdirSync)((0,Od.dirname)(e),{recursive:!0}),(0,Ut.writeFileSync)(e,JSON.stringify(t,null,2)+`
111
+ `,"utf8")}function Dd(t,e=Lc){try{let r=(0,Ut.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,Ld(i,e)),i}}catch{}let n=bS(t);return Ld(n,e),n}var Wt=require("crypto"),qt=require("fs"),Hd=require("path");function lo(t){return(0,Wt.randomBytes)(t).toString("base64url")}function co(t){return(0,Wt.createHash)("sha256").update(t).digest("hex")}function Fd(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Wt.timingSafeEqual)(n,r)}function wS(t){try{let e=(0,qt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function Ln(t,e){(0,qt.mkdirSync)((0,Hd.dirname)(t),{recursive:!0}),(0,qt.writeFileSync)(t,JSON.stringify(e,null,2)+`
112
+ `,"utf8")}var Qr=class{constructor(e=Nc){this.pairingsPath=e;this.records=wS(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${lo(8)}`,s=lo(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=lo(32),i={deviceId:e,deviceName:n,tokenHash:co(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Ln(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=co(n);return Fd(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),Ln(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=co(e),s=this.records.find(i=>!i.revokedAt&&Fd(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),Ln(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Ln(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Ln(this.pairingsPath,this.records)}};function at(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function IS(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function uo(t,e){return IS(t)??e}function Zr(t,e){return!!(t&&e&&t===e)}function fo(t,e,n,r=!0){return t?Zr(t,e)?!0:!!n(t,r):!1}var qd=require("child_process"),Gd=require("fs");function es(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function po(t){if(!es(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function AS(t){if(!es(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function TS(t){if(!es(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function xS(t){if(!es(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function ts(t){return!!t&&!AS(t)&&!TS(t)}function de(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function ho(t){return de(t.replace(/^https?:\/\//,""))??t}function CS(t,e){return(t??[]).map(n=>de(n)).filter(n=>!!n).filter(n=>ts(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function kS(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 RS(t){let e=ho(t);return po(e)||e.endsWith(".ts.net")}function ES(t){let e=ho(t);return xS(e)||e.endsWith(".local")}function PS(t){return ho(t).endsWith(".trycloudflare.com")}function Ud(t,e){return RS(t)?"tailscale":ES(t)?"local_network":e?"configured_host":"fallback"}function jd(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}:${r.secure===!0?"secure":"plain"}`;e.has(s)||(e.add(s),n.push(r))}return n}function MS(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function LS(t){try{let e=new URL(t),n=de(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=PS(n);return{kind:"relay",host:n,port:s,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function NS(t,e,n){let r=de(t)||"localhost",s=CS(e,r);return jd([{kind:"direct",host:r,port:n,source:Ud(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:Ud(i,!1),stability:"stable"}))])}function $d(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function OS(t){let e=[],n=[];for(let[r,s]of Object.entries(t))if(s&&kS(r))for(let i of s)i.internal||i.family!=="IPv4"||ts(i.address)&&(po(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Wd(t){let e=JSON.parse(t),n=de(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>de(o)).filter(o=>!!o).filter(o=>po(o)&&ts(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function zd(t=qd.execFileSync,e=Gd.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(r=>typeof r=="string"&&r.length>0).filter(r=>e(r));for(let r of n)try{let s=t("tailscale",["--socket",r,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Wd(s)}catch{}try{let r=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Wd(r)}catch{return{fallbackHosts:[]}}}function Vd(t){let e=NS(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?LS(t.relayUrl):null,r=jd([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:de(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:MS(r),port:s.port,connections:r}}function Yd(t){let e=de(t.canonicalHost),n=de(t.configuredCanonicalHost)||de(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...OS(t.interfaces)].map(s=>de(s)).filter(s=>!!s).filter(s=>ts(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Jd(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var j=N.child({module:"daemon"}),Nn=N.child({module:"ws"});function BS(){try{let t=JSON.parse(require("fs").readFileSync(Bc,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var U=Dd(S.port),Z=new Xr((t,e,n)=>Jr(t,e,{daemonId:U.daemonId,canonicalHost:On().canonicalHost,...n??{}})),pe=new Qr,rs=new Set,He=new WeakMap,Kd=!1,ef=Date.now(),Gt=null,ns=null,DS=1e3;function FS(){let t=zd();return Yd({canonicalHost:U.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:$d(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Zd.networkInterfaces)()})}function On(){let t=Date.now();if(ns&&ns.expiresAt>t)return ns.value;let e=FS(),n=Vd({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:U.port,relayUrl:S.relayUrl});return ns={value:n,expiresAt:t+DS},n}function HS(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 US(t){let e=JSON.stringify(HS(t));await(0,oe.mkdir)(Ie,{recursive:!0}),await yo.default.toFile(vi,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await yo.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});xt(`
113
113
  Scan this QR code with Vibelet app:
114
114
 
115
115
  ${n}
116
- `),Ct(`If Vibelet app can't scan the terminal QR, open this PNG instead:
117
- ${gi}
118
- `)}async function po(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function D(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function PS(t){let e=(0,Gt.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 Qd(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function MS(t,e){if(ot(t.socket.remoteAddress))return!0;let n=lo(t.headers.authorization,e.searchParams.get("token"));return co(n,S.legacyToken,(r,s)=>pe.validateAnyPairToken(r,s),!1)}function LS(){let t=pe.openWindow(Qd(),S.pairReusable),e=Nn();return{type:"vibelet-pair",daemonId:H.daemonId,displayName:H.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function NS(t,e){let n=eo(t,e),r=await(0,oe.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,oe.stat)((0,Gt.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var On=(0,Yd.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=Nn(),i=CS(),o={status:"ok",version:Et,...i?{latestVersion:i}:{}};if(!MS(t,n)){D(e,200,o);return}let a={...o,status:"ok",daemonId:H.daemonId,displayName:H.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Xd)/1e3),activeSessions:Z.getActiveSessionCount(),pairedDevices:pe.pairedCount(),wsClients:fe.clients.size,drivers:Z.getDriverCounts(),sessionInventory:ju(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),D(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!ot(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,LS());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!ot(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}pe.reset(),D(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!ot(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,{status:"stopping"}),setTimeout(()=>at("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!ot(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await po(t),i=t.headers[mn],o=Array.isArray(i)?i[0]:i;Z.handleClaudeSessionStartHook(o,s),D(e,200,{ok:!0})}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!ot(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await po(t),i=t.headers[mn],o=Array.isArray(i)?i[0]:i,a=await Z.handleClaudePermissionHook(o,s);D(e,200,a)}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await po(t);if(s.daemonId!==H.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){D(e,400,{error:"invalid_pair_request"});return}if(!pe.consumeWindow(s.pairNonce)){D(e,401,{error:"pair_window_expired"});return}let o=pe.issuePairToken(s.deviceId,s.deviceName),a=Nn();D(e,200,{daemonId:H.daemonId,displayName:H.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){D(e,400,{error:String(s)})}return}let r=lo(t.headers.authorization,n.searchParams.get("token"));if(!co(r,S.legacyToken,(s,i)=>pe.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","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,Gt.extname)(o).toLowerCase()||s[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let f of t){let g=Buffer.isBuffer(f)?f:Buffer.from(f);if(d+=g.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(g)}try{await(0,oe.mkdir)(hi,{recursive:!0});let f=`${Date.now()}_${(0,Jd.randomBytes)(8).toString("hex")}${l}`,g=(0,Gt.join)(hi,f);await(0,oe.writeFile)(g,Buffer.concat(c)),G.info({filePath:g,size:d,contentType:i,providedName:o||void 0},"file uploaded"),D(e,200,{path:g})}catch(f){G.error({error:String(f)},"upload failed"),D(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=eo(s,i);if(!(await(0,oe.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=PS(o),u=await(0,oe.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${Et}`)}),fe=new Is.default({server:On});On.on("connection",t=>{es.add(t),t.on("close",()=>{es.delete(t)})});fe.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Kr(r,S.legacyToken))Fe.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),Z.addGlobalClient(t),Z.prewarmCaches();else if(r){let s=pe.validateAnyPairToken(r);if(s)Fe.set(t,{authMode:"query_token",deviceId:s.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),Z.addGlobalClient(t),Z.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}Ln.info({clients:fe.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",fe.clients.size),I.emit("ws.connect",{clients:fe.clients.size,authMode:Fe.get(t)?.authMode??"pending",deviceId:Fe.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(zd(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Fe.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Kr(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===H.daemonId&&pe.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===H.daemonId){let l=pe.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){Fe.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),_.increment("ws.auth.success",{mode:"auth_hello"}),Z.addGlobalClient(t),Z.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:H.daemonId,displayName:H.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)I.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?G.error:a.level==="warn"?G.warn:G.info).call(G,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await NS(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=Fe.get(t);so(i,{deviceId:a?.deviceId,registerToken:to,unregisterToken:no,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Fe.get(t);so(i,{deviceId:a?.deviceId,registerToken:to,unregisterToken:no,respond:l=>t.send(JSON.stringify(l))});return}await Z.handle(t,o)}catch(i){Ln.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{Ln.info({clients:fe.clients.size,code:s},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(s)}),_.gauge("ws.clients",fe.clients.size),I.emit("ws.disconnect",{clients:fe.clients.size,code:s}),Z.removeClient(t)}),t.on("error",s=>{Ln.error({error:s.message},"websocket error")})});function ho(){for(let t of es)try{t.destroy()}catch{}es.clear()}function Zd(){let t=jc({auditPath:xt,stdoutLogPath:fr,stderrLogPath:pr,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&G.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 OS(){Wt||(Wt=setInterval(Zd,S.storageHousekeepingIntervalMs),Wt.unref())}function BS(){Wt&&(clearInterval(Wt),Wt=null)}function at(t,e=0){if(!Vd){Vd=!0,G.info({reason:t,exitCode:e},"shutting down"),I.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Xd)/1e3)}),_.stopPeriodicLog(),BS(),Lt.stop().catch(()=>{}),Z.shutdown();for(let n of fe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}fe.close(n=>{n&&G.error({error:String(n)},"websocket close error")}),On.close(n=>{if(n){G.error({error:String(n)},"http close error"),ho(),process.exit(1);return}ho(),process.exit(e)}),setTimeout(()=>{G.error("force exiting after shutdown timeout"),ho(),process.exit(e||1)},3e3).unref()}}fe.on("error",t=>{Ln.error({error:t.message},"wss error")});On.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Rd(S.port).filter(n=>n.pid!==process.pid);G.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 G.error({error:String(t)},"server error");at(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>at("SIGINT"));process.once("SIGTERM",()=>at("SIGTERM"));process.once("SIGHUP",()=>at("SIGHUP"));process.once("SIGTTIN",()=>at("SIGTTIN"));process.once("SIGTSTP",()=>at("SIGTSTP"));process.on("uncaughtException",t=>{G.error({error:String(t),stack:t.stack},"uncaughtException"),I.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{G.error({reason:String(t)},"unhandledRejection"),I.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});On.listen(S.port,async()=>{Zd(),I.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),OS(),$u(),Lt.start().catch(r=>{G.warn({error:String(r)},"session activity watcher failed to start")});let t=Nn();G.info({port:S.port,pairingPort:t.port,daemonId:H.daemonId,displayName:H.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=pe.openWindow(Qd(),S.pairReusable),n={type:"vibelet-pair",daemonId:H.daemonId,displayName:H.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};Ct(`
116
+ `),xt(`If Vibelet app can't scan the terminal QR, open this PNG instead:
117
+ ${vi}
118
+ `)}async function go(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function F(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function WS(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 tf(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function qS(t,e){if(at(t.socket.remoteAddress))return!0;let n=uo(t.headers.authorization,e.searchParams.get("token"));return fo(n,S.legacyToken,(r,s)=>pe.validateAnyPairToken(r,s),!1)}function GS(){let t=pe.openWindow(tf(),S.pairReusable),e=On();return{type:"vibelet-pair",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function jS(t,e){let n=no(t,e),r=await(0,oe.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,oe.stat)((0,jt.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var Bn=(0,Xd.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=On(),i=BS(),o={status:"ok",version:Et,...i?{latestVersion:i}:{}};if(!qS(t,n)){F(e,200,o);return}let a={...o,status:"ok",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-ef)/1e3),activeSessions:Z.getActiveSessionCount(),pairedDevices:pe.pairedCount(),wsClients:fe.clients.size,drivers:Z.getDriverCounts(),sessionInventory:Vu(),metrics:_.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),F(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!at(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}F(e,200,GS());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!at(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}pe.reset(),F(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!at(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}F(e,200,{status:"stopping"}),setTimeout(()=>lt("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!at(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}try{let s=await go(t),i=t.headers[yn],o=Array.isArray(i)?i[0]:i;Z.handleClaudeSessionStartHook(o,s),F(e,200,{ok:!0})}catch(s){F(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!at(t.socket.remoteAddress)){F(e,403,{error:"forbidden"});return}try{let s=await go(t),i=t.headers[yn],o=Array.isArray(i)?i[0]:i,a=await Z.handleClaudePermissionHook(o,s);F(e,200,a)}catch(s){F(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await go(t);if(s.daemonId!==U.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){F(e,400,{error:"invalid_pair_request"});return}if(!pe.consumeWindow(s.pairNonce)){F(e,401,{error:"pair_window_expired"});return}let o=pe.issuePairToken(s.deviceId,s.deviceName),a=On();F(e,200,{daemonId:U.daemonId,displayName:U.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){F(e,400,{error:String(s)})}return}let r=uo(t.headers.authorization,n.searchParams.get("token"));if(!fo(r,S.legacyToken,(s,i)=>pe.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif","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()||s[i]||".bin",u=50*1024*1024,c=[],d=0;for await(let p of t){let h=Buffer.isBuffer(p)?p:Buffer.from(p);if(d+=h.length,d>u){e.writeHead(413),e.end("File too large");return}c.push(h)}try{await(0,oe.mkdir)(yi,{recursive:!0});let p=`${Date.now()}_${(0,Qd.randomBytes)(8).toString("hex")}${l}`,h=(0,jt.join)(yi,p);await(0,oe.writeFile)(h,Buffer.concat(c)),j.info({filePath:h,size:d,contentType:i,providedName:o||void 0},"file uploaded"),F(e,200,{path:h})}catch(p){j.error({error:String(p)},"upload failed"),F(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=no(s,i);if(!(await(0,oe.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=WS(o),u=await(0,oe.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${Et}`)}),fe=new xs.default({server:Bn});Bn.on("connection",t=>{rs.add(t),t.on("close",()=>{rs.delete(t)})});fe.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Zr(r,S.legacyToken))He.set(t,{authMode:"query_token"}),_.increment("ws.auth.success",{mode:"query_token"}),Z.addGlobalClient(t),Z.prewarmCaches();else if(r){let s=pe.validateAnyPairToken(r);if(s)He.set(t,{authMode:"query_token",deviceId:s.deviceId}),_.increment("ws.auth.success",{mode:"query_token"}),Z.addGlobalClient(t),Z.prewarmCaches();else{_.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}Nn.info({clients:fe.clients.size},"client connected"),_.increment("ws.connect"),_.gauge("ws.clients",fe.clients.size),I.emit("ws.connect",{clients:fe.clients.size,authMode:He.get(t)?.authMode??"pending",deviceId:He.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Jd(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!He.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Zr(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===U.daemonId&&pe.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===U.daemonId){let l=pe.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){He.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),_.increment("ws.auth.success",{mode:"auth_hello"}),Z.addGlobalClient(t),Z.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:U.daemonId,displayName:U.displayName}}));return}_.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}_.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)I.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?j.error:a.level==="warn"?j.warn:j.info).call(j,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await jS(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=He.get(t);oo(i,{deviceId:a?.deviceId,registerToken:ro,unregisterToken:so,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=He.get(t);oo(i,{deviceId:a?.deviceId,registerToken:ro,unregisterToken:so,respond:l=>t.send(JSON.stringify(l))});return}await Z.handle(t,o)}catch(i){Nn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{Nn.info({clients:fe.clients.size,code:s},"client disconnected"),_.increment("ws.disconnect"),_.increment("ws.disconnect.code",{code:String(s)}),_.gauge("ws.clients",fe.clients.size),I.emit("ws.disconnect",{clients:fe.clients.size,code:s}),Z.removeClient(t)}),t.on("error",s=>{Nn.error({error:s.message},"websocket error")})});function mo(){for(let t of rs)try{t.destroy()}catch{}rs.clear()}function nf(){let t=Vc({auditPath:Tt,stdoutLogPath:pr,stderrLogPath:hr,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&j.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function $S(){Gt||(Gt=setInterval(nf,S.storageHousekeepingIntervalMs),Gt.unref())}function zS(){Gt&&(clearInterval(Gt),Gt=null)}function lt(t,e=0){if(!Kd){Kd=!0,j.info({reason:t,exitCode:e},"shutting down"),I.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-ef)/1e3)}),_.stopPeriodicLog(),zS(),Lt.stop().catch(()=>{}),Z.shutdown();for(let n of fe.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}fe.close(n=>{n&&j.error({error:String(n)},"websocket close error")}),Bn.close(n=>{if(n){j.error({error:String(n)},"http close error"),mo(),process.exit(1);return}mo(),process.exit(e)}),setTimeout(()=>{j.error("force exiting after shutdown timeout"),mo(),process.exit(e||1)},3e3).unref()}}fe.on("error",t=>{Nn.error({error:t.message},"wss error")});Bn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Md(S.port).filter(n=>n.pid!==process.pid);j.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or start Vibelet with --port <port> (or VIBE_PORT=<port>)")}else j.error({error:String(t)},"server error");lt(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>lt("SIGINT"));process.once("SIGTERM",()=>lt("SIGTERM"));process.once("SIGHUP",()=>lt("SIGHUP"));process.once("SIGTTIN",()=>lt("SIGTTIN"));process.once("SIGTSTP",()=>lt("SIGTSTP"));process.on("uncaughtException",t=>{j.error({error:String(t),stack:t.stack},"uncaughtException"),I.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{j.error({reason:String(t)},"unhandledRejection"),I.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});Bn.listen(S.port,async()=>{nf(),I.emit("daemon.start",{port:S.port}),_.startPeriodicLog(),$S(),Yu(),Lt.start().catch(r=>{j.warn({error:String(r)},"session activity watcher failed to start")});let t=On();j.info({port:S.port,pairingPort:t.port,daemonId:U.daemonId,displayName:U.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs,turnStallHardTimeoutMs:S.turnStallHardTimeoutMs},"daemon started");let e=pe.openWindow(tf(),S.pairReusable),n={type:"vibelet-pair",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};xt(`
119
119
  \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
120
120
  \u2551 Vibelet Daemon v${Et} \u2551
121
121
  \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
122
122
  \u2551 Port: ${String(n.port).padEnd(28)}\u2551
123
- \u2551 ID: ${H.daemonId.slice(0,28).padEnd(28)}\u2551
123
+ \u2551 ID: ${U.daemonId.slice(0,28).padEnd(28)}\u2551
124
124
  \u2551 Host: ${n.canonicalHost.slice(0,28).padEnd(28)}\u2551
125
125
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
126
126
 
@@ -130,4 +130,4 @@ Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
130
130
 
131
131
  Claude: ${S.claudePath}
132
132
  Codex: ${S.codexPath}
133
- `);try{await ES(n)}catch{}});
133
+ `);try{await US(n)}catch{}});