@hallohuman/hightea 0.1.31 → 0.1.32

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.
@@ -1,40 +1,40 @@
1
- import{createRequire as Rh}from"node:module";var vh=Object.create;var{getPrototypeOf:xh,defineProperty:bs,getOwnPropertyNames:bh}=Object;var Es=Object.prototype.hasOwnProperty;function Eh(e){return this[e]}var Ih,kh,ze=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Ih??=new WeakMap:kh??=new WeakMap,s=o.get(e);if(s)return s}r=e!=null?vh(xh(e)):{};let i=t||!e||!e.__esModule||!Es.call(e,"default")?bs(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of bh(e))if(!Es.call(i,a))bs(i,a,{get:Eh.bind(e,a),enumerable:!0})}if(n)o.set(e,i);return i};var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var B=Rh(import.meta.url);var Re=oe(function(Vw,Rs){var Is=["nodebuffer","arraybuffer","fragments"],ks=typeof Blob<"u";if(ks)Is.push("blob");Rs.exports={BINARY_TYPES:Is,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ks,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ct=oe(function(Ww,lr){var{EMPTY_BUFFER:Ch}=Re(),En=Buffer[Symbol.species];function Oh(e,t){if(e.length===0)return Ch;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,n),n+=s.length}if(n<t)return new En(r.buffer,r.byteOffset,n);return r}function Cs(e,t,r,n,o){for(let s=0;s<o;s++)r[n+s]=e[s]^t[s&3]}function Os(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function Th(e){if(e.length===e.buffer.byteLength)return e.buffer;return e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function In(e){if(In.readOnly=!0,Buffer.isBuffer(e))return e;let t;if(e instanceof ArrayBuffer)t=new En(e);else if(ArrayBuffer.isView(e))t=new En(e.buffer,e.byteOffset,e.byteLength);else t=Buffer.from(e),In.readOnly=!1;return t}lr.exports={concat:Oh,mask:Cs,toArrayBuffer:Th,toBuffer:In,unmask:Os};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{throw new Error("Cannot require module "+"bufferutil");})();lr.exports.mask=function(t,r,n,o,s){if(s<48)Cs(t,r,n,o,s);else e.mask(t,r,n,o,s)},lr.exports.unmask=function(t,r){if(t.length<32)Os(t,r);else e.unmask(t,r)}}catch(e){}});var Ps=oe(function(Jw,$s){var Ts=Symbol("kDone"),kn=Symbol("kRun");class As{constructor(e){this[Ts]=()=>{this.pending--,this[kn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[kn]()}[kn](){if(this.pending===this.concurrency)return;if(this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ts])}}}$s.exports=As});var dt=oe(function(Yw,Ds){var _e=B("zlib"),hr=Ct(),Ah=Ps(),{kStatusCode:Ns}=Re(),$h=Buffer[Symbol.species],Ph=Buffer.from([0,0,255,255]),pr=Symbol("permessage-deflate"),Ce=Symbol("total-length"),ct=Symbol("callback"),Me=Symbol("buffers"),ut=Symbol("error"),fr;class zs{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!fr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;fr=new Ah(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};if(this._options.serverNoContextTakeover)e.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)e.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)e.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)e.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)e.client_max_window_bits=!0;return 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;if(this._deflate){let e=this._deflate[ct];if(this._deflate.close(),this._deflate=null,e)e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find((n)=>{if(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits==="number"&&!n.client_max_window_bits)return!1;return!0});if(!r)throw Error("None of the extension offers can be accepted");if(t.serverNoContextTakeover)r.server_no_context_takeover=!0;if(t.clientNoContextTakeover)r.client_no_context_takeover=!0;if(typeof t.serverMaxWindowBits==="number")r.server_max_window_bits=t.serverMaxWindowBits;if(typeof t.clientMaxWindowBits==="number")r.client_max_window_bits=t.clientMaxWindowBits;else if(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)delete r.client_max_window_bits;return r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")t.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach((t)=>{Object.keys(t).forEach((r)=>{let n=t[r];if(n.length>1)throw Error(`Parameter "${r}" must have only a single value`);if(n=n[0],r==="client_max_window_bits"){if(n!==!0){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw TypeError(`Invalid value for parameter "${r}": ${n}`);n=o}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${r}": ${n}`)}else if(r==="server_max_window_bits"){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw TypeError(`Invalid value for parameter "${r}": ${n}`);n=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(n!==!0)throw TypeError(`Invalid value for parameter "${r}": ${n}`)}else throw Error(`Unknown parameter "${r}"`);t[r]=n})}),e}decompress(e,t,r){fr.add((n)=>{this._decompress(e,t,(o,s)=>{n(),r(o,s)})})}compress(e,t,r){fr.add((n)=>{this._compress(e,t,(o,s)=>{n(),r(o,s)})})}_decompress(e,t,r){let n=this._isServer?"client":"server";if(!this._inflate){let o=`${n}_max_window_bits`,s=typeof this.params[o]!=="number"?_e.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=_e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[pr]=this,this._inflate[Ce]=0,this._inflate[Me]=[],this._inflate.on("error",zh),this._inflate.on("data",Ms)}if(this._inflate[ct]=r,this._inflate.write(e),t)this._inflate.write(Ph);this._inflate.flush(()=>{let o=this._inflate[ut];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=hr.concat(this._inflate[Me],this._inflate[Ce]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[Ce]=0,this._inflate[Me]=[],t&&this.params[`${n}_no_context_takeover`])this._inflate.reset();r(null,s)})}_compress(e,t,r){let n=this._isServer?"server":"client";if(!this._deflate){let o=`${n}_max_window_bits`,s=typeof this.params[o]!=="number"?_e.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=_e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Ce]=0,this._deflate[Me]=[],this._deflate.on("data",Nh)}this._deflate[ct]=r,this._deflate.write(e),this._deflate.flush(_e.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=hr.concat(this._deflate[Me],this._deflate[Ce]);if(t)o=new $h(o.buffer,o.byteOffset,o.length-4);if(this._deflate[ct]=null,this._deflate[Ce]=0,this._deflate[Me]=[],t&&this.params[`${n}_no_context_takeover`])this._deflate.reset();r(null,o)})}}Ds.exports=zs;function Nh(e){this[Me].push(e),this[Ce]+=e.length}function Ms(e){if(this[Ce]+=e.length,this[pr]._maxPayload<1||this[Ce]<=this[pr]._maxPayload){this[Me].push(e);return}this[ut]=RangeError("Max payload size exceeded"),this[ut].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ut][Ns]=1009,this.removeListener("data",Ms),this.reset()}function zh(e){if(this[pr]._inflate=null,this[ut]){this[ct](this[ut]);return}e[Ns]=1007,this[ct](e)}});var lt=oe(function(Xw,mr){var{isUtf8:Ls}=B("buffer"),{hasBlob:Mh}=Re(),Dh=[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 Lh(e){return e>=1000&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3000&&e<=4999}function Rn(e){let t=e.length,r=0;while(r<t)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function Uh(e){return Mh&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}mr.exports={isBlob:Uh,isValidStatusCode:Lh,isValidUTF8:Rn,tokenChars:Dh};if(Ls)mr.exports.isValidUTF8=function(e){return e.length<24?Rn(e):Ls(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();mr.exports.isValidUTF8=function(t){return t.length<32?Rn(t):e(t)}}catch(e){}});var On=oe(function(Qw,Fs){var{Writable:Zh}=B("stream"),yr=dt(),{BINARY_TYPES:jh,EMPTY_BUFFER:Us,kStatusCode:Fh,kWebSocket:Hh}=Re(),{concat:Cn,toArrayBuffer:Bh,unmask:qh}=Ct(),{isValidStatusCode:Gh,isValidUTF8:Zs}=lt(),gr=Buffer[Symbol.species];class js extends Zh{constructor(e={}){super();this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||jh[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Hh]=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=0}_write(e,t,r){if(this._opcode===8&&this._state==0)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}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 gr(r.buffer,r.byteOffset+e,r.length-e),new gr(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],n=t.length-e;if(e>=r.length)t.set(this._buffers.shift(),n);else t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new gr(r.buffer,r.byteOffset+e,r.length-e);e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let r=(t[0]&64)===64;if(r&&!this._extensions[yr.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(r){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else 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 t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=Us;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)qh(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[yr.extensionName].decompress(e,this._fin,(n,o)=>{if(n)return t(n);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(s);return}this._fragments.push(o)}if(this.dataMessage(t),this._state===0)this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;if(this._binaryType==="nodebuffer")n=Cn(r,t);else if(this._binaryType==="arraybuffer")n=Bh(Cn(r,t));else if(this._binaryType==="blob")n=new Blob(r);else n=r;if(this._allowSynchronousEvents)this.emit("message",n,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)})}else{let n=Cn(r,t);if(!this._skipUTF8Validation&&!Zs(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",n,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)})}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Us),this.end();else{let r=e.readUInt16BE(0);if(!Gh(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(o);return}let n=new gr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Zs(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",e),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=0,this.startLoop(t)})}createError(e,t,r,n,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=o,s[Fh]=n,s}}Fs.exports=js});var An=oe(function(tS,Bs){var{Duplex:eS}=B("stream"),{randomFillSync:Kh}=B("crypto"),{types:{isUint8Array:Vh}}=B("util"),_r=dt(),{EMPTY_BUFFER:Wh,kWebSocket:Jh,NOOP:Yh}=Re(),{isBlob:ft,isValidStatusCode:Xh}=lt(),{mask:Hs,toBuffer:We}=Ct(),le=Symbol("kByteLength"),Qh=Buffer.alloc(4),Je,ht=8192,me=0,ep=1,tp=2;class De{constructor(e,t,r){if(this._extensions=t||{},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=me,this.onerror=Yh,this[Jh]=void 0}static frame(e,t){let r,n=!1,o=2,s=!1;if(t.mask){if(r=t.maskBuffer||Qh,t.generateMask)t.generateMask(r);else{if(ht===8192){if(Je===void 0)Je=Buffer.alloc(8192);Kh(Je,0,8192),ht=0}r[0]=Je[ht++],r[1]=Je[ht++],r[2]=Je[ht++],r[3]=Je[ht++]}s=(r[0]|r[1]|r[2]|r[3])===0,o=6}let i;if(typeof e==="string")if((!t.mask||s)&&t[le]!==void 0)i=t[le];else e=Buffer.from(e),i=e.length;else i=e.length,n=t.mask&&t.readOnly&&!s;let a=i;if(i>=65536)o+=8,a=127;else if(i>125)o+=2,a=126;let c=Buffer.allocUnsafe(n?i+o:o);if(c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1)c[0]|=64;if(c[1]=a,a===126)c.writeUInt16BE(i,2);else if(a===127)c[2]=c[3]=0,c.writeUIntBE(i,4,6);if(!t.mask)return[c,e];if(c[1]|=128,c[o-4]=r[0],c[o-3]=r[1],c[o-2]=r[2],c[o-1]=r[3],s)return[c,e];if(n)return Hs(e,r,c,o,i),[c];return Hs(e,r,e,0,i),[c,e]}close(e,t,r,n){let o;if(e===void 0)o=Wh;else if(typeof e!=="number"||!Xh(e))throw TypeError("First argument must be a valid error code number");else if(t===void 0||!t.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let i=Buffer.byteLength(t);if(i>123)throw RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+i),o.writeUInt16BE(e,0),typeof t==="string")o.write(t,2);else if(Vh(t))o.set(t,2);else throw TypeError("Second argument must be a string or a Uint8Array")}let s={[le]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==me)this.enqueue([this.dispatch,o,!1,s,n]);else this.sendFrame(De.frame(o,s),n)}ping(e,t,r){let n,o;if(typeof e==="string")n=Buffer.byteLength(e),o=!1;else if(ft(e))n=e.size,o=!1;else e=We(e),n=e.length,o=We.readOnly;if(n>125)throw RangeError("The data size must not be greater than 125 bytes");let s={[le]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};if(ft(e))if(this._state!==me)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==me)this.enqueue([this.dispatch,e,!1,s,r]);else this.sendFrame(De.frame(e,s),r)}pong(e,t,r){let n,o;if(typeof e==="string")n=Buffer.byteLength(e),o=!1;else if(ft(e))n=e.size,o=!1;else e=We(e),n=e.length,o=We.readOnly;if(n>125)throw RangeError("The data size must not be greater than 125 bytes");let s={[le]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};if(ft(e))if(this._state!==me)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==me)this.enqueue([this.dispatch,e,!1,s,r]);else this.sendFrame(De.frame(e,s),r)}send(e,t,r){let n=this._extensions[_r.extensionName],o=t.binary?2:1,s=t.compress,i,a;if(typeof e==="string")i=Buffer.byteLength(e),a=!1;else if(ft(e))i=e.size,a=!1;else e=We(e),i=e.length,a=We.readOnly;if(this._firstFragment){if(this._firstFragment=!1,s&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"])s=i>=n._threshold;this._compress=s}else s=!1,o=0;if(t.fin)this._firstFragment=!0;let c={[le]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:a,rsv1:s};if(ft(e))if(this._state!==me)this.enqueue([this.getBlobData,e,this._compress,c,r]);else this.getBlobData(e,this._compress,c,r);else if(this._state!==me)this.enqueue([this.dispatch,e,this._compress,c,r]);else this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,n){this._bufferedBytes+=r[le],this._state=tp,e.arrayBuffer().then((o)=>{if(this._socket.destroyed){let i=Error("The socket was closed while the blob was being read");process.nextTick(Tn,this,i,n);return}this._bufferedBytes-=r[le];let s=We(o);if(!t)this._state=me,this.sendFrame(De.frame(s,r),n),this.dequeue();else this.dispatch(s,t,r,n)}).catch((o)=>{process.nextTick(rp,this,o,n)})}dispatch(e,t,r,n){if(!t){this.sendFrame(De.frame(e,r),n);return}let o=this._extensions[_r.extensionName];this._bufferedBytes+=r[le],this._state=ep,o.compress(e,r.fin,(s,i)=>{if(this._socket.destroyed){let a=Error("The socket was closed while data was being compressed");Tn(this,a,n);return}this._bufferedBytes-=r[le],this._state=me,r.readOnly=!1,this.sendFrame(De.frame(i,r),n),this.dequeue()})}dequeue(){while(this._state===me&&this._queue.length){let e=this._queue.shift();this._bufferedBytes-=e[3][le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][le],this._queue.push(e)}sendFrame(e,t){if(e.length===2)this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork();else this._socket.write(e[0],t)}}Bs.exports=De;function Tn(e,t,r){if(typeof r==="function")r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],s=o[o.length-1];if(typeof s==="function")s(t)}}function rp(e,t,r){Tn(e,t,r),e.onerror(t)}});var Qs=oe(function(rS,Xs){var{kForOnEventAttribute:Ot,kListener:$n}=Re(),qs=Symbol("kCode"),Gs=Symbol("kData"),Ks=Symbol("kError"),Vs=Symbol("kMessage"),Ws=Symbol("kReason"),pt=Symbol("kTarget"),Js=Symbol("kType"),Ys=Symbol("kWasClean");class Le{constructor(e){this[pt]=null,this[Js]=e}get target(){return this[pt]}get type(){return this[Js]}}Object.defineProperty(Le.prototype,"target",{enumerable:!0});Object.defineProperty(Le.prototype,"type",{enumerable:!0});class mt extends Le{constructor(e,t={}){super(e);this[qs]=t.code===void 0?0:t.code,this[Ws]=t.reason===void 0?"":t.reason,this[Ys]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[qs]}get reason(){return this[Ws]}get wasClean(){return this[Ys]}}Object.defineProperty(mt.prototype,"code",{enumerable:!0});Object.defineProperty(mt.prototype,"reason",{enumerable:!0});Object.defineProperty(mt.prototype,"wasClean",{enumerable:!0});class Tt extends Le{constructor(e,t={}){super(e);this[Ks]=t.error===void 0?null:t.error,this[Vs]=t.message===void 0?"":t.message}get error(){return this[Ks]}get message(){return this[Vs]}}Object.defineProperty(Tt.prototype,"error",{enumerable:!0});Object.defineProperty(Tt.prototype,"message",{enumerable:!0});class Sr extends Le{constructor(e,t={}){super(e);this[Gs]=t.data===void 0?null:t.data}get data(){return this[Gs]}}Object.defineProperty(Sr.prototype,"data",{enumerable:!0});var np={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[Ot]&&o[$n]===t&&!o[Ot])return;let n;if(e==="message")n=function(s,i){let a=new Sr("message",{data:i?s:s.toString()});a[pt]=this,wr(t,this,a)};else if(e==="close")n=function(s,i){let a=new mt("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[pt]=this,wr(t,this,a)};else if(e==="error")n=function(s){let i=new Tt("error",{error:s,message:s.message});i[pt]=this,wr(t,this,i)};else if(e==="open")n=function(){let s=new Le("open");s[pt]=this,wr(t,this,s)};else return;if(n[Ot]=!!r[Ot],n[$n]=t,r.once)this.once(e,n);else this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[$n]===t&&!r[Ot]){this.removeListener(e,r);break}}};Xs.exports={CloseEvent:mt,ErrorEvent:Tt,Event:Le,EventTarget:np,MessageEvent:Sr};function wr(e,t,r){if(typeof e==="object"&&e.handleEvent)e.handleEvent.call(e,r);else e.call(t,r)}});var vr=oe(function(nS,ei){var{tokenChars:At}=lt();function we(e,t,r){if(e[t]===void 0)e[t]=[r];else e[t].push(r)}function op(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,s=!1,i,a,c=-1,d=-1,u=-1,l=0;for(;l<e.length;l++)if(d=e.charCodeAt(l),i===void 0)if(u===-1&&At[d]===1){if(c===-1)c=l}else if(l!==0&&(d===32||d===9)){if(u===-1&&c!==-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;let f=e.slice(c,u);if(d===44)we(t,f,r),r=Object.create(null);else i=f;c=u=-1}else throw SyntaxError(`Unexpected character at index ${l}`);else if(a===void 0)if(u===-1&&At[d]===1){if(c===-1)c=l}else if(d===32||d===9){if(u===-1&&c!==-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;if(we(r,e.slice(c,u),!0),d===44)we(t,i,r),r=Object.create(null),i=void 0;c=u=-1}else if(d===61&&c!==-1&&u===-1)a=e.slice(c,l),c=u=-1;else throw SyntaxError(`Unexpected character at index ${l}`);else if(o){if(At[d]!==1)throw SyntaxError(`Unexpected character at index ${l}`);if(c===-1)c=l;else if(!n)n=!0;o=!1}else if(s)if(At[d]===1){if(c===-1)c=l}else if(d===34&&c!==-1)s=!1,u=l;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${l}`);else if(d===34&&e.charCodeAt(l-1)===61)s=!0;else if(u===-1&&At[d]===1){if(c===-1)c=l}else if(c!==-1&&(d===32||d===9)){if(u===-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;let f=e.slice(c,u);if(n)f=f.replace(/\\/g,""),n=!1;if(we(r,a,f),d===44)we(t,i,r),r=Object.create(null),i=void 0;a=void 0,c=u=-1}else throw SyntaxError(`Unexpected character at index ${l}`);if(c===-1||s||d===32||d===9)throw SyntaxError("Unexpected end of input");if(u===-1)u=l;let p=e.slice(c,u);if(i===void 0)we(t,p,r);else{if(a===void 0)we(r,p,!0);else if(n)we(r,a,p.replace(/\\/g,""));else we(r,a,p);we(t,i,r)}return t}function sp(e){return Object.keys(e).map((t)=>{let r=e[t];if(!Array.isArray(r))r=[r];return r.map((n)=>[t].concat(Object.keys(n).map((o)=>{let s=n[o];if(!Array.isArray(s))s=[s];return s.map((i)=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ei.exports={format:sp,parse:op}});var kr=oe(function(iS,pi){var ip=B("events"),ni=B("https"),oi=B("http"),Er=B("net"),si=B("tls"),{randomBytes:ap,createHash:cp}=B("crypto"),{Duplex:oS,Readable:sS}=B("stream"),{URL:Pn}=B("url"),X=dt(),up=On(),dp=An(),{isBlob:lp}=lt(),{BINARY_TYPES:ti,CLOSE_TIMEOUT:fp,EMPTY_BUFFER:xr,GUID:hp,kForOnEventAttribute:Nn,kListener:pp,kStatusCode:mp,kWebSocket:G,NOOP:ii}=Re(),{EventTarget:{addEventListener:gp,removeEventListener:yp}}=Qs(),{format:_p,parse:wp}=vr(),{toBuffer:Sp}=Ct(),ai=Symbol("kAborted"),zn=[8,13],Oe=["CONNECTING","OPEN","CLOSING","CLOSED"],vp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class T extends ip{constructor(e,t,r){super();if(this._binaryType=ti[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xr,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){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0)t=[];else if(!Array.isArray(t))if(typeof t==="object"&&t!==null)r=t,t=[];else t=[t];ci(this,e,t,r)}else this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){if(!ti.includes(e))return;if(this._binaryType=e,this._receiver)this._receiver._binaryType=e}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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,t,r){let n=new up({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new dp(e,this._extensions,r.generateMask);if(this._receiver=n,this._sender=o,this._socket=e,n[G]=this,o[G]=this,e[G]=this,n.on("conclude",Ep),n.on("drain",Ip),n.on("error",kp),n.on("message",Rp),n.on("ping",Cp),n.on("pong",Op),o.onerror=Tp,e.setTimeout)e.setTimeout(0);if(e.setNoDelay)e.setNoDelay();if(t.length>0)e.unshift(t);e.on("close",li),e.on("data",Ir),e.on("end",fi),e.on("error",hi),this._readyState=T.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=T.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[X.extensionName])this._extensions[X.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=T.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState===T.CLOSED)return;if(this.readyState===T.CONNECTING){se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===T.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=T.CLOSING,this._sender.close(e,t,!this._isServer,(r)=>{if(r)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),di(this)}pause(){if(this.readyState===T.CONNECTING||this.readyState===T.CLOSED)return;this._paused=!0,this._socket.pause()}ping(e,t,r){if(this.readyState===T.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e==="function")r=e,e=t=void 0;else if(typeof t==="function")r=t,t=void 0;if(typeof e==="number")e=e.toString();if(this.readyState!==T.OPEN){Mn(this,e,r);return}if(t===void 0)t=!this._isServer;this._sender.ping(e||xr,t,r)}pong(e,t,r){if(this.readyState===T.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e==="function")r=e,e=t=void 0;else if(typeof t==="function")r=t,t=void 0;if(typeof e==="number")e=e.toString();if(this.readyState!==T.OPEN){Mn(this,e,r);return}if(t===void 0)t=!this._isServer;this._sender.pong(e||xr,t,r)}resume(){if(this.readyState===T.CONNECTING||this.readyState===T.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(e,t,r){if(this.readyState===T.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t==="function")r=t,t={};if(typeof e==="number")e=e.toString();if(this.readyState!==T.OPEN){Mn(this,e,r);return}let n={binary:typeof e!=="string",mask:!this._isServer,compress:!0,fin:!0,...t};if(!this._extensions[X.extensionName])n.compress=!1;this._sender.send(e||xr,n,r)}terminate(){if(this.readyState===T.CLOSED)return;if(this.readyState===T.CONNECTING){se(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=T.CLOSING,this._socket.destroy()}}Object.defineProperty(T,"CONNECTING",{enumerable:!0,value:Oe.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:Oe.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:Oe.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:Oe.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:Oe.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:Oe.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:Oe.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:Oe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e)=>{Object.defineProperty(T.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach((e)=>{Object.defineProperty(T.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Nn])return t[pp];return null},set(t){for(let r of this.listeners(e))if(r[Nn]){this.removeListener(e,r);break}if(typeof t!=="function")return;this.addEventListener(e,t,{[Nn]:!0})}})});T.prototype.addEventListener=gp;T.prototype.removeEventListener=yp;pi.exports=T;function ci(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:fp,protocolVersion:zn[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!zn.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${zn.join(", ")})`);let s;if(t instanceof Pn)s=t;else try{s=new Pn(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}if(s.protocol==="http:")s.protocol="ws:";else if(s.protocol==="https:")s.protocol="wss:";e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!i&&!a)c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(a&&!s.pathname)c="The URL's pathname is empty";else if(s.hash)c="The URL contains a fragment identifier";if(c){let y=SyntaxError(c);if(e._redirects===0)throw y;else{br(e,y);return}}let d=i?443:80,u=ap(16).toString("base64"),l=i?ni.request:oi.request,p=new Set,f;if(o.createConnection=o.createConnection||(i?bp:xp),o.defaultPort=o.defaultPort||d,o.port=s.port||d,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate)f=new X({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=_p({[X.extensionName]:f.offer()});if(r.length){for(let y of r){if(typeof y!=="string"||!vp.test(y)||p.has(y))throw SyntaxError("An invalid or duplicated subprotocol was specified");p.add(y)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin)if(o.protocolVersion<13)o.headers["Sec-WebSocket-Origin"]=o.origin;else o.headers.Origin=o.origin;if(s.username||s.password)o.auth=`${s.username}:${s.password}`;if(a){let y=o.path.split(":");o.socketPath=y[0],o.path=y[1]}let m;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let y=n&&n.headers;if(n={...n,headers:{}},y)for(let[g,w]of Object.entries(y))n.headers[g.toLowerCase()]=w}else if(e.listenerCount("redirect")===0){let y=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;if(!y||e._originalSecure&&!i){if(delete o.headers.authorization,delete o.headers.cookie,!y)delete o.headers.host;o.auth=void 0}}if(o.auth&&!n.headers.authorization)n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64");if(m=e._req=l(o),e._redirects)e.emit("redirect",e.url,m)}else m=e._req=l(o);if(o.timeout)m.on("timeout",()=>{se(e,m,"Opening handshake has timed out")});if(m.on("error",(y)=>{if(m===null||m[ai])return;m=e._req=null,br(e,y)}),m.on("response",(y)=>{let g=y.headers.location,w=y.statusCode;if(g&&o.followRedirects&&w>=300&&w<400){if(++e._redirects>o.maxRedirects){se(e,m,"Maximum redirects exceeded");return}m.abort();let b;try{b=new Pn(g,t)}catch(v){let x=SyntaxError(`Invalid URL: ${g}`);br(e,x);return}ci(e,b,r,n)}else if(!e.emit("unexpected-response",m,y))se(e,m,`Unexpected server response: ${y.statusCode}`)}),m.on("upgrade",(y,g,w)=>{if(e.emit("upgrade",y),e.readyState!==T.CONNECTING)return;m=e._req=null;let b=y.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){se(e,g,"Invalid Upgrade header");return}let v=cp("sha1").update(u+hp).digest("base64");if(y.headers["sec-websocket-accept"]!==v){se(e,g,"Invalid Sec-WebSocket-Accept header");return}let x=y.headers["sec-websocket-protocol"],I;if(x!==void 0){if(!p.size)I="Server sent a subprotocol but none was requested";else if(!p.has(x))I="Server sent an invalid subprotocol"}else if(p.size)I="Server sent no subprotocol";if(I){se(e,g,I);return}if(x)e._protocol=x;let C=y.headers["sec-websocket-extensions"];if(C!==void 0){if(!f){se(e,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=wp(C)}catch(q){se(e,g,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(E);if(A.length!==1||A[0]!==X.extensionName){se(e,g,"Server indicated an extension that was not requested");return}try{f.accept(E[X.extensionName])}catch(q){se(e,g,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[X.extensionName]=f}e.setSocket(g,w,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest)o.finishRequest(m,e);else m.end()}function br(e,t){e._readyState=T.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function xp(e){return e.path=e.socketPath,Er.connect(e)}function bp(e){if(e.path=void 0,!e.servername&&e.servername!=="")e.servername=Er.isIP(e.host)?"":e.host;return si.connect(e)}function se(e,t,r){e._readyState=T.CLOSING;let n=Error(r);if(Error.captureStackTrace(n,se),t.setHeader){if(t[ai]=!0,t.abort(),t.socket&&!t.socket.destroyed)t.socket.destroy();process.nextTick(br,e,n)}else t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e))}function Mn(e,t,r){if(t){let n=lp(t)?t.size:Sp(t).length;if(e._socket)e._sender._bufferedBytes+=n;else e._bufferedAmount+=n}if(r){let n=Error(`WebSocket is not open: readyState ${e.readyState} (${Oe[e.readyState]})`);process.nextTick(r,n)}}function Ep(e,t){let r=this[G];if(r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[G]===void 0)return;if(r._socket.removeListener("data",Ir),process.nextTick(ui,r._socket),e===1005)r.close();else r.close(e,t)}function Ip(){let e=this[G];if(!e.isPaused)e._socket.resume()}function kp(e){let t=this[G];if(t._socket[G]!==void 0)t._socket.removeListener("data",Ir),process.nextTick(ui,t._socket),t.close(e[mp]);if(!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function ri(){this[G].emitClose()}function Rp(e,t){this[G].emit("message",e,t)}function Cp(e){let t=this[G];if(t._autoPong)t.pong(e,!this._isServer,ii);t.emit("ping",e)}function Op(e){this[G].emit("pong",e)}function ui(e){e.resume()}function Tp(e){let t=this[G];if(t.readyState===T.CLOSED)return;if(t.readyState===T.OPEN)t._readyState=T.CLOSING,di(t);if(this._socket.end(),!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function di(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function li(){let e=this[G];if(this.removeListener("close",li),this.removeListener("data",Ir),this.removeListener("end",fi),e._readyState=T.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}if(e._receiver.end(),this[G]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted)e.emitClose();else e._receiver.on("error",ri),e._receiver.on("finish",ri)}function Ir(e){if(!this[G]._receiver.write(e))this.pause()}function fi(){let e=this[G];e._readyState=T.CLOSING,e._receiver.end(),this.end()}function hi(){let e=this[G];if(this.removeListener("error",hi),this.on("error",ii),e)e._readyState=T.CLOSING,this.destroy()}});var _i=oe(function(cS,yi){var aS=kr(),{Duplex:Ap}=B("stream");function mi(e){e.emit("close")}function $p(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function gi(e){if(this.removeListener("error",gi),this.destroy(),this.listenerCount("error")===0)this.emit("error",e)}function Pp(e,t){let r=!0,n=new Ap({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&n._readableState.objectMode?s.toString():s;if(!n.push(a))e.pause()}),e.once("error",function(s){if(n.destroyed)return;r=!1,n.destroy(s)}),e.once("close",function(){if(n.destroyed)return;n.push(null)}),n._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(mi,n);return}let i=!1;if(e.once("error",function(c){i=!0,s(c)}),e.once("close",function(){if(!i)s(o);process.nextTick(mi,n)}),r)e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){n._final(o)});return}if(e._socket===null)return;if(e._socket._writableState.finished){if(o(),n._readableState.endEmitted)n.destroy()}else e._socket.once("finish",function(){o()}),e.close()},n._read=function(){if(e.isPaused)e.resume()},n._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){n._write(o,s,i)});return}e.send(o,i)},n.on("end",$p),n.on("error",gi),n}yi.exports=Pp});var Dn=oe(function(uS,wi){var{tokenChars:Np}=lt();function zp(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(n===-1&&Np[i]===1){if(r===-1)r=o}else if(o!==0&&(i===32||i===9)){if(n===-1&&r!==-1)n=o}else if(i===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${o}`);if(n===-1)n=o;let a=e.slice(r,n);if(t.has(a))throw SyntaxError(`The "${a}" subprotocol is duplicated`);t.add(a),r=n=-1}else throw SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}wi.exports={parse:zp}});var Ei=oe(function(lS,bi){var Mp=B("events"),Ue=B("http"),{Duplex:dS}=B("stream"),{createHash:Dp}=B("crypto"),Rr=vr(),ie=dt(),vi=Dn(),Lp=kr(),{CLOSE_TIMEOUT:Up,GUID:Zp,kWebSocket:jp}=Re(),Fp=/^[+/0-9A-Za-z]{22}==$/;class xi extends Mp{constructor(e,t){super();if(e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Up,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Lp,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null)this._server=Ue.createServer((r,n)=>{let o=Ue.STATUS_CODES[426];n.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),n.end(o)}),this._server.listen(e.port,e.host,e.backlog,t);else if(e.server)this._server=e.server;if(this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Hp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,o,s)=>{this.handleUpgrade(n,o,s,r)}})}if(e.perMessageDeflate===!0)e.perMessageDeflate={};if(e.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(e){if(this._state===2){if(e)this.once("close",()=>{e(Error("The server is not running"))});process.nextTick($t,this);return}if(e)this.once("close",e);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick($t,this);else this._shouldEmitClose=!0;else process.nextTick($t,this)}else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{$t(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",Si);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,i=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ye(this,e,t,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Ye(this,e,t,400,"Invalid Upgrade header");return}if(o===void 0||!Fp.test(o)){Ye(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(i!==13&&i!==8){Ye(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Pt(t,400);return}let a=e.headers["sec-websocket-protocol"],c=new Set;if(a!==void 0)try{c=vi.parse(a)}catch(l){Ye(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let l=new ie({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Rr.parse(d);if(p[ie.extensionName])l.accept(p[ie.extensionName]),u[ie.extensionName]=l}catch(p){Ye(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let l={origin:e.headers[`${i===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(l,(p,f,m,y)=>{if(!p)return Pt(t,f||401,m,y);this.completeUpgrade(u,o,c,e,t,r,n)});return}if(!this.options.verifyClient(l))return Pt(t,401)}this.completeUpgrade(u,o,c,e,t,r,n)}completeUpgrade(e,t,r,n,o,s,i){if(!o.readable||!o.writable)return o.destroy();if(o[jp])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Pt(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Dp("sha1").update(t+Zp).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;if(u)c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u}if(e[ie.extensionName]){let u=e[ie.extensionName].params,l=Rr.format({[ie.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${l}`),d._extensions=e}if(this.emit("headers",c,n),o.write(c.concat(`\r
1
+ import{createRequire as Oh}from"node:module";var bh=Object.create;var{getPrototypeOf:Eh,defineProperty:bs,getOwnPropertyNames:Ih}=Object;var Es=Object.prototype.hasOwnProperty;function kh(e){return this[e]}var Ch,Rh,ze=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Ch??=new WeakMap:Rh??=new WeakMap,s=o.get(e);if(s)return s}r=e!=null?bh(Eh(e)):{};let i=t||!e||!e.__esModule||!Es.call(e,"default")?bs(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Ih(e))if(!Es.call(i,a))bs(i,a,{get:kh.bind(e,a),enumerable:!0})}if(n)o.set(e,i);return i};var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var B=Oh(import.meta.url);var Ce=oe(function(Jw,Cs){var Is=["nodebuffer","arraybuffer","fragments"],ks=typeof Blob<"u";if(ks)Is.push("blob");Cs.exports={BINARY_TYPES:Is,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ks,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Rt=oe(function(Yw,lr){var{EMPTY_BUFFER:Th}=Ce(),In=Buffer[Symbol.species];function Ah(e,t){if(e.length===0)return Th;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let s=e[o];r.set(s,n),n+=s.length}if(n<t)return new In(r.buffer,r.byteOffset,n);return r}function Rs(e,t,r,n,o){for(let s=0;s<o;s++)r[n+s]=e[s]^t[s&3]}function Os(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function $h(e){if(e.length===e.buffer.byteLength)return e.buffer;return e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function kn(e){if(kn.readOnly=!0,Buffer.isBuffer(e))return e;let t;if(e instanceof ArrayBuffer)t=new In(e);else if(ArrayBuffer.isView(e))t=new In(e.buffer,e.byteOffset,e.byteLength);else t=Buffer.from(e),kn.readOnly=!1;return t}lr.exports={concat:Ah,mask:Rs,toArrayBuffer:$h,toBuffer:kn,unmask:Os};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=(()=>{throw new Error("Cannot require module "+"bufferutil");})();lr.exports.mask=function(t,r,n,o,s){if(s<48)Rs(t,r,n,o,s);else e.mask(t,r,n,o,s)},lr.exports.unmask=function(t,r){if(t.length<32)Os(t,r);else e.unmask(t,r)}}catch(e){}});var Ps=oe(function(Xw,$s){var Ts=Symbol("kDone"),Cn=Symbol("kRun");class As{constructor(e){this[Ts]=()=>{this.pending--,this[Cn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Cn]()}[Cn](){if(this.pending===this.concurrency)return;if(this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ts])}}}$s.exports=As});var ut=oe(function(Qw,Ds){var _e=B("zlib"),hr=Rt(),Ph=Ps(),{kStatusCode:Ns}=Ce(),Nh=Buffer[Symbol.species],zh=Buffer.from([0,0,255,255]),pr=Symbol("permessage-deflate"),Re=Symbol("total-length"),at=Symbol("callback"),Me=Symbol("buffers"),ct=Symbol("error"),fr;class zs{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!fr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;fr=new Ph(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};if(this._options.serverNoContextTakeover)e.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)e.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)e.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)e.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)e.client_max_window_bits=!0;return 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;if(this._deflate){let e=this._deflate[at];if(this._deflate.close(),this._deflate=null,e)e(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find((n)=>{if(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits==="number"&&!n.client_max_window_bits)return!1;return!0});if(!r)throw Error("None of the extension offers can be accepted");if(t.serverNoContextTakeover)r.server_no_context_takeover=!0;if(t.clientNoContextTakeover)r.client_no_context_takeover=!0;if(typeof t.serverMaxWindowBits==="number")r.server_max_window_bits=t.serverMaxWindowBits;if(typeof t.clientMaxWindowBits==="number")r.client_max_window_bits=t.clientMaxWindowBits;else if(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)delete r.client_max_window_bits;return r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")t.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach((t)=>{Object.keys(t).forEach((r)=>{let n=t[r];if(n.length>1)throw Error(`Parameter "${r}" must have only a single value`);if(n=n[0],r==="client_max_window_bits"){if(n!==!0){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw TypeError(`Invalid value for parameter "${r}": ${n}`);n=o}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${r}": ${n}`)}else if(r==="server_max_window_bits"){let o=+n;if(!Number.isInteger(o)||o<8||o>15)throw TypeError(`Invalid value for parameter "${r}": ${n}`);n=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(n!==!0)throw TypeError(`Invalid value for parameter "${r}": ${n}`)}else throw Error(`Unknown parameter "${r}"`);t[r]=n})}),e}decompress(e,t,r){fr.add((n)=>{this._decompress(e,t,(o,s)=>{n(),r(o,s)})})}compress(e,t,r){fr.add((n)=>{this._compress(e,t,(o,s)=>{n(),r(o,s)})})}_decompress(e,t,r){let n=this._isServer?"client":"server";if(!this._inflate){let o=`${n}_max_window_bits`,s=typeof this.params[o]!=="number"?_e.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=_e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[pr]=this,this._inflate[Re]=0,this._inflate[Me]=[],this._inflate.on("error",Dh),this._inflate.on("data",Ms)}if(this._inflate[at]=r,this._inflate.write(e),t)this._inflate.write(zh);this._inflate.flush(()=>{let o=this._inflate[ct];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=hr.concat(this._inflate[Me],this._inflate[Re]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[Re]=0,this._inflate[Me]=[],t&&this.params[`${n}_no_context_takeover`])this._inflate.reset();r(null,s)})}_compress(e,t,r){let n=this._isServer?"server":"client";if(!this._deflate){let o=`${n}_max_window_bits`,s=typeof this.params[o]!=="number"?_e.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=_e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Re]=0,this._deflate[Me]=[],this._deflate.on("data",Mh)}this._deflate[at]=r,this._deflate.write(e),this._deflate.flush(_e.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=hr.concat(this._deflate[Me],this._deflate[Re]);if(t)o=new Nh(o.buffer,o.byteOffset,o.length-4);if(this._deflate[at]=null,this._deflate[Re]=0,this._deflate[Me]=[],t&&this.params[`${n}_no_context_takeover`])this._deflate.reset();r(null,o)})}}Ds.exports=zs;function Mh(e){this[Me].push(e),this[Re]+=e.length}function Ms(e){if(this[Re]+=e.length,this[pr]._maxPayload<1||this[Re]<=this[pr]._maxPayload){this[Me].push(e);return}this[ct]=RangeError("Max payload size exceeded"),this[ct].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ct][Ns]=1009,this.removeListener("data",Ms),this.reset()}function Dh(e){if(this[pr]._inflate=null,this[ct]){this[at](this[ct]);return}e[Ns]=1007,this[at](e)}});var dt=oe(function(eS,mr){var{isUtf8:Ls}=B("buffer"),{hasBlob:Lh}=Ce(),Uh=[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 Zh(e){return e>=1000&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3000&&e<=4999}function Rn(e){let t=e.length,r=0;while(r<t)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function jh(e){return Lh&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}mr.exports={isBlob:jh,isValidStatusCode:Zh,isValidUTF8:Rn,tokenChars:Uh};if(Ls)mr.exports.isValidUTF8=function(e){return e.length<24?Rn(e):Ls(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();mr.exports.isValidUTF8=function(t){return t.length<32?Rn(t):e(t)}}catch(e){}});var Tn=oe(function(tS,Fs){var{Writable:Fh}=B("stream"),yr=ut(),{BINARY_TYPES:Hh,EMPTY_BUFFER:Us,kStatusCode:Bh,kWebSocket:qh}=Ce(),{concat:On,toArrayBuffer:Gh,unmask:Kh}=Rt(),{isValidStatusCode:Vh,isValidUTF8:Zs}=dt(),gr=Buffer[Symbol.species];class js extends Fh{constructor(e={}){super();this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Hh[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[qh]=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=0}_write(e,t,r){if(this._opcode===8&&this._state==0)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}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 gr(r.buffer,r.byteOffset+e,r.length-e),new gr(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],n=t.length-e;if(e>=r.length)t.set(this._buffers.shift(),n);else t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new gr(r.buffer,r.byteOffset+e,r.length-e);e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let r=(t[0]&64)===64;if(r&&!this._extensions[yr.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(r){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else 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 t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=Us;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)Kh(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}if(t.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(t)}this.dataMessage(e)}decompress(e,t){this._extensions[yr.extensionName].decompress(e,this._fin,(n,o)=>{if(n)return t(n);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(s);return}this._fragments.push(o)}if(this.dataMessage(t),this._state===0)this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;if(this._binaryType==="nodebuffer")n=On(r,t);else if(this._binaryType==="arraybuffer")n=Gh(On(r,t));else if(this._binaryType==="blob")n=new Blob(r);else n=r;if(this._allowSynchronousEvents)this.emit("message",n,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)})}else{let n=On(r,t);if(!this._skipUTF8Validation&&!Zs(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",n,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)})}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Us),this.end();else{let r=e.readUInt16BE(0);if(!Vh(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(o);return}let n=new gr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Zs(n)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",e),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=0,this.startLoop(t)})}createError(e,t,r,n,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=o,s[Bh]=n,s}}Fs.exports=js});var $n=oe(function(nS,Bs){var{Duplex:rS}=B("stream"),{randomFillSync:Wh}=B("crypto"),{types:{isUint8Array:Jh}}=B("util"),_r=ut(),{EMPTY_BUFFER:Yh,kWebSocket:Xh,NOOP:Qh}=Ce(),{isBlob:lt,isValidStatusCode:ep}=dt(),{mask:Hs,toBuffer:Ve}=Rt(),le=Symbol("kByteLength"),tp=Buffer.alloc(4),We,ft=8192,me=0,rp=1,np=2;class De{constructor(e,t,r){if(this._extensions=t||{},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=me,this.onerror=Qh,this[Xh]=void 0}static frame(e,t){let r,n=!1,o=2,s=!1;if(t.mask){if(r=t.maskBuffer||tp,t.generateMask)t.generateMask(r);else{if(ft===8192){if(We===void 0)We=Buffer.alloc(8192);Wh(We,0,8192),ft=0}r[0]=We[ft++],r[1]=We[ft++],r[2]=We[ft++],r[3]=We[ft++]}s=(r[0]|r[1]|r[2]|r[3])===0,o=6}let i;if(typeof e==="string")if((!t.mask||s)&&t[le]!==void 0)i=t[le];else e=Buffer.from(e),i=e.length;else i=e.length,n=t.mask&&t.readOnly&&!s;let a=i;if(i>=65536)o+=8,a=127;else if(i>125)o+=2,a=126;let c=Buffer.allocUnsafe(n?i+o:o);if(c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1)c[0]|=64;if(c[1]=a,a===126)c.writeUInt16BE(i,2);else if(a===127)c[2]=c[3]=0,c.writeUIntBE(i,4,6);if(!t.mask)return[c,e];if(c[1]|=128,c[o-4]=r[0],c[o-3]=r[1],c[o-2]=r[2],c[o-1]=r[3],s)return[c,e];if(n)return Hs(e,r,c,o,i),[c];return Hs(e,r,e,0,i),[c,e]}close(e,t,r,n){let o;if(e===void 0)o=Yh;else if(typeof e!=="number"||!ep(e))throw TypeError("First argument must be a valid error code number");else if(t===void 0||!t.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let i=Buffer.byteLength(t);if(i>123)throw RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+i),o.writeUInt16BE(e,0),typeof t==="string")o.write(t,2);else if(Jh(t))o.set(t,2);else throw TypeError("Second argument must be a string or a Uint8Array")}let s={[le]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==me)this.enqueue([this.dispatch,o,!1,s,n]);else this.sendFrame(De.frame(o,s),n)}ping(e,t,r){let n,o;if(typeof e==="string")n=Buffer.byteLength(e),o=!1;else if(lt(e))n=e.size,o=!1;else e=Ve(e),n=e.length,o=Ve.readOnly;if(n>125)throw RangeError("The data size must not be greater than 125 bytes");let s={[le]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};if(lt(e))if(this._state!==me)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==me)this.enqueue([this.dispatch,e,!1,s,r]);else this.sendFrame(De.frame(e,s),r)}pong(e,t,r){let n,o;if(typeof e==="string")n=Buffer.byteLength(e),o=!1;else if(lt(e))n=e.size,o=!1;else e=Ve(e),n=e.length,o=Ve.readOnly;if(n>125)throw RangeError("The data size must not be greater than 125 bytes");let s={[le]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};if(lt(e))if(this._state!==me)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==me)this.enqueue([this.dispatch,e,!1,s,r]);else this.sendFrame(De.frame(e,s),r)}send(e,t,r){let n=this._extensions[_r.extensionName],o=t.binary?2:1,s=t.compress,i,a;if(typeof e==="string")i=Buffer.byteLength(e),a=!1;else if(lt(e))i=e.size,a=!1;else e=Ve(e),i=e.length,a=Ve.readOnly;if(this._firstFragment){if(this._firstFragment=!1,s&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"])s=i>=n._threshold;this._compress=s}else s=!1,o=0;if(t.fin)this._firstFragment=!0;let c={[le]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:a,rsv1:s};if(lt(e))if(this._state!==me)this.enqueue([this.getBlobData,e,this._compress,c,r]);else this.getBlobData(e,this._compress,c,r);else if(this._state!==me)this.enqueue([this.dispatch,e,this._compress,c,r]);else this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,n){this._bufferedBytes+=r[le],this._state=np,e.arrayBuffer().then((o)=>{if(this._socket.destroyed){let i=Error("The socket was closed while the blob was being read");process.nextTick(An,this,i,n);return}this._bufferedBytes-=r[le];let s=Ve(o);if(!t)this._state=me,this.sendFrame(De.frame(s,r),n),this.dequeue();else this.dispatch(s,t,r,n)}).catch((o)=>{process.nextTick(op,this,o,n)})}dispatch(e,t,r,n){if(!t){this.sendFrame(De.frame(e,r),n);return}let o=this._extensions[_r.extensionName];this._bufferedBytes+=r[le],this._state=rp,o.compress(e,r.fin,(s,i)=>{if(this._socket.destroyed){let a=Error("The socket was closed while data was being compressed");An(this,a,n);return}this._bufferedBytes-=r[le],this._state=me,r.readOnly=!1,this.sendFrame(De.frame(i,r),n),this.dequeue()})}dequeue(){while(this._state===me&&this._queue.length){let e=this._queue.shift();this._bufferedBytes-=e[3][le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][le],this._queue.push(e)}sendFrame(e,t){if(e.length===2)this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork();else this._socket.write(e[0],t)}}Bs.exports=De;function An(e,t,r){if(typeof r==="function")r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],s=o[o.length-1];if(typeof s==="function")s(t)}}function op(e,t,r){An(e,t,r),e.onerror(t)}});var Qs=oe(function(oS,Xs){var{kForOnEventAttribute:Ot,kListener:Pn}=Ce(),qs=Symbol("kCode"),Gs=Symbol("kData"),Ks=Symbol("kError"),Vs=Symbol("kMessage"),Ws=Symbol("kReason"),ht=Symbol("kTarget"),Js=Symbol("kType"),Ys=Symbol("kWasClean");class Le{constructor(e){this[ht]=null,this[Js]=e}get target(){return this[ht]}get type(){return this[Js]}}Object.defineProperty(Le.prototype,"target",{enumerable:!0});Object.defineProperty(Le.prototype,"type",{enumerable:!0});class pt extends Le{constructor(e,t={}){super(e);this[qs]=t.code===void 0?0:t.code,this[Ws]=t.reason===void 0?"":t.reason,this[Ys]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[qs]}get reason(){return this[Ws]}get wasClean(){return this[Ys]}}Object.defineProperty(pt.prototype,"code",{enumerable:!0});Object.defineProperty(pt.prototype,"reason",{enumerable:!0});Object.defineProperty(pt.prototype,"wasClean",{enumerable:!0});class Tt extends Le{constructor(e,t={}){super(e);this[Ks]=t.error===void 0?null:t.error,this[Vs]=t.message===void 0?"":t.message}get error(){return this[Ks]}get message(){return this[Vs]}}Object.defineProperty(Tt.prototype,"error",{enumerable:!0});Object.defineProperty(Tt.prototype,"message",{enumerable:!0});class Sr extends Le{constructor(e,t={}){super(e);this[Gs]=t.data===void 0?null:t.data}get data(){return this[Gs]}}Object.defineProperty(Sr.prototype,"data",{enumerable:!0});var sp={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[Ot]&&o[Pn]===t&&!o[Ot])return;let n;if(e==="message")n=function(s,i){let a=new Sr("message",{data:i?s:s.toString()});a[ht]=this,wr(t,this,a)};else if(e==="close")n=function(s,i){let a=new pt("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ht]=this,wr(t,this,a)};else if(e==="error")n=function(s){let i=new Tt("error",{error:s,message:s.message});i[ht]=this,wr(t,this,i)};else if(e==="open")n=function(){let s=new Le("open");s[ht]=this,wr(t,this,s)};else return;if(n[Ot]=!!r[Ot],n[Pn]=t,r.once)this.once(e,n);else this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Pn]===t&&!r[Ot]){this.removeListener(e,r);break}}};Xs.exports={CloseEvent:pt,ErrorEvent:Tt,Event:Le,EventTarget:sp,MessageEvent:Sr};function wr(e,t,r){if(typeof e==="object"&&e.handleEvent)e.handleEvent.call(e,r);else e.call(t,r)}});var vr=oe(function(sS,ei){var{tokenChars:At}=dt();function we(e,t,r){if(e[t]===void 0)e[t]=[r];else e[t].push(r)}function ip(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,s=!1,i,a,c=-1,d=-1,u=-1,l=0;for(;l<e.length;l++)if(d=e.charCodeAt(l),i===void 0)if(u===-1&&At[d]===1){if(c===-1)c=l}else if(l!==0&&(d===32||d===9)){if(u===-1&&c!==-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;let f=e.slice(c,u);if(d===44)we(t,f,r),r=Object.create(null);else i=f;c=u=-1}else throw SyntaxError(`Unexpected character at index ${l}`);else if(a===void 0)if(u===-1&&At[d]===1){if(c===-1)c=l}else if(d===32||d===9){if(u===-1&&c!==-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;if(we(r,e.slice(c,u),!0),d===44)we(t,i,r),r=Object.create(null),i=void 0;c=u=-1}else if(d===61&&c!==-1&&u===-1)a=e.slice(c,l),c=u=-1;else throw SyntaxError(`Unexpected character at index ${l}`);else if(o){if(At[d]!==1)throw SyntaxError(`Unexpected character at index ${l}`);if(c===-1)c=l;else if(!n)n=!0;o=!1}else if(s)if(At[d]===1){if(c===-1)c=l}else if(d===34&&c!==-1)s=!1,u=l;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${l}`);else if(d===34&&e.charCodeAt(l-1)===61)s=!0;else if(u===-1&&At[d]===1){if(c===-1)c=l}else if(c!==-1&&(d===32||d===9)){if(u===-1)u=l}else if(d===59||d===44){if(c===-1)throw SyntaxError(`Unexpected character at index ${l}`);if(u===-1)u=l;let f=e.slice(c,u);if(n)f=f.replace(/\\/g,""),n=!1;if(we(r,a,f),d===44)we(t,i,r),r=Object.create(null),i=void 0;a=void 0,c=u=-1}else throw SyntaxError(`Unexpected character at index ${l}`);if(c===-1||s||d===32||d===9)throw SyntaxError("Unexpected end of input");if(u===-1)u=l;let p=e.slice(c,u);if(i===void 0)we(t,p,r);else{if(a===void 0)we(r,p,!0);else if(n)we(r,a,p.replace(/\\/g,""));else we(r,a,p);we(t,i,r)}return t}function ap(e){return Object.keys(e).map((t)=>{let r=e[t];if(!Array.isArray(r))r=[r];return r.map((n)=>[t].concat(Object.keys(n).map((o)=>{let s=n[o];if(!Array.isArray(s))s=[s];return s.map((i)=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ei.exports={format:ap,parse:ip}});var kr=oe(function(cS,pi){var cp=B("events"),ni=B("https"),oi=B("http"),Er=B("net"),si=B("tls"),{randomBytes:up,createHash:dp}=B("crypto"),{Duplex:iS,Readable:aS}=B("stream"),{URL:Nn}=B("url"),X=ut(),lp=Tn(),fp=$n(),{isBlob:hp}=dt(),{BINARY_TYPES:ti,CLOSE_TIMEOUT:pp,EMPTY_BUFFER:xr,GUID:mp,kForOnEventAttribute:zn,kListener:gp,kStatusCode:yp,kWebSocket:G,NOOP:ii}=Ce(),{EventTarget:{addEventListener:_p,removeEventListener:wp}}=Qs(),{format:Sp,parse:vp}=vr(),{toBuffer:xp}=Rt(),ai=Symbol("kAborted"),Mn=[8,13],Oe=["CONNECTING","OPEN","CLOSING","CLOSED"],bp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class O extends cp{constructor(e,t,r){super();if(this._binaryType=ti[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=O.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0)t=[];else if(!Array.isArray(t))if(typeof t==="object"&&t!==null)r=t,t=[];else t=[t];ci(this,e,t,r)}else this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){if(!ti.includes(e))return;if(this._binaryType=e,this._receiver)this._receiver._binaryType=e}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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,t,r){let n=new lp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new fp(e,this._extensions,r.generateMask);if(this._receiver=n,this._sender=o,this._socket=e,n[G]=this,o[G]=this,e[G]=this,n.on("conclude",kp),n.on("drain",Cp),n.on("error",Rp),n.on("message",Op),n.on("ping",Tp),n.on("pong",Ap),o.onerror=$p,e.setTimeout)e.setTimeout(0);if(e.setNoDelay)e.setNoDelay();if(t.length>0)e.unshift(t);e.on("close",li),e.on("data",Ir),e.on("end",fi),e.on("error",hi),this._readyState=O.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=O.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[X.extensionName])this._extensions[X.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=O.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState===O.CLOSED)return;if(this.readyState===O.CONNECTING){se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===O.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=O.CLOSING,this._sender.close(e,t,!this._isServer,(r)=>{if(r)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),di(this)}pause(){if(this.readyState===O.CONNECTING||this.readyState===O.CLOSED)return;this._paused=!0,this._socket.pause()}ping(e,t,r){if(this.readyState===O.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e==="function")r=e,e=t=void 0;else if(typeof t==="function")r=t,t=void 0;if(typeof e==="number")e=e.toString();if(this.readyState!==O.OPEN){Dn(this,e,r);return}if(t===void 0)t=!this._isServer;this._sender.ping(e||xr,t,r)}pong(e,t,r){if(this.readyState===O.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e==="function")r=e,e=t=void 0;else if(typeof t==="function")r=t,t=void 0;if(typeof e==="number")e=e.toString();if(this.readyState!==O.OPEN){Dn(this,e,r);return}if(t===void 0)t=!this._isServer;this._sender.pong(e||xr,t,r)}resume(){if(this.readyState===O.CONNECTING||this.readyState===O.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(e,t,r){if(this.readyState===O.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t==="function")r=t,t={};if(typeof e==="number")e=e.toString();if(this.readyState!==O.OPEN){Dn(this,e,r);return}let n={binary:typeof e!=="string",mask:!this._isServer,compress:!0,fin:!0,...t};if(!this._extensions[X.extensionName])n.compress=!1;this._sender.send(e||xr,n,r)}terminate(){if(this.readyState===O.CLOSED)return;if(this.readyState===O.CONNECTING){se(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=O.CLOSING,this._socket.destroy()}}Object.defineProperty(O,"CONNECTING",{enumerable:!0,value:Oe.indexOf("CONNECTING")});Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:Oe.indexOf("CONNECTING")});Object.defineProperty(O,"OPEN",{enumerable:!0,value:Oe.indexOf("OPEN")});Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:Oe.indexOf("OPEN")});Object.defineProperty(O,"CLOSING",{enumerable:!0,value:Oe.indexOf("CLOSING")});Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:Oe.indexOf("CLOSING")});Object.defineProperty(O,"CLOSED",{enumerable:!0,value:Oe.indexOf("CLOSED")});Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:Oe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e)=>{Object.defineProperty(O.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach((e)=>{Object.defineProperty(O.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[zn])return t[gp];return null},set(t){for(let r of this.listeners(e))if(r[zn]){this.removeListener(e,r);break}if(typeof t!=="function")return;this.addEventListener(e,t,{[zn]:!0})}})});O.prototype.addEventListener=_p;O.prototype.removeEventListener=wp;pi.exports=O;function ci(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:pp,protocolVersion:Mn[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!Mn.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Mn.join(", ")})`);let s;if(t instanceof Nn)s=t;else try{s=new Nn(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}if(s.protocol==="http:")s.protocol="ws:";else if(s.protocol==="https:")s.protocol="wss:";e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!i&&!a)c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(a&&!s.pathname)c="The URL's pathname is empty";else if(s.hash)c="The URL contains a fragment identifier";if(c){let y=SyntaxError(c);if(e._redirects===0)throw y;else{br(e,y);return}}let d=i?443:80,u=up(16).toString("base64"),l=i?ni.request:oi.request,p=new Set,f;if(o.createConnection=o.createConnection||(i?Ip:Ep),o.defaultPort=o.defaultPort||d,o.port=s.port||d,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate)f=new X({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Sp({[X.extensionName]:f.offer()});if(r.length){for(let y of r){if(typeof y!=="string"||!bp.test(y)||p.has(y))throw SyntaxError("An invalid or duplicated subprotocol was specified");p.add(y)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin)if(o.protocolVersion<13)o.headers["Sec-WebSocket-Origin"]=o.origin;else o.headers.Origin=o.origin;if(s.username||s.password)o.auth=`${s.username}:${s.password}`;if(a){let y=o.path.split(":");o.socketPath=y[0],o.path=y[1]}let m;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let y=n&&n.headers;if(n={...n,headers:{}},y)for(let[g,w]of Object.entries(y))n.headers[g.toLowerCase()]=w}else if(e.listenerCount("redirect")===0){let y=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;if(!y||e._originalSecure&&!i){if(delete o.headers.authorization,delete o.headers.cookie,!y)delete o.headers.host;o.auth=void 0}}if(o.auth&&!n.headers.authorization)n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64");if(m=e._req=l(o),e._redirects)e.emit("redirect",e.url,m)}else m=e._req=l(o);if(o.timeout)m.on("timeout",()=>{se(e,m,"Opening handshake has timed out")});if(m.on("error",(y)=>{if(m===null||m[ai])return;m=e._req=null,br(e,y)}),m.on("response",(y)=>{let g=y.headers.location,w=y.statusCode;if(g&&o.followRedirects&&w>=300&&w<400){if(++e._redirects>o.maxRedirects){se(e,m,"Maximum redirects exceeded");return}m.abort();let b;try{b=new Nn(g,t)}catch(v){let x=SyntaxError(`Invalid URL: ${g}`);br(e,x);return}ci(e,b,r,n)}else if(!e.emit("unexpected-response",m,y))se(e,m,`Unexpected server response: ${y.statusCode}`)}),m.on("upgrade",(y,g,w)=>{if(e.emit("upgrade",y),e.readyState!==O.CONNECTING)return;m=e._req=null;let b=y.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){se(e,g,"Invalid Upgrade header");return}let v=dp("sha1").update(u+mp).digest("base64");if(y.headers["sec-websocket-accept"]!==v){se(e,g,"Invalid Sec-WebSocket-Accept header");return}let x=y.headers["sec-websocket-protocol"],I;if(x!==void 0){if(!p.size)I="Server sent a subprotocol but none was requested";else if(!p.has(x))I="Server sent an invalid subprotocol"}else if(p.size)I="Server sent no subprotocol";if(I){se(e,g,I);return}if(x)e._protocol=x;let R=y.headers["sec-websocket-extensions"];if(R!==void 0){if(!f){se(e,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=vp(R)}catch(q){se(e,g,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(E);if(A.length!==1||A[0]!==X.extensionName){se(e,g,"Server indicated an extension that was not requested");return}try{f.accept(E[X.extensionName])}catch(q){se(e,g,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[X.extensionName]=f}e.setSocket(g,w,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest)o.finishRequest(m,e);else m.end()}function br(e,t){e._readyState=O.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function Ep(e){return e.path=e.socketPath,Er.connect(e)}function Ip(e){if(e.path=void 0,!e.servername&&e.servername!=="")e.servername=Er.isIP(e.host)?"":e.host;return si.connect(e)}function se(e,t,r){e._readyState=O.CLOSING;let n=Error(r);if(Error.captureStackTrace(n,se),t.setHeader){if(t[ai]=!0,t.abort(),t.socket&&!t.socket.destroyed)t.socket.destroy();process.nextTick(br,e,n)}else t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e))}function Dn(e,t,r){if(t){let n=hp(t)?t.size:xp(t).length;if(e._socket)e._sender._bufferedBytes+=n;else e._bufferedAmount+=n}if(r){let n=Error(`WebSocket is not open: readyState ${e.readyState} (${Oe[e.readyState]})`);process.nextTick(r,n)}}function kp(e,t){let r=this[G];if(r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[G]===void 0)return;if(r._socket.removeListener("data",Ir),process.nextTick(ui,r._socket),e===1005)r.close();else r.close(e,t)}function Cp(){let e=this[G];if(!e.isPaused)e._socket.resume()}function Rp(e){let t=this[G];if(t._socket[G]!==void 0)t._socket.removeListener("data",Ir),process.nextTick(ui,t._socket),t.close(e[yp]);if(!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function ri(){this[G].emitClose()}function Op(e,t){this[G].emit("message",e,t)}function Tp(e){let t=this[G];if(t._autoPong)t.pong(e,!this._isServer,ii);t.emit("ping",e)}function Ap(e){this[G].emit("pong",e)}function ui(e){e.resume()}function $p(e){let t=this[G];if(t.readyState===O.CLOSED)return;if(t.readyState===O.OPEN)t._readyState=O.CLOSING,di(t);if(this._socket.end(),!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function di(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function li(){let e=this[G];if(this.removeListener("close",li),this.removeListener("data",Ir),this.removeListener("end",fi),e._readyState=O.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}if(e._receiver.end(),this[G]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted)e.emitClose();else e._receiver.on("error",ri),e._receiver.on("finish",ri)}function Ir(e){if(!this[G]._receiver.write(e))this.pause()}function fi(){let e=this[G];e._readyState=O.CLOSING,e._receiver.end(),this.end()}function hi(){let e=this[G];if(this.removeListener("error",hi),this.on("error",ii),e)e._readyState=O.CLOSING,this.destroy()}});var _i=oe(function(dS,yi){var uS=kr(),{Duplex:Pp}=B("stream");function mi(e){e.emit("close")}function Np(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function gi(e){if(this.removeListener("error",gi),this.destroy(),this.listenerCount("error")===0)this.emit("error",e)}function zp(e,t){let r=!0,n=new Pp({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&n._readableState.objectMode?s.toString():s;if(!n.push(a))e.pause()}),e.once("error",function(s){if(n.destroyed)return;r=!1,n.destroy(s)}),e.once("close",function(){if(n.destroyed)return;n.push(null)}),n._destroy=function(o,s){if(e.readyState===e.CLOSED){s(o),process.nextTick(mi,n);return}let i=!1;if(e.once("error",function(c){i=!0,s(c)}),e.once("close",function(){if(!i)s(o);process.nextTick(mi,n)}),r)e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){n._final(o)});return}if(e._socket===null)return;if(e._socket._writableState.finished){if(o(),n._readableState.endEmitted)n.destroy()}else e._socket.once("finish",function(){o()}),e.close()},n._read=function(){if(e.isPaused)e.resume()},n._write=function(o,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){n._write(o,s,i)});return}e.send(o,i)},n.on("end",Np),n.on("error",gi),n}yi.exports=zp});var Ln=oe(function(lS,wi){var{tokenChars:Mp}=dt();function Dp(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let i=e.charCodeAt(o);if(n===-1&&Mp[i]===1){if(r===-1)r=o}else if(o!==0&&(i===32||i===9)){if(n===-1&&r!==-1)n=o}else if(i===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${o}`);if(n===-1)n=o;let a=e.slice(r,n);if(t.has(a))throw SyntaxError(`The "${a}" subprotocol is duplicated`);t.add(a),r=n=-1}else throw SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw SyntaxError("Unexpected end of input");let s=e.slice(r,o);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}wi.exports={parse:Dp}});var Ei=oe(function(hS,bi){var Lp=B("events"),Ue=B("http"),{Duplex:fS}=B("stream"),{createHash:Up}=B("crypto"),Cr=vr(),ie=ut(),vi=Ln(),Zp=kr(),{CLOSE_TIMEOUT:jp,GUID:Fp,kWebSocket:Hp}=Ce(),Bp=/^[+/0-9A-Za-z]{22}==$/;class xi extends Lp{constructor(e,t){super();if(e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Zp,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null)this._server=Ue.createServer((r,n)=>{let o=Ue.STATUS_CODES[426];n.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),n.end(o)}),this._server.listen(e.port,e.host,e.backlog,t);else if(e.server)this._server=e.server;if(this._server){let r=this.emit.bind(this,"connection");this._removeListeners=qp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,o,s)=>{this.handleUpgrade(n,o,s,r)}})}if(e.perMessageDeflate===!0)e.perMessageDeflate={};if(e.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=e,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(e){if(this._state===2){if(e)this.once("close",()=>{e(Error("The server is not running"))});process.nextTick($t,this);return}if(e)this.once("close",e);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick($t,this);else this._shouldEmitClose=!0;else process.nextTick($t,this)}else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{$t(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",Si);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,i=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Je(this,e,t,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Je(this,e,t,400,"Invalid Upgrade header");return}if(o===void 0||!Bp.test(o)){Je(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(i!==13&&i!==8){Je(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Pt(t,400);return}let a=e.headers["sec-websocket-protocol"],c=new Set;if(a!==void 0)try{c=vi.parse(a)}catch(l){Je(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let l=new ie({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Cr.parse(d);if(p[ie.extensionName])l.accept(p[ie.extensionName]),u[ie.extensionName]=l}catch(p){Je(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let l={origin:e.headers[`${i===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(l,(p,f,m,y)=>{if(!p)return Pt(t,f||401,m,y);this.completeUpgrade(u,o,c,e,t,r,n)});return}if(!this.options.verifyClient(l))return Pt(t,401)}this.completeUpgrade(u,o,c,e,t,r,n)}completeUpgrade(e,t,r,n,o,s,i){if(!o.readable||!o.writable)return o.destroy();if(o[Hp])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Pt(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Up("sha1").update(t+Fp).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;if(u)c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u}if(e[ie.extensionName]){let u=e[ie.extensionName].params,l=Cr.format({[ie.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${l}`),d._extensions=e}if(this.emit("headers",c,n),o.write(c.concat(`\r
2
2
  `).join(`\r
3
- `)),o.removeListener("error",Si),d.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(d),d.on("close",()=>{if(this.clients.delete(d),this._shouldEmitClose&&!this.clients.size)process.nextTick($t,this)});i(d,n)}}bi.exports=xi;function Hp(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function $t(e){e._state=2,e.emit("close")}function Si(){this.destroy()}function Pt(e,t,r,n){r=r||Ue.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Ue.STATUS_CODES[t]}\r
3
+ `)),o.removeListener("error",Si),d.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(d),d.on("close",()=>{if(this.clients.delete(d),this._shouldEmitClose&&!this.clients.size)process.nextTick($t,this)});i(d,n)}}bi.exports=xi;function qp(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function $t(e){e._state=2,e.emit("close")}function Si(){this.destroy()}function Pt(e,t,r,n){r=r||Ue.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Ue.STATUS_CODES[t]}\r
4
4
  `+Object.keys(n).map((o)=>`${o}: ${n[o]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+r)}function Ye(e,t,r,n,o,s){if(e.listenerCount("wsClientError")){let i=Error(o);Error.captureStackTrace(i,Ye),e.emit("wsClientError",i,r,t)}else Pt(r,n,o,s)}});var Bp=ze(_i(),1),qp=ze(vr(),1),Gp=ze(dt(),1),Kp=ze(On(),1),Vp=ze(An(),1),Wp=ze(Dn(),1),Ii=ze(kr(),1),Jp=ze(Ei(),1);var ki=Ii.default;var Ri;(function(e){e.Snapshot="snapshot",e.Replay="replay",e.Live="live"})(Ri||(Ri={}));var Ci;(function(e){e.Enabled="enabled",e.Disabled="disabled",e.Unconfigured="unconfigured"})(Ci||(Ci={}));var Ln;(function(e){e.Creating="creating",e.Ready="ready",e.Failed="failed"})(Ln||(Ln={}));var Cr;(function(e){e[e.Idle=1]="Idle",e[e.Error=2]="Error",e[e.InProgress=8]="InProgress",e[e.InputNeeded=24]="InputNeeded",e[e.IsRead=32]="IsRead",e[e.IsArchived=64]="IsArchived"})(Cr||(Cr={}));var Oi;(function(e){e.Automation="automation"})(Oi||(Oi={}));var Un;(function(e){e.ChatInput="chatInput",e.ToolConfirmation="toolConfirmation",e.ToolClientExecution="toolClientExecution",e.ToolAuthentication="toolAuthentication"})(Un||(Un={}));var Zn;(function(e){e.Plugin="plugin",e.Directory="directory",e.Agent="agent",e.Skill="skill",e.Prompt="prompt",e.Rule="rule",e.Hook="hook",e.McpServer="mcpServer"})(Zn||(Zn={}));var Ti;(function(e){e.Global="global",e.Workspace="workspace",e.Session="session"})(Ti||(Ti={}));var Ai;(function(e){e.Loading="loading",e.Loaded="loaded",e.Degraded="degraded",e.Error="error"})(Ai||(Ai={}));var jn;(function(e){e.Starting="starting",e.Ready="ready",e.AuthRequired="authRequired",e.Error="error",e.Stopped="stopped"})(jn||(jn={}));var $i;(function(e){e.Required="required",e.Expired="expired",e.InsufficientScope="insufficientScope"})($i||($i={}));var Pi;(function(e){e.Shell="shell",e.Subagent="subagent"})(Pi||(Pi={}));var Ni;(function(e){e.User="user",e.Fork="fork",e.SideChat="sideChat",e.Tool="tool"})(Ni||(Ni={}));var zi;(function(e){e.Full="full",e.ReadOnly="read-only",e.Hidden="hidden"})(zi||(zi={}));var Fn;(function(e){e.Steering="steering",e.Queued="queued"})(Fn||(Fn={}));var Mi;(function(e){e.Accept="accept",e.Decline="decline",e.Cancel="cancel"})(Mi||(Mi={}));var Di;(function(e){e.Text="text",e.Number="number",e.Integer="integer",e.Boolean="boolean",e.SingleSelect="single-select",e.MultiSelect="multi-select"})(Di||(Di={}));var Li;(function(e){e.Text="text",e.Number="number",e.Boolean="boolean",e.Selected="selected",e.SelectedMany="selected-many"})(Li||(Li={}));var Ui;(function(e){e.Draft="draft",e.Submitted="submitted",e.Skipped="skipped"})(Ui||(Ui={}));var Hn;(function(e){e.Complete="complete",e.Cancelled="cancelled",e.Error="error"})(Hn||(Hn={}));var Zi;(function(e){e.Simple="simple",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.Annotations="annotations",e.Chat="chat"})(Zi||(Zi={}));var ji;(function(e){e.User="user",e.Agent="agent",e.Tool="tool",e.Automation="automation",e.SystemNotification="systemNotification"})(ji||(ji={}));var Bn;(function(e){e.Markdown="markdown",e.ContentRef="contentRef",e.ToolCall="toolCall",e.Reasoning="reasoning",e.SystemNotification="systemNotification",e.InputRequest="inputRequest",e.Error="error"})(Bn||(Bn={}));var qn;(function(e){e.Streaming="streaming",e.PendingConfirmation="pending-confirmation",e.Running="running",e.AuthRequired="auth-required",e.PendingResultConfirmation="pending-result-confirmation",e.Completed="completed",e.Cancelled="cancelled"})(qn||(qn={}));var Gn;(function(e){e.NotNeeded="not-needed",e.UserAction="user-action",e.Setting="setting"})(Gn||(Gn={}));var Fi;(function(e){e.Judge="judge"})(Fi||(Fi={}));var Hi;(function(e){e.Loading="loading",e.Complete="complete"})(Hi||(Hi={}));var Kn;(function(e){e.Denied="denied",e.Skipped="skipped",e.ResultDenied="result-denied"})(Kn||(Kn={}));var Bi;(function(e){e.Approve="approve",e.Deny="deny"})(Bi||(Bi={}));var Vn;(function(e){e.Client="client",e.MCP="mcp"})(Vn||(Vn={}));var qi;(function(e){e.Text="text",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.FileEdit="fileEdit",e.Terminal="terminal",e.Subagent="subagent"})(qi||(qi={}));var Wn;(function(e){e.Running="running",e.Exited="exited"})(Wn||(Wn={}));var Gi;(function(e){e.Client="client",e.Session="session"})(Gi||(Gi={}));var Jn;(function(e){e.Computing="computing",e.Recomputing="recomputing",e.Ready="ready",e.Error="error"})(Jn||(Jn={}));var Ki;(function(e){e[e.Editing=1]="Editing"})(Ki||(Ki={}));var Yn;(function(e){e.Idle="idle",e.Running="running",e.Error="error",e.Disabled="disabled"})(Yn||(Yn={}));var Vi;(function(e){e.Changeset="changeset",e.Resource="resource",e.Range="range"})(Vi||(Vi={}));var Wi;(function(e){e.Added="added",e.Updated="updated",e.Deleted="deleted"})(Wi||(Wi={}));var Ji;(function(e){e.Update="update",e.Remove="remove",e.Run="run"})(Ji||(Ji={}));var Yi;(function(e){e.Skip="skip",e.RunOnce="runOnce"})(Yi||(Yi={}));var Xi;(function(e){e.Schedule="schedule",e.Event="event"})(Xi||(Xi={}));var Qi;(function(e){e.AfterRuns="afterRuns",e.AfterDate="afterDate"})(Qi||(Qi={}));var ea;(function(e){e.Pending="pending",e.Running="running",e.Completed="completed",e.Failed="failed",e.Cancelled="cancelled"})(ea||(ea={}));var ta;(function(e){e.Manual="manual",e.Trigger="trigger"})(ta||(ta={}));var h;(function(e){e.RootAgentsChanged="root/agentsChanged",e.RootActiveSessionsChanged="root/activeSessionsChanged",e.SessionReady="session/ready",e.SessionCreationFailed="session/creationFailed",e.SessionChatAdded="session/chatAdded",e.SessionChatRemoved="session/chatRemoved",e.SessionChatUpdated="session/chatUpdated",e.SessionChatsReordered="session/chatsReordered",e.SessionDefaultChatChanged="session/defaultChatChanged",e.ChatTurnStarted="chat/turnStarted",e.ChatDelta="chat/delta",e.ChatResponsePart="chat/responsePart",e.ChatToolCallStart="chat/toolCallStart",e.ChatToolCallDelta="chat/toolCallDelta",e.ChatToolCallReady="chat/toolCallReady",e.ChatToolCallConfirmed="chat/toolCallConfirmed",e.ChatToolCallComplete="chat/toolCallComplete",e.ChatToolCallResultConfirmed="chat/toolCallResultConfirmed",e.ChatToolCallContentChanged="chat/toolCallContentChanged",e.ChatToolCallAuthRequired="chat/toolCallAuthRequired",e.ChatToolCallAuthResolved="chat/toolCallAuthResolved",e.ChatTurnComplete="chat/turnComplete",e.ChatTurnCancelled="chat/turnCancelled",e.ChatError="chat/error",e.ChatTurnResume="chat/turnResume",e.ChatActivityChanged="chat/activityChanged",e.ChatBackgroundWorkSet="chat/backgroundWorkSet",e.ChatBackgroundWorkRemoved="chat/backgroundWorkRemoved",e.ChatMovableChanged="chat/movableChanged",e.ChatChangesetsChanged="chat/changesetsChanged",e.ChatCanvasesChanged="chat/canvasesChanged",e.CanvasStateChanged="canvas/stateChanged",e.ChatWorkingDirectorySet="chat/workingDirectorySet",e.ChatWorkingDirectoryRemoved="chat/workingDirectoryRemoved",e.SessionTitleChanged="session/titleChanged",e.ChatUsage="chat/usage",e.ChatReasoning="chat/reasoning",e.SessionServerToolsChanged="session/serverToolsChanged",e.SessionActiveClientSet="session/activeClientSet",e.SessionActiveClientRemoved="session/activeClientRemoved",e.SessionWorkingDirectorySet="session/workingDirectorySet",e.SessionWorkingDirectoryRemoved="session/workingDirectoryRemoved",e.SessionWorkingDirectoryReplaced="session/workingDirectoryReplaced",e.SessionInputNeededSet="session/inputNeededSet",e.SessionInputNeededRemoved="session/inputNeededRemoved",e.ChatPendingMessageSet="chat/pendingMessageSet",e.ChatPendingMessageRemoved="chat/pendingMessageRemoved",e.ChatQueuedMessagesReordered="chat/queuedMessagesReordered",e.ChatDraftChanged="chat/draftChanged",e.ChatIsReadChanged="chat/isReadChanged",e.ChatIsArchivedChanged="chat/isArchivedChanged",e.ChatConfigChanged="chat/configChanged",e.ChatMoved="chat/moved",e.ChatInputRequested="chat/inputRequested",e.ChatInputAnswerChanged="chat/inputAnswerChanged",e.ChatInputCompleted="chat/inputCompleted",e.SessionCustomizationsChanged="session/customizationsChanged",e.SessionCustomizationToggled="session/customizationToggled",e.SessionCustomizationUpdated="session/customizationUpdated",e.SessionCustomizationRemoved="session/customizationRemoved",e.SessionMcpServerStateChanged="session/mcpServerStateChanged",e.SessionMcpServerStartRequested="session/mcpServerStartRequested",e.SessionMcpServerStopRequested="session/mcpServerStopRequested",e.SessionMcpServerBackgroundRequested="session/mcpServerBackgroundRequested",e.ChatTruncated="chat/truncated",e.ChatTurnsLoaded="chat/turnsLoaded",e.SessionIsReadChanged="session/isReadChanged",e.SessionIsArchivedChanged="session/isArchivedChanged",e.SessionActivityChanged="session/activityChanged",e.SessionChangesetsChanged="session/changesetsChanged",e.SessionConfigChanged="session/configChanged",e.SessionMetaChanged="session/metaChanged",e.ChangesetStatusChanged="changeset/statusChanged",e.ChangesetFileSet="changeset/fileSet",e.ChangesetFileRemoved="changeset/fileRemoved",e.ChangesetFilesReviewChanged="changeset/filesReviewChanged",e.ChangesetContentChanged="changeset/contentChanged",e.ChangesetOperationsChanged="changeset/operationsChanged",e.ChangesetOperationStatusChanged="changeset/operationStatusChanged",e.ChangesetCleared="changeset/cleared",e.AnnotationsSet="annotations/set",e.AnnotationsUpdated="annotations/updated",e.AnnotationsRemoved="annotations/removed",e.AnnotationsEntrySet="annotations/entrySet",e.AnnotationsEntryRemoved="annotations/entryRemoved",e.RootTerminalsChanged="root/terminalsChanged",e.RootConfigChanged="root/configChanged",e.TerminalData="terminal/data",e.TerminalInput="terminal/input",e.TerminalResized="terminal/resized",e.TerminalClaimed="terminal/claimed",e.TerminalTitleChanged="terminal/titleChanged",e.TerminalCwdChanged="terminal/cwdChanged",e.TerminalExited="terminal/exited",e.TerminalCleared="terminal/cleared",e.TerminalCommandDetectionAvailable="terminal/commandDetectionAvailable",e.TerminalCommandExecuted="terminal/commandExecuted",e.TerminalCommandFinished="terminal/commandFinished",e.ResourceWatchChanged="resourceWatch/changed",e.AutomationCreateRequested="automation/createRequested",e.AutomationUpdateRequested="automation/updateRequested",e.AutomationSet="automation/set",e.AutomationRemoved="automation/removed",e.AutomationRunLifecycleChanged="automationRun/lifecycleChanged",e.AutomationRunSessionSet="automationRun/sessionSet",e.AutomationRunSessionRemoved="automationRun/sessionRemoved",e.AutomationRunPrimarySessionChanged="automationRun/primarySessionChanged",e.AutomationRunCancelRequested="automationRun/cancelRequested"})(h||(h={}));var Yp={[h.RootAgentsChanged]:!1,[h.RootActiveSessionsChanged]:!1,[h.RootTerminalsChanged]:!1,[h.RootConfigChanged]:!0,[h.SessionReady]:!1,[h.SessionCreationFailed]:!1,[h.SessionChatAdded]:!1,[h.SessionChatRemoved]:!1,[h.SessionChatUpdated]:!1,[h.SessionChatsReordered]:!1,[h.SessionDefaultChatChanged]:!1,[h.SessionTitleChanged]:!0,[h.SessionServerToolsChanged]:!1,[h.SessionActiveClientSet]:!0,[h.SessionActiveClientRemoved]:!0,[h.SessionWorkingDirectorySet]:!0,[h.SessionWorkingDirectoryRemoved]:!0,[h.SessionWorkingDirectoryReplaced]:!0,[h.SessionInputNeededSet]:!1,[h.SessionInputNeededRemoved]:!1,[h.SessionCustomizationsChanged]:!1,[h.SessionCustomizationToggled]:!0,[h.SessionCustomizationUpdated]:!1,[h.SessionCustomizationRemoved]:!1,[h.SessionMcpServerStateChanged]:!1,[h.SessionMcpServerStartRequested]:!0,[h.SessionMcpServerStopRequested]:!0,[h.SessionMcpServerBackgroundRequested]:!0,[h.SessionIsReadChanged]:!0,[h.SessionIsArchivedChanged]:!0,[h.SessionActivityChanged]:!1,[h.SessionChangesetsChanged]:!1,[h.SessionConfigChanged]:!0,[h.SessionMetaChanged]:!1,[h.ChatTurnStarted]:!0,[h.ChatDelta]:!1,[h.ChatResponsePart]:!1,[h.ChatToolCallStart]:!1,[h.ChatToolCallDelta]:!1,[h.ChatToolCallReady]:!1,[h.ChatToolCallConfirmed]:!0,[h.ChatToolCallComplete]:!0,[h.ChatToolCallResultConfirmed]:!0,[h.ChatToolCallContentChanged]:!0,[h.ChatToolCallAuthRequired]:!1,[h.ChatToolCallAuthResolved]:!1,[h.ChatTurnComplete]:!1,[h.ChatTurnCancelled]:!0,[h.ChatError]:!1,[h.ChatTurnResume]:!0,[h.ChatActivityChanged]:!1,[h.ChatBackgroundWorkSet]:!1,[h.ChatBackgroundWorkRemoved]:!1,[h.ChatMovableChanged]:!1,[h.ChatChangesetsChanged]:!1,[h.ChatCanvasesChanged]:!1,[h.CanvasStateChanged]:!1,[h.ChatWorkingDirectorySet]:!0,[h.ChatWorkingDirectoryRemoved]:!0,[h.ChatUsage]:!1,[h.ChatReasoning]:!1,[h.ChatPendingMessageSet]:!0,[h.ChatPendingMessageRemoved]:!0,[h.ChatQueuedMessagesReordered]:!0,[h.ChatDraftChanged]:!0,[h.ChatIsReadChanged]:!0,[h.ChatIsArchivedChanged]:!0,[h.ChatConfigChanged]:!0,[h.ChatMoved]:!1,[h.ChatInputRequested]:!1,[h.ChatInputAnswerChanged]:!0,[h.ChatInputCompleted]:!0,[h.ChatTruncated]:!0,[h.ChatTurnsLoaded]:!1,[h.ChangesetStatusChanged]:!1,[h.ChangesetFileSet]:!1,[h.ChangesetFileRemoved]:!1,[h.ChangesetFilesReviewChanged]:!0,[h.ChangesetContentChanged]:!1,[h.ChangesetOperationsChanged]:!1,[h.ChangesetOperationStatusChanged]:!1,[h.ChangesetCleared]:!1,[h.AnnotationsSet]:!0,[h.AnnotationsUpdated]:!0,[h.AnnotationsRemoved]:!0,[h.AnnotationsEntrySet]:!0,[h.AnnotationsEntryRemoved]:!0,[h.TerminalData]:!1,[h.TerminalInput]:!0,[h.TerminalResized]:!0,[h.TerminalClaimed]:!0,[h.TerminalTitleChanged]:!0,[h.TerminalCwdChanged]:!1,[h.TerminalExited]:!1,[h.TerminalCleared]:!0,[h.TerminalCommandDetectionAvailable]:!1,[h.TerminalCommandExecuted]:!1,[h.TerminalCommandFinished]:!1,[h.ResourceWatchChanged]:!1,[h.AutomationCreateRequested]:!0,[h.AutomationUpdateRequested]:!0,[h.AutomationSet]:!1,[h.AutomationRemoved]:!0,[h.AutomationRunLifecycleChanged]:!1,[h.AutomationRunSessionSet]:!1,[h.AutomationRunSessionRemoved]:!1,[h.AutomationRunPrimarySessionChanged]:!1,[h.AutomationRunCancelRequested]:!0};var Xp=["channel/credit","tcp/reset","unsubscribe"],YS=new Set(Xp);var ra;(function(e){e.Posix="posix",e.Windows="windows"})(ra||(ra={}));var na;(function(e){e.Replay="replay",e.Snapshot="snapshot"})(na||(na={}));var oa;(function(e){e.Base64="base64",e.Utf8="utf-8"})(oa||(oa={}));var sa;(function(e){e.Truncate="truncate",e.Append="append",e.Insert="insert"})(sa||(sa={}));var ia;(function(e){e.File="file",e.Directory="directory",e.Symlink="symlink"})(ia||(ia={}));var aa;(function(e){e.McpServer="mcpServer"})(aa||(aa={}));var ca;(function(e){e.UserMessage="userMessage"})(ca||(ca={}));var ua;(function(e){e.Fork="fork",e.SideChat="sideChat"})(ua||(ua={}));var da;(function(e){e.Session="session",e.NewSession="newSession"})(da||(da={}));var la;(function(e){e.Resource="resource",e.Range="range"})(la||(la={}));var fa;(function(e){e.Required="required",e.Expired="expired"})(fa||(fa={}));var Ev=Object.freeze(["1.0.0","0.9.0"]);var Iv={[h.RootAgentsChanged]:"0.1.0",[h.RootActiveSessionsChanged]:"0.1.0",[h.SessionReady]:"0.1.0",[h.SessionCreationFailed]:"0.1.0",[h.SessionChatAdded]:"0.4.0",[h.SessionChatRemoved]:"0.4.0",[h.SessionChatUpdated]:"0.4.0",[h.SessionChatsReordered]:"0.9.0",[h.SessionDefaultChatChanged]:"0.4.0",[h.SessionTitleChanged]:"0.1.0",[h.SessionServerToolsChanged]:"0.1.0",[h.SessionActiveClientSet]:"0.5.0",[h.SessionActiveClientRemoved]:"0.5.0",[h.SessionWorkingDirectorySet]:"0.7.0",[h.SessionWorkingDirectoryRemoved]:"0.7.0",[h.SessionWorkingDirectoryReplaced]:"0.8.0",[h.SessionInputNeededSet]:"0.5.1",[h.SessionInputNeededRemoved]:"0.5.1",[h.SessionCustomizationsChanged]:"0.1.0",[h.SessionCustomizationToggled]:"0.1.0",[h.SessionCustomizationUpdated]:"0.1.0",[h.SessionCustomizationRemoved]:"0.2.0",[h.SessionMcpServerStateChanged]:"0.3.0",[h.SessionMcpServerStartRequested]:"0.5.2",[h.SessionMcpServerStopRequested]:"0.5.2",[h.SessionMcpServerBackgroundRequested]:"0.9.0",[h.SessionIsReadChanged]:"0.1.0",[h.SessionIsArchivedChanged]:"0.1.0",[h.SessionActivityChanged]:"0.1.0",[h.SessionChangesetsChanged]:"0.2.0",[h.SessionConfigChanged]:"0.1.0",[h.SessionMetaChanged]:"0.1.0",[h.ChatTurnStarted]:"0.4.0",[h.ChatDelta]:"0.4.0",[h.ChatResponsePart]:"0.4.0",[h.ChatToolCallStart]:"0.4.0",[h.ChatToolCallDelta]:"0.4.0",[h.ChatToolCallReady]:"0.4.0",[h.ChatToolCallConfirmed]:"0.4.0",[h.ChatToolCallComplete]:"0.4.0",[h.ChatToolCallResultConfirmed]:"0.4.0",[h.ChatToolCallContentChanged]:"0.4.0",[h.ChatToolCallAuthRequired]:"0.6.0",[h.ChatToolCallAuthResolved]:"0.6.0",[h.ChatTurnComplete]:"0.4.0",[h.ChatTurnCancelled]:"0.4.0",[h.ChatError]:"0.4.0",[h.ChatTurnResume]:"0.9.0",[h.ChatActivityChanged]:"0.5.0",[h.ChatBackgroundWorkSet]:"0.9.0",[h.ChatBackgroundWorkRemoved]:"0.9.0",[h.ChatMovableChanged]:"0.9.0",[h.ChatChangesetsChanged]:"0.9.0",[h.ChatCanvasesChanged]:"0.10.0",[h.CanvasStateChanged]:"0.10.0",[h.ChatWorkingDirectorySet]:"0.7.0",[h.ChatWorkingDirectoryRemoved]:"0.7.0",[h.ChatUsage]:"0.4.0",[h.ChatReasoning]:"0.4.0",[h.ChatPendingMessageSet]:"0.4.0",[h.ChatPendingMessageRemoved]:"0.4.0",[h.ChatQueuedMessagesReordered]:"0.4.0",[h.ChatDraftChanged]:"0.5.0",[h.ChatIsReadChanged]:"0.9.0",[h.ChatIsArchivedChanged]:"0.9.0",[h.ChatConfigChanged]:"1.1.0",[h.ChatMoved]:"1.1.0",[h.ChatInputRequested]:"0.4.0",[h.ChatInputAnswerChanged]:"0.4.0",[h.ChatInputCompleted]:"0.4.0",[h.ChatTruncated]:"0.4.0",[h.ChatTurnsLoaded]:"0.5.1",[h.ChangesetStatusChanged]:"0.2.0",[h.ChangesetFileSet]:"0.2.0",[h.ChangesetFileRemoved]:"0.2.0",[h.ChangesetFilesReviewChanged]:"0.6.0",[h.ChangesetContentChanged]:"0.4.0",[h.ChangesetOperationsChanged]:"0.2.0",[h.ChangesetOperationStatusChanged]:"0.3.0",[h.ChangesetCleared]:"0.2.0",[h.AnnotationsSet]:"0.4.0",[h.AnnotationsUpdated]:"0.4.0",[h.AnnotationsRemoved]:"0.4.0",[h.AnnotationsEntrySet]:"0.4.0",[h.AnnotationsEntryRemoved]:"0.4.0",[h.RootTerminalsChanged]:"0.1.0",[h.RootConfigChanged]:"0.1.0",[h.TerminalData]:"0.1.0",[h.TerminalInput]:"0.1.0",[h.TerminalResized]:"0.1.0",[h.TerminalClaimed]:"0.1.0",[h.TerminalTitleChanged]:"0.1.0",[h.TerminalCwdChanged]:"0.1.0",[h.TerminalExited]:"0.1.0",[h.TerminalCleared]:"0.1.0",[h.TerminalCommandDetectionAvailable]:"0.1.0",[h.TerminalCommandExecuted]:"0.1.0",[h.TerminalCommandFinished]:"0.1.0",[h.ResourceWatchChanged]:"0.2.0",[h.AutomationCreateRequested]:"0.8.0",[h.AutomationUpdateRequested]:"0.8.0",[h.AutomationSet]:"0.8.0",[h.AutomationRemoved]:"0.8.0",[h.AutomationRunLifecycleChanged]:"0.8.0",[h.AutomationRunSessionSet]:"0.8.0",[h.AutomationRunSessionRemoved]:"0.8.0",[h.AutomationRunPrimarySessionChanged]:"0.8.0",[h.AutomationRunCancelRequested]:"0.8.0"};function zt(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Qn(e,t="|"){return e.map((r)=>ro(r)).join(t)}function Mt(e,t){if(typeof t==="bigint")return t.toString();return t}class ha{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Dt(e){return new ha(e)}function pa(e){return e===null||e===void 0}function Or(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ma(e,t){let r=e/t,n=Math.round(r),o=4*Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function fe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Lt(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Te(e){return Lt(e._zod.def)??e._zod.def.shape}function ga(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return fe(this,t,n),n},enumerable:!0,configurable:!0})}function ya(e,t,r){if(t in e)fe(e,t,r);else e[t]=r}function Xe(e,t,r,n){let o=Te(t);for(let s of r){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)ga(e,s,()=>{let a=t._zod.def.shape[s];return n?n(a,s):a});else ya(e,s,n?n(i.value,s):i.value)}}function lm(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)ga(e,r,()=>t[r]);else ya(e,r,n.value)}}function ae(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function _a(e){return JSON.stringify(e)}function wa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var eo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Sa=Dt(()=>{if(Q.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Qe(e){if(gt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(gt(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function to(e){if(Qe(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var va=new Set(["string","number","symbol"]);function Fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Se(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function R(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ro(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function xa(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Tr=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),no={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function fm(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s={};return Xe(s,e,Ar(e,t)),Se(e,ae(r,{shape:s,checks:[]}))}function Ar(e,t){let r=Te(e),n=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])n.push(o)}return n}function hm(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(Ar(e,t)),i={};return Xe(i,e,Reflect.ownKeys(Te(e)).filter((a)=>!s.has(a))),Se(e,ae(r,{shape:i,checks:[]}))}function pm(e,t){if(!Qe(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=Te(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Se(e,ae(e._zod.def,{shape:ba(e,t)}))}function ba(e,t){let r={};return Xe(r,e,Reflect.ownKeys(Te(e))),lm(r,t),r}function mm(e,t){if(!Qe(t))throw Error("Invalid input to safeExtend: expected a plain object");return Se(e,ae(e._zod.def,{shape:ba(e,t)}))}function gm(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Xe(r,e,Reflect.ownKeys(Te(e))),Xe(r,t,Reflect.ownKeys(Te(t)));let n=ae(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Se(e,n)}function Ea(e,t,r,n="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(Ar(t,r)):void 0,c={};return Xe(c,t,Reflect.ownKeys(Te(t)),e&&((d,u)=>a&&!a.has(u)?d:new e({type:"optional",innerType:d}))),Se(t,ae(t._zod.def,{shape:c,checks:[]}))}function ym(e,t,r){let n=r?new Set(Ar(t,r)):void 0,o={};return Xe(o,t,Reflect.ownKeys(Te(t)),(s,i)=>n&&!n.has(i)?s:new e({type:"nonoptional",innerType:s})),Se(t,ae(t._zod.def,{shape:o}))}function he(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ia(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ve(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Nt(e){return typeof e==="string"?e:e?.message}function oo(e){let t=[];for(let r of e??[]){let n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let o=n.maximum??n.length??n.size;if(o>=0)t.push([o,r])}return t}function $r(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function xe(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Nt(e.inst?._zod.def?.error?.(e))??Nt(s?.(e))??Nt(t?.error?.(e))??Nt(r.customError?.(e))??Nt(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}var _m=/[\uD800-\uDBFF]/;function Pr(e){let t=e.length;if(!_m.test(e))return t;let r=t;for(let n=0;n<t-1;n++)if((e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320)r--,n++;return r}function Nr(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ka(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function et(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}function Ra(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else wm(e,r,n.value)}}function Ae(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function zr(e,t,r){return Ae(e,t,r,!1)}function Ca(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return Ae(this,r,n(this))},set(o){Ae(this,r,o)}})}return t}function wm(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:Ae(this,t,r.bind(this))},set(n){Ae(this,t,n)}})}function Sm(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Xn,je=!1,vm={configurable:!0,get(){je=!0;return}};function P(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Xn!==e._zod){Xn=void 0;return}Xn=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,vm);let o=je;je=!1;try{let s=r(this);if(je)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return je=je||o,s}catch(s){throw delete this[t],je=je||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function xm(e,t,r,n){let o=Sm(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var bm="~constantCatch";function Oa(e){let t=()=>e;return t[bm]=!0,t}var Ta;var so={value:void 0,enumerable:!1},Aa="captureStackTrace"in Error?Error:null;function Em(e){let t=Aa;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return Aa=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function _(e,t,r,n){let o={};function s(p){this.def=p,this.constr=l,this.traits=new Set}s.prototype=o;let i=r,a=i&&new WeakSet;function c(p,f){if(!p._zod){so.value=new s(f);try{Object.defineProperty(p,"_zod",so)}finally{so.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,f),a){let y=Object.getPrototypeOf(p),g=p._zod.constr.prototype,w=y;while(w&&w!==g)w=Object.getPrototypeOf(w);let b=w??y;if(!a.has(b))a.add(b),Ra(b,i)}let m=l.prototype;for(let y in m){if(!Object.prototype.hasOwnProperty.call(m,y))continue;if(!(y in p))p[y]=m[y].bind(p)}}let d=n?.Parent??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function l(p){let f=n?.Parent?Em(u):this;c(f,p);let m=f._zod.deferred;if(m){for(let g of m)g();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;if(y)y(f);return f}return Object.defineProperty(l,"init",{value:c}),Object.defineProperty(l,Symbol.hasInstance,{value:(p)=>{if(n?.Parent&&p instanceof n.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(l,"name",{value:e}),l}class be extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ut extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Ta=globalThis).__zod_globalConfig??(Ta.__zod_globalConfig={});var Q=globalThis.__zod_globalConfig;function ce(e){if(e)Object.assign(Q,e);return Q}function Im(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Mt,2)),e.message}function km(e){this._zod.message=e}var Rm={get:Im,set:km,enumerable:!0,configurable:!0},ao={value:void 0,enumerable:!1},$a=new WeakSet([Object.prototype,Error.prototype]),Pa=(e,t)=>{e.name="$ZodError",ao.value=t,Object.defineProperty(e,"issues",ao),ao.value=void 0,Object.defineProperty(e,"message",Rm);let r=Object.getPrototypeOf(e);if(!$a.has(r))$a.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Na=_("$ZodError",Pa),Mx=_("$ZodError",Pa,void 0,{Parent:Error});function Cm(e,t,r){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0});else e[t]=r();return e[t]}function za(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)Cm(r,o.path[0],()=>[]).push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Ma(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,d=0;while(d<a.length){let u=a[d],l=d===a.length-1;if(u==="_errors"){if(l)c._errors.push(t(i));d++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[u];if(l)p._errors.push(t(i));c=p,d++}}}};return n(e),r}function Mr(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Dr=(e)=>{let t=(r,n,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new be;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((d)=>xe(d,i,ce())));throw eo(c,s?.callee??t),c}return a.value};return t};var Lr=(e)=>{let t=async(r,n,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((d)=>xe(d,i,ce())));throw eo(c,s?.callee??t),c}return a.value};return t};var Ur=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new be;return s.issues.length?Da(e,s.issues,o):{success:!0,data:s.value}};function Da(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>xe(o,r,ce()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var Zr=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?Da(e,s.issues,o):{success:!0,data:s.value}};var Om=Symbol.for("zod.compile.invalid"),Tm=Symbol.for("zod.compile.fallback"),co=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==Om)return!0;if(n.definite===!0&&r===void 0)return!1}return Am(e,t,r)};function Am(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)n[Tm]=!0,s=o({value:t,issues:[]},n);else s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)throw new be;return s.issues.length===0}var uo=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},n);if(o instanceof Promise)o=await o;return o.issues.length===0},La=(e)=>{let t=Dr(e),r=(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(n,o,a,Mr(r,i))};return r};var Ua=(e)=>{let t=Dr(e),r=(n,o,s,i)=>t(n,o,s,Mr(r,i));return r};var Za=(e)=>{let t=Lr(e),r=async(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(n,o,a,Mr(r,i))};return r};var ja=(e)=>{let t=Lr(e),r=async(n,o,s,i)=>await t(n,o,s,Mr(r,i));return r};var Fa=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ur(e)(t,r,o)};var Ha=(e)=>(t,r,n)=>Ur(e)(t,r,n);var Ba=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Zr(e)(t,r,o)};var qa=(e)=>async(t,r,n)=>Zr(e)(t,r,n);var Ga=/^[cC][0-9a-z]{6,}$/,Ka=/^[0-9a-z]+$/,Va=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Wa=/^[0-9a-vA-V]{20}$/,Ja=/^[A-Za-z0-9]{27}$/,Ya=/^[a-zA-Z0-9_-]{21}$/;function Xa(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Qa=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ec=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fo=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var tc=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var $m="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function rc(){return new RegExp($m,"u")}var nc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var sc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ic=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ac=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cc=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var uc=/^https?$/,dc=/^\+[1-9]\d{6,14}$/;var lc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Pm(e){return new RegExp(`^${e}$`)}var fc=Pm(lc);function lo(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function hc(e){return new RegExp(`^${lo(e)}$`)}function pc(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${lo({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${lo({precision:e.precision})}`:r;return new RegExp(`^${lc}T(?:${n})$`)}var mc=/^[\s\S]{0,}$/;var ho=/^-?\d+$/,Zt=/^-?\d+(?:\.\d+)?$/,gc=/^(?:true|false)$/i;var yc=/^[^A-Z]*$/,_c=/^[^a-z]*$/;var V=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var po=(e)=>{let t=e.value;return!pa(t)&&t.length!==void 0},jr={number:"number",bigint:"bigint",object:"date"},mo=_("$ZodCheckLessThan",(e,t)=>{V.init(e,t);let r=jr[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:jr[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),go=_("$ZodCheckGreaterThan",(e,t)=>{V.init(e,t);let r=jr[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:jr[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wc=_("$ZodCheckMultipleOf",(e,t)=>{V.init(e,t),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):ma(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Sc=_("$ZodCheckNumberFormat",(e,t)=>{V.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Tr[t.format];e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var vc=_("$ZodCheckMaxLength",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=po),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>t.maximum?Pr(o):s)<=t.maximum)return;let a=Nr(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xc=_("$ZodCheckMinLength",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=po),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?Pr(o):s)>=t.minimum)return;let a=Nr(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bc=_("$ZodCheckLengthEquals",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=po),e._zod.check=(n)=>{let o=n.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?Pr(o):s;if(i===t.length)return;let a=Nr(o),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ft=_("$ZodCheckStringFormat",(e,t)=>{var r,n;if(V.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Ec=_("$ZodCheckRegex",(e,t)=>{Ft.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ic=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=yc),Ft.init(e,t)}),kc=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=_c),Ft.init(e,t)}),Rc=_("$ZodCheckIncludes",(e,t)=>{V.init(e,t);let r=Fe(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Cc=_("$ZodCheckStartsWith",(e,t)=>{V.init(e,t);let r=new RegExp(`^${Fe(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Oc=_("$ZodCheckEndsWith",(e,t)=>{V.init(e,t);let r=new RegExp(`.*${Fe(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Tc=_("$ZodCheckOverwrite",(e,t)=>{V.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class yo{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
7
+ `+r)}function Je(e,t,r,n,o,s){if(e.listenerCount("wsClientError")){let i=Error(o);Error.captureStackTrace(i,Je),e.emit("wsClientError",i,r,t)}else Pt(r,n,o,s)}});var Gp=ze(_i(),1),Kp=ze(vr(),1),Vp=ze(ut(),1),Wp=ze(Tn(),1),Jp=ze($n(),1),Yp=ze(Ln(),1),Ii=ze(kr(),1),Xp=ze(Ei(),1);var ki=Ii.default;var Ci;(function(e){e.Snapshot="snapshot",e.Replay="replay",e.Live="live"})(Ci||(Ci={}));var Ri;(function(e){e.Enabled="enabled",e.Disabled="disabled",e.Unconfigured="unconfigured"})(Ri||(Ri={}));var Un;(function(e){e.Creating="creating",e.Ready="ready",e.Failed="failed"})(Un||(Un={}));var Rr;(function(e){e[e.Idle=1]="Idle",e[e.Error=2]="Error",e[e.InProgress=8]="InProgress",e[e.InputNeeded=24]="InputNeeded",e[e.IsRead=32]="IsRead",e[e.IsArchived=64]="IsArchived"})(Rr||(Rr={}));var Oi;(function(e){e.Automation="automation"})(Oi||(Oi={}));var Zn;(function(e){e.ChatInput="chatInput",e.ToolConfirmation="toolConfirmation",e.ToolClientExecution="toolClientExecution",e.ToolAuthentication="toolAuthentication"})(Zn||(Zn={}));var jn;(function(e){e.Plugin="plugin",e.Directory="directory",e.Agent="agent",e.Skill="skill",e.Prompt="prompt",e.Rule="rule",e.Hook="hook",e.McpServer="mcpServer"})(jn||(jn={}));var Ti;(function(e){e.Global="global",e.Workspace="workspace",e.Session="session"})(Ti||(Ti={}));var Ai;(function(e){e.Loading="loading",e.Loaded="loaded",e.Degraded="degraded",e.Error="error"})(Ai||(Ai={}));var Fn;(function(e){e.Starting="starting",e.Ready="ready",e.AuthRequired="authRequired",e.Error="error",e.Stopped="stopped"})(Fn||(Fn={}));var $i;(function(e){e.Required="required",e.Expired="expired",e.InsufficientScope="insufficientScope"})($i||($i={}));var Pi;(function(e){e.Shell="shell",e.Subagent="subagent"})(Pi||(Pi={}));var Ni;(function(e){e.User="user",e.Fork="fork",e.SideChat="sideChat",e.Tool="tool"})(Ni||(Ni={}));var zi;(function(e){e.Full="full",e.ReadOnly="read-only",e.Hidden="hidden"})(zi||(zi={}));var Hn;(function(e){e.Steering="steering",e.Queued="queued"})(Hn||(Hn={}));var Mi;(function(e){e.Accept="accept",e.Decline="decline",e.Cancel="cancel"})(Mi||(Mi={}));var Di;(function(e){e.Text="text",e.Number="number",e.Integer="integer",e.Boolean="boolean",e.SingleSelect="single-select",e.MultiSelect="multi-select"})(Di||(Di={}));var Li;(function(e){e.Text="text",e.Number="number",e.Boolean="boolean",e.Selected="selected",e.SelectedMany="selected-many"})(Li||(Li={}));var Ui;(function(e){e.Draft="draft",e.Submitted="submitted",e.Skipped="skipped"})(Ui||(Ui={}));var Bn;(function(e){e.Complete="complete",e.Cancelled="cancelled",e.Error="error"})(Bn||(Bn={}));var Zi;(function(e){e.Simple="simple",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.Annotations="annotations",e.Chat="chat"})(Zi||(Zi={}));var ji;(function(e){e.User="user",e.Agent="agent",e.Tool="tool",e.Automation="automation",e.SystemNotification="systemNotification"})(ji||(ji={}));var qn;(function(e){e.Markdown="markdown",e.ContentRef="contentRef",e.ToolCall="toolCall",e.Reasoning="reasoning",e.SystemNotification="systemNotification",e.InputRequest="inputRequest",e.Error="error"})(qn||(qn={}));var Gn;(function(e){e.Streaming="streaming",e.PendingConfirmation="pending-confirmation",e.Running="running",e.AuthRequired="auth-required",e.PendingResultConfirmation="pending-result-confirmation",e.Completed="completed",e.Cancelled="cancelled"})(Gn||(Gn={}));var Kn;(function(e){e.NotNeeded="not-needed",e.UserAction="user-action",e.Setting="setting"})(Kn||(Kn={}));var Fi;(function(e){e.Judge="judge"})(Fi||(Fi={}));var Hi;(function(e){e.Loading="loading",e.Complete="complete"})(Hi||(Hi={}));var Vn;(function(e){e.Denied="denied",e.Skipped="skipped",e.ResultDenied="result-denied"})(Vn||(Vn={}));var Bi;(function(e){e.Approve="approve",e.Deny="deny"})(Bi||(Bi={}));var Wn;(function(e){e.Client="client",e.MCP="mcp"})(Wn||(Wn={}));var qi;(function(e){e.Text="text",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.FileEdit="fileEdit",e.Terminal="terminal",e.Subagent="subagent"})(qi||(qi={}));var Jn;(function(e){e.Running="running",e.Exited="exited"})(Jn||(Jn={}));var Gi;(function(e){e.Client="client",e.Session="session"})(Gi||(Gi={}));var Yn;(function(e){e.Computing="computing",e.Recomputing="recomputing",e.Ready="ready",e.Error="error"})(Yn||(Yn={}));var Ki;(function(e){e[e.Editing=1]="Editing"})(Ki||(Ki={}));var Xn;(function(e){e.Idle="idle",e.Running="running",e.Error="error",e.Disabled="disabled"})(Xn||(Xn={}));var Vi;(function(e){e.Changeset="changeset",e.Resource="resource",e.Range="range"})(Vi||(Vi={}));var Wi;(function(e){e.Added="added",e.Updated="updated",e.Deleted="deleted"})(Wi||(Wi={}));var Ji;(function(e){e.Update="update",e.Remove="remove",e.Run="run"})(Ji||(Ji={}));var Yi;(function(e){e.Skip="skip",e.RunOnce="runOnce"})(Yi||(Yi={}));var Xi;(function(e){e.Schedule="schedule",e.Event="event"})(Xi||(Xi={}));var Qi;(function(e){e.AfterRuns="afterRuns",e.AfterDate="afterDate"})(Qi||(Qi={}));var ea;(function(e){e.Pending="pending",e.Running="running",e.Completed="completed",e.Failed="failed",e.Cancelled="cancelled"})(ea||(ea={}));var ta;(function(e){e.Manual="manual",e.Trigger="trigger"})(ta||(ta={}));var h;(function(e){e.RootAgentsChanged="root/agentsChanged",e.RootActiveSessionsChanged="root/activeSessionsChanged",e.SessionReady="session/ready",e.SessionCreationFailed="session/creationFailed",e.SessionChatAdded="session/chatAdded",e.SessionChatRemoved="session/chatRemoved",e.SessionChatUpdated="session/chatUpdated",e.SessionChatsReordered="session/chatsReordered",e.SessionDefaultChatChanged="session/defaultChatChanged",e.ChatTurnStarted="chat/turnStarted",e.ChatDelta="chat/delta",e.ChatResponsePart="chat/responsePart",e.ChatToolCallStart="chat/toolCallStart",e.ChatToolCallDelta="chat/toolCallDelta",e.ChatToolCallReady="chat/toolCallReady",e.ChatToolCallConfirmed="chat/toolCallConfirmed",e.ChatToolCallComplete="chat/toolCallComplete",e.ChatToolCallResultConfirmed="chat/toolCallResultConfirmed",e.ChatToolCallContentChanged="chat/toolCallContentChanged",e.ChatToolCallAuthRequired="chat/toolCallAuthRequired",e.ChatToolCallAuthResolved="chat/toolCallAuthResolved",e.ChatTurnComplete="chat/turnComplete",e.ChatTurnCancelled="chat/turnCancelled",e.ChatError="chat/error",e.ChatTurnResume="chat/turnResume",e.ChatActivityChanged="chat/activityChanged",e.ChatBackgroundWorkSet="chat/backgroundWorkSet",e.ChatBackgroundWorkRemoved="chat/backgroundWorkRemoved",e.ChatMovableChanged="chat/movableChanged",e.ChatChangesetsChanged="chat/changesetsChanged",e.ChatCanvasesChanged="chat/canvasesChanged",e.CanvasStateChanged="canvas/stateChanged",e.ChatWorkingDirectorySet="chat/workingDirectorySet",e.ChatWorkingDirectoryRemoved="chat/workingDirectoryRemoved",e.SessionTitleChanged="session/titleChanged",e.ChatUsage="chat/usage",e.ChatReasoning="chat/reasoning",e.SessionServerToolsChanged="session/serverToolsChanged",e.SessionActiveClientSet="session/activeClientSet",e.SessionActiveClientRemoved="session/activeClientRemoved",e.SessionWorkingDirectorySet="session/workingDirectorySet",e.SessionWorkingDirectoryRemoved="session/workingDirectoryRemoved",e.SessionWorkingDirectoryReplaced="session/workingDirectoryReplaced",e.SessionInputNeededSet="session/inputNeededSet",e.SessionInputNeededRemoved="session/inputNeededRemoved",e.ChatPendingMessageSet="chat/pendingMessageSet",e.ChatPendingMessageRemoved="chat/pendingMessageRemoved",e.ChatQueuedMessagesReordered="chat/queuedMessagesReordered",e.ChatDraftChanged="chat/draftChanged",e.ChatIsReadChanged="chat/isReadChanged",e.ChatIsArchivedChanged="chat/isArchivedChanged",e.ChatConfigChanged="chat/configChanged",e.ChatMoved="chat/moved",e.ChatInputRequested="chat/inputRequested",e.ChatInputAnswerChanged="chat/inputAnswerChanged",e.ChatInputCompleted="chat/inputCompleted",e.SessionCustomizationsChanged="session/customizationsChanged",e.SessionCustomizationToggled="session/customizationToggled",e.SessionCustomizationUpdated="session/customizationUpdated",e.SessionCustomizationRemoved="session/customizationRemoved",e.SessionMcpServerStateChanged="session/mcpServerStateChanged",e.SessionMcpServerStartRequested="session/mcpServerStartRequested",e.SessionMcpServerStopRequested="session/mcpServerStopRequested",e.SessionMcpServerBackgroundRequested="session/mcpServerBackgroundRequested",e.ChatTruncated="chat/truncated",e.ChatTurnsLoaded="chat/turnsLoaded",e.SessionIsReadChanged="session/isReadChanged",e.SessionIsArchivedChanged="session/isArchivedChanged",e.SessionActivityChanged="session/activityChanged",e.SessionChangesetsChanged="session/changesetsChanged",e.SessionConfigChanged="session/configChanged",e.SessionMetaChanged="session/metaChanged",e.ChangesetStatusChanged="changeset/statusChanged",e.ChangesetFileSet="changeset/fileSet",e.ChangesetFileRemoved="changeset/fileRemoved",e.ChangesetFilesReviewChanged="changeset/filesReviewChanged",e.ChangesetContentChanged="changeset/contentChanged",e.ChangesetOperationsChanged="changeset/operationsChanged",e.ChangesetOperationStatusChanged="changeset/operationStatusChanged",e.ChangesetCleared="changeset/cleared",e.AnnotationsSet="annotations/set",e.AnnotationsUpdated="annotations/updated",e.AnnotationsRemoved="annotations/removed",e.AnnotationsEntrySet="annotations/entrySet",e.AnnotationsEntryRemoved="annotations/entryRemoved",e.RootTerminalsChanged="root/terminalsChanged",e.RootConfigChanged="root/configChanged",e.TerminalData="terminal/data",e.TerminalInput="terminal/input",e.TerminalResized="terminal/resized",e.TerminalClaimed="terminal/claimed",e.TerminalTitleChanged="terminal/titleChanged",e.TerminalCwdChanged="terminal/cwdChanged",e.TerminalExited="terminal/exited",e.TerminalCleared="terminal/cleared",e.TerminalCommandDetectionAvailable="terminal/commandDetectionAvailable",e.TerminalCommandExecuted="terminal/commandExecuted",e.TerminalCommandFinished="terminal/commandFinished",e.ResourceWatchChanged="resourceWatch/changed",e.AutomationCreateRequested="automation/createRequested",e.AutomationUpdateRequested="automation/updateRequested",e.AutomationSet="automation/set",e.AutomationRemoved="automation/removed",e.AutomationRunLifecycleChanged="automationRun/lifecycleChanged",e.AutomationRunSessionSet="automationRun/sessionSet",e.AutomationRunSessionRemoved="automationRun/sessionRemoved",e.AutomationRunPrimarySessionChanged="automationRun/primarySessionChanged",e.AutomationRunCancelRequested="automationRun/cancelRequested"})(h||(h={}));var Qp={[h.RootAgentsChanged]:!1,[h.RootActiveSessionsChanged]:!1,[h.RootTerminalsChanged]:!1,[h.RootConfigChanged]:!0,[h.SessionReady]:!1,[h.SessionCreationFailed]:!1,[h.SessionChatAdded]:!1,[h.SessionChatRemoved]:!1,[h.SessionChatUpdated]:!1,[h.SessionChatsReordered]:!1,[h.SessionDefaultChatChanged]:!1,[h.SessionTitleChanged]:!0,[h.SessionServerToolsChanged]:!1,[h.SessionActiveClientSet]:!0,[h.SessionActiveClientRemoved]:!0,[h.SessionWorkingDirectorySet]:!0,[h.SessionWorkingDirectoryRemoved]:!0,[h.SessionWorkingDirectoryReplaced]:!0,[h.SessionInputNeededSet]:!1,[h.SessionInputNeededRemoved]:!1,[h.SessionCustomizationsChanged]:!1,[h.SessionCustomizationToggled]:!0,[h.SessionCustomizationUpdated]:!1,[h.SessionCustomizationRemoved]:!1,[h.SessionMcpServerStateChanged]:!1,[h.SessionMcpServerStartRequested]:!0,[h.SessionMcpServerStopRequested]:!0,[h.SessionMcpServerBackgroundRequested]:!0,[h.SessionIsReadChanged]:!0,[h.SessionIsArchivedChanged]:!0,[h.SessionActivityChanged]:!1,[h.SessionChangesetsChanged]:!1,[h.SessionConfigChanged]:!0,[h.SessionMetaChanged]:!1,[h.ChatTurnStarted]:!0,[h.ChatDelta]:!1,[h.ChatResponsePart]:!1,[h.ChatToolCallStart]:!1,[h.ChatToolCallDelta]:!1,[h.ChatToolCallReady]:!1,[h.ChatToolCallConfirmed]:!0,[h.ChatToolCallComplete]:!0,[h.ChatToolCallResultConfirmed]:!0,[h.ChatToolCallContentChanged]:!0,[h.ChatToolCallAuthRequired]:!1,[h.ChatToolCallAuthResolved]:!1,[h.ChatTurnComplete]:!1,[h.ChatTurnCancelled]:!0,[h.ChatError]:!1,[h.ChatTurnResume]:!0,[h.ChatActivityChanged]:!1,[h.ChatBackgroundWorkSet]:!1,[h.ChatBackgroundWorkRemoved]:!1,[h.ChatMovableChanged]:!1,[h.ChatChangesetsChanged]:!1,[h.ChatCanvasesChanged]:!1,[h.CanvasStateChanged]:!1,[h.ChatWorkingDirectorySet]:!0,[h.ChatWorkingDirectoryRemoved]:!0,[h.ChatUsage]:!1,[h.ChatReasoning]:!1,[h.ChatPendingMessageSet]:!0,[h.ChatPendingMessageRemoved]:!0,[h.ChatQueuedMessagesReordered]:!0,[h.ChatDraftChanged]:!0,[h.ChatIsReadChanged]:!0,[h.ChatIsArchivedChanged]:!0,[h.ChatConfigChanged]:!0,[h.ChatMoved]:!1,[h.ChatInputRequested]:!1,[h.ChatInputAnswerChanged]:!0,[h.ChatInputCompleted]:!0,[h.ChatTruncated]:!0,[h.ChatTurnsLoaded]:!1,[h.ChangesetStatusChanged]:!1,[h.ChangesetFileSet]:!1,[h.ChangesetFileRemoved]:!1,[h.ChangesetFilesReviewChanged]:!0,[h.ChangesetContentChanged]:!1,[h.ChangesetOperationsChanged]:!1,[h.ChangesetOperationStatusChanged]:!1,[h.ChangesetCleared]:!1,[h.AnnotationsSet]:!0,[h.AnnotationsUpdated]:!0,[h.AnnotationsRemoved]:!0,[h.AnnotationsEntrySet]:!0,[h.AnnotationsEntryRemoved]:!0,[h.TerminalData]:!1,[h.TerminalInput]:!0,[h.TerminalResized]:!0,[h.TerminalClaimed]:!0,[h.TerminalTitleChanged]:!0,[h.TerminalCwdChanged]:!1,[h.TerminalExited]:!1,[h.TerminalCleared]:!0,[h.TerminalCommandDetectionAvailable]:!1,[h.TerminalCommandExecuted]:!1,[h.TerminalCommandFinished]:!1,[h.ResourceWatchChanged]:!1,[h.AutomationCreateRequested]:!0,[h.AutomationUpdateRequested]:!0,[h.AutomationSet]:!1,[h.AutomationRemoved]:!0,[h.AutomationRunLifecycleChanged]:!1,[h.AutomationRunSessionSet]:!1,[h.AutomationRunSessionRemoved]:!1,[h.AutomationRunPrimarySessionChanged]:!1,[h.AutomationRunCancelRequested]:!0};var em=["channel/credit","tcp/reset","unsubscribe"],QS=new Set(em);var ra;(function(e){e.Posix="posix",e.Windows="windows"})(ra||(ra={}));var na;(function(e){e.Replay="replay",e.Snapshot="snapshot"})(na||(na={}));var oa;(function(e){e.Base64="base64",e.Utf8="utf-8"})(oa||(oa={}));var sa;(function(e){e.Truncate="truncate",e.Append="append",e.Insert="insert"})(sa||(sa={}));var ia;(function(e){e.File="file",e.Directory="directory",e.Symlink="symlink"})(ia||(ia={}));var aa;(function(e){e.McpServer="mcpServer"})(aa||(aa={}));var ca;(function(e){e.UserMessage="userMessage"})(ca||(ca={}));var ua;(function(e){e.Fork="fork",e.SideChat="sideChat"})(ua||(ua={}));var da;(function(e){e.Session="session",e.NewSession="newSession"})(da||(da={}));var la;(function(e){e.Resource="resource",e.Range="range"})(la||(la={}));var fa;(function(e){e.Required="required",e.Expired="expired"})(fa||(fa={}));var kv=Object.freeze(["1.0.0","0.9.0"]);var Cv={[h.RootAgentsChanged]:"0.1.0",[h.RootActiveSessionsChanged]:"0.1.0",[h.SessionReady]:"0.1.0",[h.SessionCreationFailed]:"0.1.0",[h.SessionChatAdded]:"0.4.0",[h.SessionChatRemoved]:"0.4.0",[h.SessionChatUpdated]:"0.4.0",[h.SessionChatsReordered]:"0.9.0",[h.SessionDefaultChatChanged]:"0.4.0",[h.SessionTitleChanged]:"0.1.0",[h.SessionServerToolsChanged]:"0.1.0",[h.SessionActiveClientSet]:"0.5.0",[h.SessionActiveClientRemoved]:"0.5.0",[h.SessionWorkingDirectorySet]:"0.7.0",[h.SessionWorkingDirectoryRemoved]:"0.7.0",[h.SessionWorkingDirectoryReplaced]:"0.8.0",[h.SessionInputNeededSet]:"0.5.1",[h.SessionInputNeededRemoved]:"0.5.1",[h.SessionCustomizationsChanged]:"0.1.0",[h.SessionCustomizationToggled]:"0.1.0",[h.SessionCustomizationUpdated]:"0.1.0",[h.SessionCustomizationRemoved]:"0.2.0",[h.SessionMcpServerStateChanged]:"0.3.0",[h.SessionMcpServerStartRequested]:"0.5.2",[h.SessionMcpServerStopRequested]:"0.5.2",[h.SessionMcpServerBackgroundRequested]:"0.9.0",[h.SessionIsReadChanged]:"0.1.0",[h.SessionIsArchivedChanged]:"0.1.0",[h.SessionActivityChanged]:"0.1.0",[h.SessionChangesetsChanged]:"0.2.0",[h.SessionConfigChanged]:"0.1.0",[h.SessionMetaChanged]:"0.1.0",[h.ChatTurnStarted]:"0.4.0",[h.ChatDelta]:"0.4.0",[h.ChatResponsePart]:"0.4.0",[h.ChatToolCallStart]:"0.4.0",[h.ChatToolCallDelta]:"0.4.0",[h.ChatToolCallReady]:"0.4.0",[h.ChatToolCallConfirmed]:"0.4.0",[h.ChatToolCallComplete]:"0.4.0",[h.ChatToolCallResultConfirmed]:"0.4.0",[h.ChatToolCallContentChanged]:"0.4.0",[h.ChatToolCallAuthRequired]:"0.6.0",[h.ChatToolCallAuthResolved]:"0.6.0",[h.ChatTurnComplete]:"0.4.0",[h.ChatTurnCancelled]:"0.4.0",[h.ChatError]:"0.4.0",[h.ChatTurnResume]:"0.9.0",[h.ChatActivityChanged]:"0.5.0",[h.ChatBackgroundWorkSet]:"0.9.0",[h.ChatBackgroundWorkRemoved]:"0.9.0",[h.ChatMovableChanged]:"0.9.0",[h.ChatChangesetsChanged]:"0.9.0",[h.ChatCanvasesChanged]:"0.10.0",[h.CanvasStateChanged]:"0.10.0",[h.ChatWorkingDirectorySet]:"0.7.0",[h.ChatWorkingDirectoryRemoved]:"0.7.0",[h.ChatUsage]:"0.4.0",[h.ChatReasoning]:"0.4.0",[h.ChatPendingMessageSet]:"0.4.0",[h.ChatPendingMessageRemoved]:"0.4.0",[h.ChatQueuedMessagesReordered]:"0.4.0",[h.ChatDraftChanged]:"0.5.0",[h.ChatIsReadChanged]:"0.9.0",[h.ChatIsArchivedChanged]:"0.9.0",[h.ChatConfigChanged]:"1.1.0",[h.ChatMoved]:"1.1.0",[h.ChatInputRequested]:"0.4.0",[h.ChatInputAnswerChanged]:"0.4.0",[h.ChatInputCompleted]:"0.4.0",[h.ChatTruncated]:"0.4.0",[h.ChatTurnsLoaded]:"0.5.1",[h.ChangesetStatusChanged]:"0.2.0",[h.ChangesetFileSet]:"0.2.0",[h.ChangesetFileRemoved]:"0.2.0",[h.ChangesetFilesReviewChanged]:"0.6.0",[h.ChangesetContentChanged]:"0.4.0",[h.ChangesetOperationsChanged]:"0.2.0",[h.ChangesetOperationStatusChanged]:"0.3.0",[h.ChangesetCleared]:"0.2.0",[h.AnnotationsSet]:"0.4.0",[h.AnnotationsUpdated]:"0.4.0",[h.AnnotationsRemoved]:"0.4.0",[h.AnnotationsEntrySet]:"0.4.0",[h.AnnotationsEntryRemoved]:"0.4.0",[h.RootTerminalsChanged]:"0.1.0",[h.RootConfigChanged]:"0.1.0",[h.TerminalData]:"0.1.0",[h.TerminalInput]:"0.1.0",[h.TerminalResized]:"0.1.0",[h.TerminalClaimed]:"0.1.0",[h.TerminalTitleChanged]:"0.1.0",[h.TerminalCwdChanged]:"0.1.0",[h.TerminalExited]:"0.1.0",[h.TerminalCleared]:"0.1.0",[h.TerminalCommandDetectionAvailable]:"0.1.0",[h.TerminalCommandExecuted]:"0.1.0",[h.TerminalCommandFinished]:"0.1.0",[h.ResourceWatchChanged]:"0.2.0",[h.AutomationCreateRequested]:"0.8.0",[h.AutomationUpdateRequested]:"0.8.0",[h.AutomationSet]:"0.8.0",[h.AutomationRemoved]:"0.8.0",[h.AutomationRunLifecycleChanged]:"0.8.0",[h.AutomationRunSessionSet]:"0.8.0",[h.AutomationRunSessionRemoved]:"0.8.0",[h.AutomationRunPrimarySessionChanged]:"0.8.0",[h.AutomationRunCancelRequested]:"0.8.0"};function zt(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function eo(e,t="|"){return e.map((r)=>no(r)).join(t)}function Mt(e,t){if(typeof t==="bigint")return t.toString();return t}class ha{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Dt(e){return new ha(e)}function pa(e){return e===null||e===void 0}function Or(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ma(e,t){let r=e/t,n=Math.round(r),o=4*Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function fe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Lt(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Te(e){return Lt(e._zod.def)??e._zod.def.shape}function ga(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return fe(this,t,n),n},enumerable:!0,configurable:!0})}function ya(e,t,r){if(t in e)fe(e,t,r);else e[t]=r}function Ye(e,t,r,n){let o=Te(t);for(let s of r){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)ga(e,s,()=>{let a=t._zod.def.shape[s];return n?n(a,s):a});else ya(e,s,n?n(i.value,s):i.value)}}function hm(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)ga(e,r,()=>t[r]);else ya(e,r,n.value)}}function ae(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function _a(e){return JSON.stringify(e)}function wa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var to="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function mt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Sa=Dt(()=>{if(Q.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Xe(e){if(mt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(mt(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function ro(e){if(Xe(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var va=new Set(["string","number","symbol"]);function Fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Se(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function C(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function no(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function xa(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Tr=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),oo={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pm(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s={};return Ye(s,e,Ar(e,t)),Se(e,ae(r,{shape:s,checks:[]}))}function Ar(e,t){let r=Te(e),n=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])n.push(o)}return n}function mm(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(Ar(e,t)),i={};return Ye(i,e,Reflect.ownKeys(Te(e)).filter((a)=>!s.has(a))),Se(e,ae(r,{shape:i,checks:[]}))}function gm(e,t){if(!Xe(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=Te(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Se(e,ae(e._zod.def,{shape:ba(e,t)}))}function ba(e,t){let r={};return Ye(r,e,Reflect.ownKeys(Te(e))),hm(r,t),r}function ym(e,t){if(!Xe(t))throw Error("Invalid input to safeExtend: expected a plain object");return Se(e,ae(e._zod.def,{shape:ba(e,t)}))}function _m(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Ye(r,e,Reflect.ownKeys(Te(e))),Ye(r,t,Reflect.ownKeys(Te(t)));let n=ae(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Se(e,n)}function Ea(e,t,r,n="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(Ar(t,r)):void 0,c={};return Ye(c,t,Reflect.ownKeys(Te(t)),e&&((d,u)=>a&&!a.has(u)?d:new e({type:"optional",innerType:d}))),Se(t,ae(t._zod.def,{shape:c,checks:[]}))}function wm(e,t,r){let n=r?new Set(Ar(t,r)):void 0,o={};return Ye(o,t,Reflect.ownKeys(Te(t)),(s,i)=>n&&!n.has(i)?s:new e({type:"nonoptional",innerType:s})),Se(t,ae(t._zod.def,{shape:o}))}function he(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ia(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ve(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Nt(e){return typeof e==="string"?e:e?.message}function so(e){let t=[];for(let r of e??[]){let n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let o=n.maximum??n.length??n.size;if(o>=0)t.push([o,r])}return t}function $r(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function xe(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Nt(e.inst?._zod.def?.error?.(e))??Nt(s?.(e))??Nt(t?.error?.(e))??Nt(r.customError?.(e))??Nt(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}var Sm=/[\uD800-\uDBFF]/;function Pr(e){let t=e.length;if(!Sm.test(e))return t;let r=t;for(let n=0;n<t-1;n++)if((e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320)r--,n++;return r}function Nr(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ka(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Qe(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}function Ca(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else vm(e,r,n.value)}}function Ae(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function zr(e,t,r){return Ae(e,t,r,!1)}function Ra(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return Ae(this,r,n(this))},set(o){Ae(this,r,o)}})}return t}function vm(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:Ae(this,t,r.bind(this))},set(n){Ae(this,t,n)}})}function xm(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Qn,je=!1,bm={configurable:!0,get(){je=!0;return}};function P(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Qn!==e._zod){Qn=void 0;return}Qn=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,bm);let o=je;je=!1;try{let s=r(this);if(je)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return je=je||o,s}catch(s){throw delete this[t],je=je||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Em(e,t,r,n){let o=xm(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var Im="~constantCatch";function Oa(e){let t=()=>e;return t[Im]=!0,t}var Ta;var io={value:void 0,enumerable:!1},Aa="captureStackTrace"in Error?Error:null;function km(e){let t=Aa;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return Aa=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function _(e,t,r,n){let o={};function s(p){this.def=p,this.constr=l,this.traits=new Set}s.prototype=o;let i=r,a=i&&new WeakSet;function c(p,f){if(!p._zod){io.value=new s(f);try{Object.defineProperty(p,"_zod",io)}finally{io.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,f),a){let y=Object.getPrototypeOf(p),g=p._zod.constr.prototype,w=y;while(w&&w!==g)w=Object.getPrototypeOf(w);let b=w??y;if(!a.has(b))a.add(b),Ca(b,i)}let m=l.prototype;for(let y in m){if(!Object.prototype.hasOwnProperty.call(m,y))continue;if(!(y in p))p[y]=m[y].bind(p)}}let d=n?.Parent??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function l(p){let f=n?.Parent?km(u):this;c(f,p);let m=f._zod.deferred;if(m){for(let g of m)g();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;if(y)y(f);return f}return Object.defineProperty(l,"init",{value:c}),Object.defineProperty(l,Symbol.hasInstance,{value:(p)=>{if(n?.Parent&&p instanceof n.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(l,"name",{value:e}),l}class be extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ut extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Ta=globalThis).__zod_globalConfig??(Ta.__zod_globalConfig={});var Q=globalThis.__zod_globalConfig;function ce(e){if(e)Object.assign(Q,e);return Q}function Cm(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Mt,2)),e.message}function Rm(e){this._zod.message=e}var Om={get:Cm,set:Rm,enumerable:!0,configurable:!0},co={value:void 0,enumerable:!1},$a=new WeakSet([Object.prototype,Error.prototype]),Pa=(e,t)=>{e.name="$ZodError",co.value=t,Object.defineProperty(e,"issues",co),co.value=void 0,Object.defineProperty(e,"message",Om);let r=Object.getPrototypeOf(e);if(!$a.has(r))$a.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Na=_("$ZodError",Pa),Lx=_("$ZodError",Pa,void 0,{Parent:Error});function Tm(e,t,r){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0});else e[t]=r();return e[t]}function za(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)Tm(r,o.path[0],()=>[]).push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Ma(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,d=0;while(d<a.length){let u=a[d],l=d===a.length-1;if(u==="_errors"){if(l)c._errors.push(t(i));d++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[u];if(l)p._errors.push(t(i));c=p,d++}}}};return n(e),r}function Mr(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Dr=(e)=>{let t=(r,n,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new be;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((d)=>xe(d,i,ce())));throw to(c,s?.callee??t),c}return a.value};return t};var Lr=(e)=>{let t=async(r,n,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((d)=>xe(d,i,ce())));throw to(c,s?.callee??t),c}return a.value};return t};var Ur=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new be;return s.issues.length?Da(e,s.issues,o):{success:!0,data:s.value}};function Da(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>xe(o,r,ce()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var Zr=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?Da(e,s.issues,o):{success:!0,data:s.value}};var Am=Symbol.for("zod.compile.invalid"),$m=Symbol.for("zod.compile.fallback"),uo=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==Am)return!0;if(n.definite===!0&&r===void 0)return!1}return Pm(e,t,r)};function Pm(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)n[$m]=!0,s=o({value:t,issues:[]},n);else s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)throw new be;return s.issues.length===0}var lo=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},n);if(o instanceof Promise)o=await o;return o.issues.length===0},La=(e)=>{let t=Dr(e),r=(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(n,o,a,Mr(r,i))};return r};var Ua=(e)=>{let t=Dr(e),r=(n,o,s,i)=>t(n,o,s,Mr(r,i));return r};var Za=(e)=>{let t=Lr(e),r=async(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(n,o,a,Mr(r,i))};return r};var ja=(e)=>{let t=Lr(e),r=async(n,o,s,i)=>await t(n,o,s,Mr(r,i));return r};var Fa=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ur(e)(t,r,o)};var Ha=(e)=>(t,r,n)=>Ur(e)(t,r,n);var Ba=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Zr(e)(t,r,o)};var qa=(e)=>async(t,r,n)=>Zr(e)(t,r,n);var Ga=/^[cC][0-9a-z]{6,}$/,Ka=/^[0-9a-z]+$/,Va=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Wa=/^[0-9a-vA-V]{20}$/,Ja=/^[A-Za-z0-9]{27}$/,Ya=/^[a-zA-Z0-9_-]{21}$/;function Xa(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Qa=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ec=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ho=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var tc=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Nm="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function rc(){return new RegExp(Nm,"u")}var nc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var sc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ic=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ac=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cc=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var uc=/^https?$/,dc=/^\+[1-9]\d{6,14}$/;var lc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function zm(e){return new RegExp(`^${e}$`)}var fc=zm(lc);function fo(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function hc(e){return new RegExp(`^${fo(e)}$`)}function pc(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${fo({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${fo({precision:e.precision})}`:r;return new RegExp(`^${lc}T(?:${n})$`)}var mc=/^[\s\S]{0,}$/;var po=/^-?\d+$/,Zt=/^-?\d+(?:\.\d+)?$/,gc=/^(?:true|false)$/i;var yc=/^[^A-Z]*$/,_c=/^[^a-z]*$/;var V=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var mo=(e)=>{let t=e.value;return!pa(t)&&t.length!==void 0},jr={number:"number",bigint:"bigint",object:"date"},go=_("$ZodCheckLessThan",(e,t)=>{V.init(e,t);let r=jr[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:jr[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yo=_("$ZodCheckGreaterThan",(e,t)=>{V.init(e,t);let r=jr[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:jr[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wc=_("$ZodCheckMultipleOf",(e,t)=>{V.init(e,t),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):ma(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Sc=_("$ZodCheckNumberFormat",(e,t)=>{V.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Tr[t.format];e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var vc=_("$ZodCheckMaxLength",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=mo),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>t.maximum?Pr(o):s)<=t.maximum)return;let a=Nr(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),xc=_("$ZodCheckMinLength",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=mo),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?Pr(o):s)>=t.minimum)return;let a=Nr(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bc=_("$ZodCheckLengthEquals",(e,t)=>{var r;V.init(e,t),(r=e._zod.def).when??(r.when=mo),e._zod.check=(n)=>{let o=n.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?Pr(o):s;if(i===t.length)return;let a=Nr(o),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ft=_("$ZodCheckStringFormat",(e,t)=>{var r,n;if(V.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Ec=_("$ZodCheckRegex",(e,t)=>{Ft.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ic=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=yc),Ft.init(e,t)}),kc=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=_c),Ft.init(e,t)}),Cc=_("$ZodCheckIncludes",(e,t)=>{V.init(e,t);let r=Fe(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Rc=_("$ZodCheckStartsWith",(e,t)=>{V.init(e,t);let r=new RegExp(`^${Fe(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Oc=_("$ZodCheckEndsWith",(e,t)=>{V.init(e,t);let r=new RegExp(`.*${Fe(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Tc=_("$ZodCheckOverwrite",(e,t)=>{V.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class _o{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
8
8
  `).filter((s)=>s),n=Math.min(...r.map((s)=>s.length-s.trimStart().length)),o=r.map((s)=>s.slice(n)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
9
9
  ${t.join(`
10
10
  `)}
11
- };`)(...Object.values(this.closed))}}var $c={major:4,minor:6,patch:7};var M=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=$c;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,c,d)=>{if(a.memo)return a;let u=he(a),l;for(let p of c){if(p._zod.def.when){if(Ia(a))continue;if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,m=p._zod.check(a);if(m instanceof Promise&&d?.async===!1)throw new be;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{if(await m,a.issues.length===f)return;if($r(a.issues,f,e),!u)u=he(a,f)});else{if(a.issues.length===f)continue;if($r(a.issues,f,e),!u)u=he(a,f)}}if(l)return l.then(()=>a);return a},i=(a,c,d)=>{if(he(a))return a.aborted=!0,a;let u=s(c,o,d);if(u instanceof Promise){if(d.async===!1)throw new be;return u.then((l)=>e._zod.parse(l,d))}return e._zod.parse(u,d)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((l)=>i(l,a,c));return i(u,a,c)}let d=e._zod.parse(a,c);if(d instanceof Promise){if(c.async===!1)throw new be;return d.then((u)=>s(u,o,c))}return s(d,o,c)}}},{get "~standard"(){return zr(this,"~standard",wo(this))},set "~standard"(e){Ae(this,"~standard",e)}}),Gc=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>xe(r,t,ce()))}:{value:e.value};async function Nm(e,t){let r={async:!0};return Gc(await e._zod.run({value:t,issues:[]},r),r)}function wo(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Gc(n,r)}catch(n){}return Nm(e,t)},vendor:"zod",version:1}}var qr=_("$ZodString",(e,t)=>{M.init(e,t),e._zod.pattern=t.pattern??mc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),L=_("$ZodStringFormat",(e,t)=>{Ft.init(e,t),qr.init(e,t)}),Kc=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ec),L.init(e,t)}),Vc=_("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=fo(n))}else t.pattern??(t.pattern=fo());L.init(e,t)}),Wc=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tc),L.init(e,t)}),Jc=1,Hr=2;function Yc(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function zm(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Yc(e)||Hr;return Mm(e,t)}function Mm(e,t){if(!t.normalize&&t.protocol?.source===uc.source&&!/^https?:\/\//i.test(e))return Jc;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??Hr}return new URL(e)}catch{return Hr}}var Dm=/[\t\n\r]/g;function Pc(e){return e.replace(Dm,"")}function Lm(e,t){return t.lastIndex=0,t.test(e.hostname)}function Um(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Xc=_("$ZodURL",(e,t)=>{L.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=zm(n,t);if(o===Jc){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===Hr){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=Pc(n);return}if(t.hostname&&!Lm(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!Um(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:Pc(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Qc=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rc()),L.init(e,t)}),eu=_("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Ya:Xa(t.length)),L.init(e,t)}),tu=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ga),L.init(e,t)}),ru=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ka),L.init(e,t)}),nu=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Va),L.init(e,t)}),ou=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Wa),L.init(e,t)}),su=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ja),L.init(e,t)}),iu=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=pc(t)),L.init(e,t)}),au=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fc),L.init(e,t)}),cu=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hc(t)),L.init(e,t)}),uu=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qa),L.init(e,t)}),du=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=nc),L.init(e,t)}),Zm=/^[0-9a-fA-F:.]+$/;function lu(e){if(!Zm.test(e))return!1;return Yc(`http://[${e}]`)}var fu=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=oc),L.init(e,t),e._zod.check=(r)=>{if(!lu(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var hu=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=sc),L.init(e,t)});function jm(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let o=Number(n);if(`${o}`!==n)return!1;if(o<0||o>128)return!1;return lu(r)}var pu=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ic),L.init(e,t),e._zod.check=(r)=>{if(!jm(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function mu(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var So=/^[0-9a-zA-Z+/]*={0,2}$/,gu=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=So),L.init(e,t),e._zod.check=(r)=>{if(mu(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Gr=/^[A-Za-z0-9_-]*$/;function Fm(e){if(!Gr.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return mu(r)}var yu=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gr),L.init(e,t),e._zod.check=(r)=>{if(Fm(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),_u=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dc),L.init(e,t)});function Hm(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var wu=_("$ZodJWT",(e,t)=>{L.init(e,t),e._zod.check=(r)=>{if(Hm(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var vo=_("$ZodNumber",(e,t)=>{M.init(e,t),e._zod.pattern=Zt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Su=_("$ZodNumberFormat",(e,t)=>{Sc.init(e,t),vo.init(e,t)}),vu=_("$ZodBoolean",(e,t)=>{M.init(e,t),e._zod.pattern=gc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var xu=_("$ZodUnknown",(e,t)=>{M.init(e,t),e._zod.parse=(r)=>r}),bu=_("$ZodNever",(e,t)=>{M.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Bm(e,t){let r=oo(e._zod.def.checks);if(!r.length)return;let n=Math.min(...r.map((s)=>s[0])),o=e._zod.parse;e._zod.parse=(s,i)=>{let a=t(s.value);if(a>n&&!i?.skipChecks&&i?.direction!=="backward"){for(let[c,d]of oo(e._zod.def.checks))if(a>c&&d._zod.def.when(s)){let u=s.issues.length;return d._zod.check(s),s.issues[u].continue=!1,$r(s.issues,u,e),s}}return o(s,i)}}var qm=(e)=>Array.isArray(e)?e.length:-1;function Nc(e,t,r){if(e.issues.length)t.issues.push(...ve(r,e.issues));t.value[r]=e.value}var Eu=_("$ZodArray",(e,t)=>{M.init(e,t);let r=Q.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=r?r.alloc(e,n,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let c=0;c<s.length;c++){let d=s[c],u=t.element._zod.run({value:d,issues:[]},o);if(u instanceof Promise)i.push(u.then((l)=>Nc(l,n,c)));else if(Nc(u,n,c),a&&u.issues.length!==0&&he(u))break}if(i.length)return Promise.all(i).then(()=>n);return n},Bm(e,qm)});function Br(e,t,r,n,o,s){let i=r in n,a=s==="optional";if(!i&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...ve(r,e.issues))}if(!i&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var Gm=[];function Iu(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:Gm,o=n.length?[...t,...n]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=xa(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function ku(e,t,r,n,o,s,i){let a=[],c=o.keySet,d=o.catchall._zod,u=d.def.type,{optin:l,optout:p}=d,f=0;for(let m in t){if(i&&r.issues.length!==f){if(he(r,f))break;f=r.issues.length}if(c.has(m))continue;if(m==="__proto__"){if(u==="never")a.push(m);continue}if(u==="never"){a.push(m);continue}let y=d.run({value:t[m],issues:[]},n);if(y instanceof Promise)e.push(y.then((g)=>Br(g,r,m,t,l,p)));else Br(y,r,m,t,l,p)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var Km=_("$ZodObject",(e,t)=>{M.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let d=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=n,Object.defineProperty(t,"shape",{get:d})}let o=Dt(()=>Iu(t));P(e,"propValues",(d)=>{let u=d.def.shape,l={};for(let p in u){let f=u[p]._zod;if(f.values){if(!Object.prototype.hasOwnProperty.call(l,p))fe(l,p,new Set);for(let m of f.values)l[p].add(m);if(f.optin!==void 0)l[p].add(void 0)}}return l});let s=gt,i=t.catchall,a,c=Q.memoizer;c?.attach(e),e._zod.parse=(d,u)=>{a??(a=o.value);let l=d.value;if(!s(l))return d.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),d;d.value=c?c.alloc(e,d,{},u):{};let p=[],f=a.shape,m=u?.abortEarly,y=d.issues.length;for(let g of a.allKeys){if(m&&d.issues.length!==y){if(he(d,y))break;y=d.issues.length}if(g==="__proto__")continue;let w=f[g],b=w._zod.optin,v=w._zod.optout,x=w._zod.run({value:l[g],issues:[]},u);if(x instanceof Promise)p.push(x.then((I)=>Br(I,d,g,l,b,v)));else Br(x,d,g,l,b,v)}if(!i)return p.length?Promise.all(p).then(()=>d):d;return ku(p,l,d,u,o.value,e,m===!0)}}),Ru=_("$ZodObjectJIT",(e,t)=>{Km.init(e,t);let r=e._zod.parse,n=Dt(()=>Iu(t)),o=Q.memoizer,s=(f)=>{let m=n.value,y=m.symbolKeys,g=new yo(["payload","ctx"],{shape:f,inst:e,memo:o,syms:y}),w=(I)=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,b=(I,C)=>`
11
+ };`)(...Object.values(this.closed))}}var $c={major:4,minor:6,patch:7};var z=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=$c;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,c,d)=>{if(a.memo)return a;let u=he(a),l;for(let p of c){if(p._zod.def.when){if(Ia(a))continue;if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,m=p._zod.check(a);if(m instanceof Promise&&d?.async===!1)throw new be;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{if(await m,a.issues.length===f)return;if($r(a.issues,f,e),!u)u=he(a,f)});else{if(a.issues.length===f)continue;if($r(a.issues,f,e),!u)u=he(a,f)}}if(l)return l.then(()=>a);return a},i=(a,c,d)=>{if(he(a))return a.aborted=!0,a;let u=s(c,o,d);if(u instanceof Promise){if(d.async===!1)throw new be;return u.then((l)=>e._zod.parse(l,d))}return e._zod.parse(u,d)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((l)=>i(l,a,c));return i(u,a,c)}let d=e._zod.parse(a,c);if(d instanceof Promise){if(c.async===!1)throw new be;return d.then((u)=>s(u,o,c))}return s(d,o,c)}}},{get "~standard"(){return zr(this,"~standard",So(this))},set "~standard"(e){Ae(this,"~standard",e)}}),Gc=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>xe(r,t,ce()))}:{value:e.value};async function Mm(e,t){let r={async:!0};return Gc(await e._zod.run({value:t,issues:[]},r),r)}function So(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Gc(n,r)}catch(n){}return Mm(e,t)},vendor:"zod",version:1}}var qr=_("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=t.pattern??mc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),D=_("$ZodStringFormat",(e,t)=>{Ft.init(e,t),qr.init(e,t)}),Kc=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ec),D.init(e,t)}),Vc=_("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ho(n))}else t.pattern??(t.pattern=ho());D.init(e,t)}),Wc=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tc),D.init(e,t)}),Jc=1,Hr=2;function Yc(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function Dm(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Yc(e)||Hr;return Lm(e,t)}function Lm(e,t){if(!t.normalize&&t.protocol?.source===uc.source&&!/^https?:\/\//i.test(e))return Jc;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??Hr}return new URL(e)}catch{return Hr}}var Um=/[\t\n\r]/g;function Pc(e){return e.replace(Um,"")}function Zm(e,t){return t.lastIndex=0,t.test(e.hostname)}function jm(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Xc=_("$ZodURL",(e,t)=>{D.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=Dm(n,t);if(o===Jc){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===Hr){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=Pc(n);return}if(t.hostname&&!Zm(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!jm(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:Pc(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Qc=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=rc()),D.init(e,t)}),eu=_("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Ya:Xa(t.length)),D.init(e,t)}),tu=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ga),D.init(e,t)}),ru=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ka),D.init(e,t)}),nu=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Va),D.init(e,t)}),ou=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Wa),D.init(e,t)}),su=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ja),D.init(e,t)}),iu=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=pc(t)),D.init(e,t)}),au=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fc),D.init(e,t)}),cu=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hc(t)),D.init(e,t)}),uu=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qa),D.init(e,t)}),du=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=nc),D.init(e,t)}),Fm=/^[0-9a-fA-F:.]+$/;function lu(e){if(!Fm.test(e))return!1;return Yc(`http://[${e}]`)}var fu=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=oc),D.init(e,t),e._zod.check=(r)=>{if(!lu(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var hu=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=sc),D.init(e,t)});function Hm(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let o=Number(n);if(`${o}`!==n)return!1;if(o<0||o>128)return!1;return lu(r)}var pu=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ic),D.init(e,t),e._zod.check=(r)=>{if(!Hm(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function mu(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var vo=/^[0-9a-zA-Z+/]*={0,2}$/,gu=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=vo),D.init(e,t),e._zod.check=(r)=>{if(mu(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Gr=/^[A-Za-z0-9_-]*$/;function Bm(e){if(!Gr.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return mu(r)}var yu=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gr),D.init(e,t),e._zod.check=(r)=>{if(Bm(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),_u=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dc),D.init(e,t)});function qm(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var wu=_("$ZodJWT",(e,t)=>{D.init(e,t),e._zod.check=(r)=>{if(qm(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var xo=_("$ZodNumber",(e,t)=>{z.init(e,t),e._zod.pattern=Zt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Su=_("$ZodNumberFormat",(e,t)=>{Sc.init(e,t),xo.init(e,t)}),vu=_("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=gc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var xu=_("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=(r)=>r}),bu=_("$ZodNever",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Gm(e,t){let r=so(e._zod.def.checks);if(!r.length)return;let n=Math.min(...r.map((s)=>s[0])),o=e._zod.parse;e._zod.parse=(s,i)=>{let a=t(s.value);if(a>n&&!i?.skipChecks&&i?.direction!=="backward"){for(let[c,d]of so(e._zod.def.checks))if(a>c&&d._zod.def.when(s)){let u=s.issues.length;return d._zod.check(s),s.issues[u].continue=!1,$r(s.issues,u,e),s}}return o(s,i)}}var Km=(e)=>Array.isArray(e)?e.length:-1;function Nc(e,t,r){if(e.issues.length)t.issues.push(...ve(r,e.issues));t.value[r]=e.value}var Eu=_("$ZodArray",(e,t)=>{z.init(e,t);let r=Q.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=r?r.alloc(e,n,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let c=0;c<s.length;c++){let d=s[c],u=t.element._zod.run({value:d,issues:[]},o);if(u instanceof Promise)i.push(u.then((l)=>Nc(l,n,c)));else if(Nc(u,n,c),a&&u.issues.length!==0&&he(u))break}if(i.length)return Promise.all(i).then(()=>n);return n},Gm(e,Km)});function Br(e,t,r,n,o,s){let i=r in n,a=s==="optional";if(!i&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...ve(r,e.issues))}if(!i&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var Vm=[];function Iu(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:Vm,o=n.length?[...t,...n]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=xa(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function ku(e,t,r,n,o,s,i){let a=[],c=o.keySet,d=o.catchall._zod,u=d.def.type,{optin:l,optout:p}=d,f=0;for(let m in t){if(i&&r.issues.length!==f){if(he(r,f))break;f=r.issues.length}if(c.has(m))continue;if(m==="__proto__"){if(u==="never")a.push(m);continue}if(u==="never"){a.push(m);continue}let y=d.run({value:t[m],issues:[]},n);if(y instanceof Promise)e.push(y.then((g)=>Br(g,r,m,t,l,p)));else Br(y,r,m,t,l,p)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var Wm=_("$ZodObject",(e,t)=>{z.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let d=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=n,Object.defineProperty(t,"shape",{get:d})}let o=Dt(()=>Iu(t));P(e,"propValues",(d)=>{let u=d.def.shape,l={};for(let p in u){let f=u[p]._zod;if(f.values){if(!Object.prototype.hasOwnProperty.call(l,p))fe(l,p,new Set);for(let m of f.values)l[p].add(m);if(f.optin!==void 0)l[p].add(void 0)}}return l});let s=mt,i=t.catchall,a,c=Q.memoizer;c?.attach(e),e._zod.parse=(d,u)=>{a??(a=o.value);let l=d.value;if(!s(l))return d.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),d;d.value=c?c.alloc(e,d,{},u):{};let p=[],f=a.shape,m=u?.abortEarly,y=d.issues.length;for(let g of a.allKeys){if(m&&d.issues.length!==y){if(he(d,y))break;y=d.issues.length}if(g==="__proto__")continue;let w=f[g],b=w._zod.optin,v=w._zod.optout,x=w._zod.run({value:l[g],issues:[]},u);if(x instanceof Promise)p.push(x.then((I)=>Br(I,d,g,l,b,v)));else Br(x,d,g,l,b,v)}if(!i)return p.length?Promise.all(p).then(()=>d):d;return ku(p,l,d,u,o.value,e,m===!0)}}),Cu=_("$ZodObjectJIT",(e,t)=>{Wm.init(e,t);let r=e._zod.parse,n=Dt(()=>Iu(t)),o=Q.memoizer,s=(f)=>{let m=n.value,y=m.symbolKeys,g=new _o(["payload","ctx"],{shape:f,inst:e,memo:o,syms:y}),w=(I)=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,b=(I,R)=>`
12
12
  let ${I}_ab = false;
13
13
  for (let i = 0; i < ${I}.issues.length; i++) {
14
14
  const iss = ${I}.issues[i];
15
- iss.path = iss.path ? [${C}, ...iss.path] : [${C}];
15
+ iss.path = iss.path ? [${R}, ...iss.path] : [${R}];
16
16
  payload.issues.push(iss);
17
17
  if (iss.continue !== true) ${I}_ab = true;
18
18
  }
19
19
  if (${I}_ab && ctx && ctx.abortEarly) {
20
20
  payload.value = newResult;
21
21
  return payload;
22
- }`;g.write("const input = payload.value;");let v=Object.create(null),x=0;for(let I of m.allKeys)v[I]=`key_${x++}`;g.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let I of m.allKeys){if(I==="__proto__")continue;let C=v[I],E=typeof I==="symbol"?`syms[${y.indexOf(I)}]`:_a(I),A=`${E} in input`,q=f[I],ke=q?._zod?.optin,re=ke!==void 0,Ne=q?._zod?.optout==="optional";if(g.write(`const ${C} = ${w(E)};`),re&&Ne){let dr=ke==="optional"?`${C}_present`:`${C}.value !== undefined || ${C}_present`;g.write(`
23
- const ${C}_present = ${A};
24
- if (!${C}.issues.length || ${C}_present) {
25
- if (${C}.issues.length) {${b(C,E)}
22
+ }`;g.write("const input = payload.value;");let v=Object.create(null),x=0;for(let I of m.allKeys)v[I]=`key_${x++}`;g.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let I of m.allKeys){if(I==="__proto__")continue;let R=v[I],E=typeof I==="symbol"?`syms[${y.indexOf(I)}]`:_a(I),A=`${E} in input`,q=f[I],ke=q?._zod?.optin,re=ke!==void 0,Ne=q?._zod?.optout==="optional";if(g.write(`const ${R} = ${w(E)};`),re&&Ne){let dr=ke==="optional"?`${R}_present`:`${R}.value !== undefined || ${R}_present`;g.write(`
23
+ const ${R}_present = ${A};
24
+ if (!${R}.issues.length || ${R}_present) {
25
+ if (${R}.issues.length) {${b(R,E)}
26
26
  }
27
27
 
28
28
  if (${dr}) {
29
- newResult[${E}] = ${C}.value;
29
+ newResult[${E}] = ${R}.value;
30
30
  }
31
31
  }
32
32
 
33
33
  `)}else if(!re)g.write(`
34
- const ${C}_present = ${A};
35
- if (${C}.issues.length) {${b(C,E)}
34
+ const ${R}_present = ${A};
35
+ if (${R}.issues.length) {${b(R,E)}
36
36
  }
37
- if (!${C}_present && !${C}.issues.length) {
37
+ if (!${R}_present && !${R}.issues.length) {
38
38
  payload.issues.push({
39
39
  code: "invalid_type",
40
40
  expected: "nonoptional",
@@ -47,34 +47,34 @@ ${t.join(`
47
47
  }
48
48
  }
49
49
 
50
- if (${C}_present) {
51
- newResult[${E}] = ${C}.value;
50
+ if (${R}_present) {
51
+ newResult[${E}] = ${R}.value;
52
52
  }
53
53
 
54
54
  `);else if(g.write(`
55
- if (${C}.issues.length) {${b(C,E)}
55
+ if (${R}.issues.length) {${b(R,E)}
56
56
  }
57
- `),ke==="defaulted")g.write(`newResult[${E}] = ${C}.value;`);else g.write(`
58
- if (${C}.value !== undefined || ${A}) {
59
- newResult[${E}] = ${C}.value;
57
+ `),ke==="defaulted")g.write(`newResult[${E}] = ${R}.value;`);else g.write(`
58
+ if (${R}.value !== undefined || ${A}) {
59
+ newResult[${E}] = ${R}.value;
60
60
  }
61
- `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},i,a=gt,c=!Q.jitless,u=c&&Sa.value,l=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=n.value);let y=f.value;if(!a(y))return f.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),f;if(c&&u&&m?.async===!1&&m.jitless!==!0){if(!i)i=s(t.shape);if(f=i(f,m),!l)return f;return ku([],y,f,m,p,e,m?.abortEarly===!0)}return r(f,m)}});function zc(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!he(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>xe(i,n,ce())))}),t}var xo=_("$ZodUnion",(e,t)=>{M.init(e,t),P(e,"optin",(n)=>n.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),P(e,"optout",(n)=>n.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),P(e,"values",(n)=>{if(n.def.options.every((o)=>o._zod.values))return new Set(n.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),P(e,"pattern",(n)=>{if(n.def.options.every((o)=>o._zod.pattern)){let o=n.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>Or(s.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return zc(i,n,e,o);return Promise.all(i).then((a)=>zc(a,n,e,o))}});function Vm(e){let t=new Map;for(let r of e.options){let n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(let o of n)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,r)}return t}var Cu=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,xo.init(e,t);let r=e._zod.parse;P(e,"propValues",(o)=>{let s={},i=0;for(let a of o.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);if(c[o.def.discriminator]?.has(void 0))i++;for(let[d,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,d))fe(s,d,new Set);for(let l of u)s[d].add(l)}}if(!o.def.unionFallback&&i>1)s[o.def.discriminator]?.delete(void 0);return s}),t.options.forEach((o,s)=>{let i=Lt(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let n=Dt(()=>Vm(t));e._zod.parse=(o,s)=>{let i=o.value;if(!gt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],c=n.value.get(a);if(c&&(a!==void 0||s.direction!=="backward"))return c._zod.run(o,s);if(t.unionFallback||s.direction==="backward")return r(o,s);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter((d)=>n.value.get(d)!==null),input:i,path:[t.discriminator],inst:e}),o}}),Ou=_("$ZodIntersection",(e,t)=>{M.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,d])=>Mc(r,c,d));return Mc(r,s,i)}});function _o(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Qe(e)&&Qe(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of n){if(s==="__proto__")continue;let i=_o(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=_o(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mc(e,t,r){let n=new Map,o,s=new Map,i=(d,u)=>{let l;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),l=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let p=String(d.path[0]);if(!s.has(p))s.set(p,d);l=[p]}else return!1;for(let p of l){if(!n.has(p))n.set(p,{});n.get(p)[u]=!0}return!0};for(let d of t.issues)if(!i(d,"l"))e.issues.push(d);for(let d of r.issues)if(!i(d,"r"))e.issues.push(d);let a=[...n].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){let d=o?a.filter((u)=>o.keys.includes(u)):[];if(d.length)e.issues.push({...o,keys:d});for(let u of a)if(!d.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=_o(t.value,r.value);if(!c.valid){if(he(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Tu=_("$ZodTuple",(e,t)=>{M.init(e,t);let r=t.items,n=Q.memoizer;n?.attach(e),e._zod.parse=(o,s)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=n?n.alloc(e,o,[],s):[];let a=[],c=Dc(r,"optin"),d=Dc(r,"optout");if(!t.rest){if(i.length<c)return o.issues.push({code:"too_small",minimum:c,inclusive:!0,input:i,inst:e,origin:"array"}),o;if(i.length>r.length)o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=Array(r.length),l=t.rest?s?.abortEarly:void 0,p=!1;for(let f=0;f<r.length;f++){let m=r[f]._zod.run({value:i[f],issues:[]},s);if(m instanceof Promise)a.push(m.then((y)=>{u[f]=y}));else if(u[f]=m,l&&!p&&m.issues.length)p=he(m)}if(t.rest&&!p){let f=r.length-1,m=i.slice(r.length),y=o.issues.length;for(let g of m){if(l&&o.issues.length!==y){if(he(o,y))break;y=o.issues.length}f++;let w=t.rest._zod.run({value:g,issues:[]},s);if(w instanceof Promise)a.push(w.then((b)=>Lc(b,o,f)));else Lc(w,o,f)}}if(a.length)return Promise.all(a).then(()=>Uc(u,o,r,i,d));return Uc(u,o,r,i,d)}});function Dc(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function Lc(e,t,r){if(e.issues.length)t.issues.push(...ve(r,e.issues));t.value[r]=e.value}function Uc(e,t,r,n,o){for(let s=0;s<r.length;s++){let i=e[s],a=s<n.length;if(!a&&s>=o&&r[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=o){t.value.length=s;break}t.issues.push(...ve(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=n.length;s--)if(r[s]._zod.optout==="optional"&&t.value[s]===void 0)t.value.length=s;else break;return t}var Au=_("$ZodRecord",(e,t)=>{M.init(e,t);let r=Q.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Qe(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let l=t.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>xe(m,o,ce())),input:u,path:[u],inst:e});continue}let p=l.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(u,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(u,f.issues));n.value[p]=f.value}}let d;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=s[u]}else d=d??[],d.push(u);if(d&&d.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let d of Reflect.ownKeys(s)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&Zt.test(d)&&u.issues.length){let m=t.keyType._zod.run({value:Number(d),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)u=m}if(u.issues.length){if(t.mode==="loose")n.value[d]=s[d];else if(a)c=c??[],c.push(d);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((m)=>xe(m,o,ce())),input:d,path:[d],inst:e});continue}let p=u.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[d],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(d,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(d,f.issues));n.value[p]=f.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}});var $u=_("$ZodEnum",(e,t)=>{M.init(e,t);let r=zt(t.entries),n=new Set(r);e._zod.values=n,P(e,"pattern",(o)=>{let s=zt(o.def.entries).filter((i)=>va.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>Fe(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Pu=_("$ZodLiteral",(e,t)=>{M.init(e,t);let r=new Set(t.values);e._zod.values=r,P(e,"pattern",(n)=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map((s)=>typeof s==="string"?Fe(s):s?Fe(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var Nu=_("$ZodTransform",(e,t)=>{M.init(e,t),e._zod.optin="optional",Q.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r));if(o instanceof Promise)throw new be;return r.value=o,r}});function Zc(e,t){return e.value=t.issues.length?void 0:t.value,e}var bo=_("$ZodOptional",(e,t)=>{M.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Zc(r,s));return Zc(r,o)}return t.innerType._zod.run(r,n)}}),zu=_("$ZodExactOptional",(e,t)=>{bo.init(e,t),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Mu=_("$ZodNullable",(e,t)=>{M.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)}|null)$`):void 0}),P(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Du=_("$ZodDefault",(e,t)=>{M.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>jc(s,t));return jc(o,t)}});function jc(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Lu=_("$ZodPrefault",(e,t)=>{M.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Uu=_("$ZodNonOptional",(e,t)=>{M.init(e,t),P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fc(s,e));return Fc(o,e)}});function Fc(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Hc(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>xe(o,n,ce()))},input:e.value}),e}var Zu=_("$ZodCatch",(e,t)=>{M.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Hc(r,s,t,n));return Hc(r,o,t,n)}});var ju=_("$ZodPipe",(e,t)=>{M.init(e,t),P(e,"values",(r)=>r.def.in._zod.values),P(e,"optin",(r)=>r.def.in._zod.optin),P(e,"optout",(r)=>r.def.out._zod.optout),P(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>Fr(i,t.in,n));return Fr(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fr(s,t.out,n));return Fr(o,t.out,n)}});function Fr(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}var Fu=_("$ZodReadonly",(e,t)=>{M.init(e,t),P(e,"propValues",(r)=>r.def.innerType._zod.propValues),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"optin",(r)=>r.def.innerType?._zod?.optin),P(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(Bc);return Bc(o)}});function Bc(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Hu=_("$ZodCustom",(e,t)=>{V.init(e,t),M.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>qc(s,r,n,e));qc(o,r,n,e);return}});function qc(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(et(o))}}class qu extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Io="~memo",Bu=[];function Gu(e){return e!==null&&typeof e==="object"}function Eo(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ku=new WeakMap,Ht=0,Wr=1,Bt=2;function Jr(e,t,r){let n=Ku.get(e);if(n!==void 0)return n?Bt:Ht;if(t.has(e))return Bt;t.add(e);let o=Ht,s=(u)=>{if(o!==Bt&&u?._zod){let l=Jr(u,t,r);if(l>o)o=l}},i=(u,l)=>{let p=Ht;for(let f of Reflect.ownKeys(u)){let m=Object.getOwnPropertyDescriptor(u,f);if(l&&!m.enumerable)continue;let y=m.get?Wr:m.value?._zod?Jr(m.value,t,r):Ht;if(y>p)p=y}return p},a=(u)=>{if(u>o)o=u},c=e._zod.def,d=c.type;switch(d){case"object":{let u=Lt(c);a(u?i(u,!0):Wr),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Jr(u,t,!1):Wr);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let l=Object.getOwnPropertyDescriptor(c,u);if(!l||l.get)continue;let p=l.value;if(!p||typeof p!=="object")continue;if(p._zod)s(p);else if(Array.isArray(p))for(let f of p)s(f)}}return t.delete(e),Wm(e,o)}function Wm(e,t){if(t!==Wr)Ku.set(e,t===Bt);return t}function Jm(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var Kr,Vr=[],Ym={alloc(e,t,r){let n=Kr;if(!n)return r;Kr=void 0;let o={value:r,issues:null};return n.set(t.value,o),Vr.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,s)=>{if(s.direction!=="backward"&&Xm(s,o.value))throw new qu;return r(o,s)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,d)=>{if(r===void 0){let w=Jr(e,new Set,!1);if(w===Ht){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,d)}if(w===Bt||n)r=!0;else n=!0}let u=c.value;if(!Gu(u))return i(c,d);let l=d[Io];if(!l)l={buckets:new WeakMap,backEdges:void 0},d[Io]=l;let p;if(o===d)p=s;else p=Jm(l,e),o=d,s=p;let f=p.get(u);if(f){if(c.value=f.value,f.issues){if(f.issues.length)c.issues.push(...Eo(f.issues))}else c.memo=!0,l.backEdges??(l.backEdges=new WeakSet),l.backEdges.add(f.value);return c}Kr=p;let m=Vr.length,y=i(c,d);Kr=void 0;let g=Vr.length>m?Vr.pop():void 0;if(y instanceof Promise)return y.then((w)=>{if(g)g.issues=w.issues.length?Eo(w.issues):Bu;return w});if(g)g.issues=y.issues.length?Eo(y.issues):Bu;return y};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function Vu(){return Ym}function Xm(e,t){let r=e[Io]?.backEdges;return r!==void 0&&Gu(t)&&r.has(t)}var Qm=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=ka(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${ro(s.values[0])}`;return`Invalid option: expected one of ${Qn(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Qn(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((a)=>`'${a}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function ko(){return{localeError:Qm()}}var Wu;class Ju{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function eg(){return new Ju}(Wu=globalThis).__zod_globalRegistry??(Wu.__zod_globalRegistry=eg());var tt=globalThis.__zod_globalRegistry;function Yu(e){if(e.checks)e.checks=[...e.checks];return e}function Xu(e,t){return new e(Yu({type:"string",...R(t)}))}function Qu(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function ed(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function td(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function sd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function id(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function ad(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function cd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function ud(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function dd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function ld(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function fd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function hd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function pd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function md(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function gd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function _d(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function wd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function Sd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function vd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function xd(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function bd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Ed(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function Id(e,t){return new e(Yu({type:"number",checks:[],...R(t)}))}function kd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function Rd(e,t){return new e({type:"boolean",...R(t)})}function Cd(e){return new e({type:"unknown"})}function Od(e,t){return new e({type:"never",...R(t)})}function Yr(e,t){return new mo({check:"less_than",...R(t),value:e,inclusive:!1})}function qt(e,t){return new mo({check:"less_than",...R(t),value:e,inclusive:!0})}function Xr(e,t){return new go({check:"greater_than",...R(t),value:e,inclusive:!1})}function Gt(e,t){return new go({check:"greater_than",...R(t),value:e,inclusive:!0})}function Qr(e,t){return new wc({check:"multiple_of",...R(t),value:e})}function en(e,t){return new vc({check:"max_length",...R(t),maximum:e})}function yt(e,t){return new xc({check:"min_length",...R(t),minimum:e})}function tn(e,t){return new bc({check:"length_equals",...R(t),length:e})}function Ro(e,t){return new Ec({check:"string_format",format:"regex",...R(t),pattern:e})}function Co(e){return new Ic({check:"string_format",format:"lowercase",...R(e)})}function Oo(e){return new kc({check:"string_format",format:"uppercase",...R(e)})}function To(e,t){return new Rc({check:"string_format",format:"includes",...R(t),includes:e})}function Ao(e,t){return new Cc({check:"string_format",format:"starts_with",...R(t),prefix:e})}function $o(e,t){return new Oc({check:"string_format",format:"ends_with",...R(t),suffix:e})}function He(e){return new Tc({check:"overwrite",tx:e})}function Po(e){return He((t)=>t.normalize(e))}function No(){return He((e)=>e.trim())}function zo(){return He((e)=>e.toLowerCase())}function Mo(){return He((e)=>e.toUpperCase())}function Do(){return He((e)=>wa(e))}function Td(e,t,r){return new e({type:"array",element:t,...R(r)})}function Ad(e,t,r){return new e({type:"custom",check:"custom",fn:t,...R(r)})}function $d(e,t){let r=tg((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(et(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(et(s))}},e(n.value,n)),t);return r}function tg(e,t){let r=new V({check:"custom",...R(t)});return r._zod.check=e,r}function Kt(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))fe(e,n,r[n]);return e}function Uo(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??tt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function $e(e,t,r,n,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(r,s),!0}function j(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[o.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,u)}let l=e._zod.parent;if(l){if(!i.ref)i.ref=l;j(l,t,u),t.seen.get(l).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Kt(i.schema,c);if(t.io==="input"&&ee(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Pd(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Zo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,p=e.external.uri??((m)=>m);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${Pd(f)}`}}let c="#",d=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+Pd(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:d}=o(i);if(a.def={...a.schema},d)a.defId=d;let u=a.schema;for(let l in u)delete u[l];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
61
+ `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},i,a=mt,c=!Q.jitless,u=c&&Sa.value,l=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=n.value);let y=f.value;if(!a(y))return f.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),f;if(c&&u&&m?.async===!1&&m.jitless!==!0){if(!i)i=s(t.shape);if(f=i(f,m),!l)return f;return ku([],y,f,m,p,e,m?.abortEarly===!0)}return r(f,m)}});function zc(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!he(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>xe(i,n,ce())))}),t}var bo=_("$ZodUnion",(e,t)=>{z.init(e,t),P(e,"optin",(n)=>n.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),P(e,"optout",(n)=>n.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),P(e,"values",(n)=>{if(n.def.options.every((o)=>o._zod.values))return new Set(n.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),P(e,"pattern",(n)=>{if(n.def.options.every((o)=>o._zod.pattern)){let o=n.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>Or(s.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return zc(i,n,e,o);return Promise.all(i).then((a)=>zc(a,n,e,o))}});function Jm(e){let t=new Map;for(let r of e.options){let n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(let o of n)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,r)}return t}var Ru=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,bo.init(e,t);let r=e._zod.parse;P(e,"propValues",(o)=>{let s={},i=0;for(let a of o.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);if(c[o.def.discriminator]?.has(void 0))i++;for(let[d,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,d))fe(s,d,new Set);for(let l of u)s[d].add(l)}}if(!o.def.unionFallback&&i>1)s[o.def.discriminator]?.delete(void 0);return s}),t.options.forEach((o,s)=>{let i=Lt(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let n=Dt(()=>Jm(t));e._zod.parse=(o,s)=>{let i=o.value;if(!mt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],c=n.value.get(a);if(c&&(a!==void 0||s.direction!=="backward"))return c._zod.run(o,s);if(t.unionFallback||s.direction==="backward")return r(o,s);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter((d)=>n.value.get(d)!==null),input:i,path:[t.discriminator],inst:e}),o}}),Ou=_("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,d])=>Mc(r,c,d));return Mc(r,s,i)}});function wo(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Xe(e)&&Xe(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of n){if(s==="__proto__")continue;let i=wo(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=wo(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mc(e,t,r){let n=new Map,o,s=new Map,i=(d,u)=>{let l;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),l=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let p=String(d.path[0]);if(!s.has(p))s.set(p,d);l=[p]}else return!1;for(let p of l){if(!n.has(p))n.set(p,{});n.get(p)[u]=!0}return!0};for(let d of t.issues)if(!i(d,"l"))e.issues.push(d);for(let d of r.issues)if(!i(d,"r"))e.issues.push(d);let a=[...n].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){let d=o?a.filter((u)=>o.keys.includes(u)):[];if(d.length)e.issues.push({...o,keys:d});for(let u of a)if(!d.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=wo(t.value,r.value);if(!c.valid){if(he(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Tu=_("$ZodTuple",(e,t)=>{z.init(e,t);let r=t.items,n=Q.memoizer;n?.attach(e),e._zod.parse=(o,s)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=n?n.alloc(e,o,[],s):[];let a=[],c=Dc(r,"optin"),d=Dc(r,"optout");if(!t.rest){if(i.length<c)return o.issues.push({code:"too_small",minimum:c,inclusive:!0,input:i,inst:e,origin:"array"}),o;if(i.length>r.length)o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=Array(r.length),l=t.rest?s?.abortEarly:void 0,p=!1;for(let f=0;f<r.length;f++){let m=r[f]._zod.run({value:i[f],issues:[]},s);if(m instanceof Promise)a.push(m.then((y)=>{u[f]=y}));else if(u[f]=m,l&&!p&&m.issues.length)p=he(m)}if(t.rest&&!p){let f=r.length-1,m=i.slice(r.length),y=o.issues.length;for(let g of m){if(l&&o.issues.length!==y){if(he(o,y))break;y=o.issues.length}f++;let w=t.rest._zod.run({value:g,issues:[]},s);if(w instanceof Promise)a.push(w.then((b)=>Lc(b,o,f)));else Lc(w,o,f)}}if(a.length)return Promise.all(a).then(()=>Uc(u,o,r,i,d));return Uc(u,o,r,i,d)}});function Dc(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function Lc(e,t,r){if(e.issues.length)t.issues.push(...ve(r,e.issues));t.value[r]=e.value}function Uc(e,t,r,n,o){for(let s=0;s<r.length;s++){let i=e[s],a=s<n.length;if(!a&&s>=o&&r[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=o){t.value.length=s;break}t.issues.push(...ve(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=n.length;s--)if(r[s]._zod.optout==="optional"&&t.value[s]===void 0)t.value.length=s;else break;return t}var Au=_("$ZodRecord",(e,t)=>{z.init(e,t);let r=Q.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Xe(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let l=t.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>xe(m,o,ce())),input:u,path:[u],inst:e});continue}let p=l.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(u,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(u,f.issues));n.value[p]=f.value}}let d;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=s[u]}else d=d??[],d.push(u);if(d&&d.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let d of Reflect.ownKeys(s)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&Zt.test(d)&&u.issues.length){let m=t.keyType._zod.run({value:Number(d),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)u=m}if(u.issues.length){if(t.mode==="loose")n.value[d]=s[d];else if(a)c=c??[],c.push(d);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((m)=>xe(m,o,ce())),input:d,path:[d],inst:e});continue}let p=u.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[d],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(d,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(d,f.issues));n.value[p]=f.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}});var $u=_("$ZodEnum",(e,t)=>{z.init(e,t);let r=zt(t.entries),n=new Set(r);e._zod.values=n,P(e,"pattern",(o)=>{let s=zt(o.def.entries).filter((i)=>va.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>Fe(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Pu=_("$ZodLiteral",(e,t)=>{z.init(e,t);let r=new Set(t.values);e._zod.values=r,P(e,"pattern",(n)=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map((s)=>typeof s==="string"?Fe(s):s?Fe(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var Nu=_("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",Q.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r));if(o instanceof Promise)throw new be;return r.value=o,r}});function Zc(e,t){return e.value=t.issues.length?void 0:t.value,e}var Eo=_("$ZodOptional",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Zc(r,s));return Zc(r,o)}return t.innerType._zod.run(r,n)}}),zu=_("$ZodExactOptional",(e,t)=>{Eo.init(e,t),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Mu=_("$ZodNullable",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)}|null)$`):void 0}),P(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Du=_("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>jc(s,t));return jc(o,t)}});function jc(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Lu=_("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Uu=_("$ZodNonOptional",(e,t)=>{z.init(e,t),P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fc(s,e));return Fc(o,e)}});function Fc(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Hc(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>xe(o,n,ce()))},input:e.value}),e}var Zu=_("$ZodCatch",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Hc(r,s,t,n));return Hc(r,o,t,n)}});var ju=_("$ZodPipe",(e,t)=>{z.init(e,t),P(e,"values",(r)=>r.def.in._zod.values),P(e,"optin",(r)=>r.def.in._zod.optin),P(e,"optout",(r)=>r.def.out._zod.optout),P(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>Fr(i,t.in,n));return Fr(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fr(s,t.out,n));return Fr(o,t.out,n)}});function Fr(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}var Fu=_("$ZodReadonly",(e,t)=>{z.init(e,t),P(e,"propValues",(r)=>r.def.innerType._zod.propValues),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"optin",(r)=>r.def.innerType?._zod?.optin),P(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(Bc);return Bc(o)}});function Bc(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Hu=_("$ZodCustom",(e,t)=>{V.init(e,t),z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>qc(s,r,n,e));qc(o,r,n,e);return}});function qc(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Qe(o))}}class qu extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var ko="~memo",Bu=[];function Gu(e){return e!==null&&typeof e==="object"}function Io(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ku=new WeakMap,Ht=0,Wr=1,Bt=2;function Jr(e,t,r){let n=Ku.get(e);if(n!==void 0)return n?Bt:Ht;if(t.has(e))return Bt;t.add(e);let o=Ht,s=(u)=>{if(o!==Bt&&u?._zod){let l=Jr(u,t,r);if(l>o)o=l}},i=(u,l)=>{let p=Ht;for(let f of Reflect.ownKeys(u)){let m=Object.getOwnPropertyDescriptor(u,f);if(l&&!m.enumerable)continue;let y=m.get?Wr:m.value?._zod?Jr(m.value,t,r):Ht;if(y>p)p=y}return p},a=(u)=>{if(u>o)o=u},c=e._zod.def,d=c.type;switch(d){case"object":{let u=Lt(c);a(u?i(u,!0):Wr),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Jr(u,t,!1):Wr);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let l=Object.getOwnPropertyDescriptor(c,u);if(!l||l.get)continue;let p=l.value;if(!p||typeof p!=="object")continue;if(p._zod)s(p);else if(Array.isArray(p))for(let f of p)s(f)}}return t.delete(e),Ym(e,o)}function Ym(e,t){if(t!==Wr)Ku.set(e,t===Bt);return t}function Xm(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var Kr,Vr=[],Qm={alloc(e,t,r){let n=Kr;if(!n)return r;Kr=void 0;let o={value:r,issues:null};return n.set(t.value,o),Vr.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,s)=>{if(s.direction!=="backward"&&eg(s,o.value))throw new qu;return r(o,s)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,d)=>{if(r===void 0){let w=Jr(e,new Set,!1);if(w===Ht){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,d)}if(w===Bt||n)r=!0;else n=!0}let u=c.value;if(!Gu(u))return i(c,d);let l=d[ko];if(!l)l={buckets:new WeakMap,backEdges:void 0},d[ko]=l;let p;if(o===d)p=s;else p=Xm(l,e),o=d,s=p;let f=p.get(u);if(f){if(c.value=f.value,f.issues){if(f.issues.length)c.issues.push(...Io(f.issues))}else c.memo=!0,l.backEdges??(l.backEdges=new WeakSet),l.backEdges.add(f.value);return c}Kr=p;let m=Vr.length,y=i(c,d);Kr=void 0;let g=Vr.length>m?Vr.pop():void 0;if(y instanceof Promise)return y.then((w)=>{if(g)g.issues=w.issues.length?Io(w.issues):Bu;return w});if(g)g.issues=y.issues.length?Io(y.issues):Bu;return y};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function Vu(){return Qm}function eg(e,t){let r=e[ko]?.backEdges;return r!==void 0&&Gu(t)&&r.has(t)}var tg=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=ka(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${no(s.values[0])}`;return`Invalid option: expected one of ${eo(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${eo(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((a)=>`'${a}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Co(){return{localeError:tg()}}var Wu;class Ju{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function rg(){return new Ju}(Wu=globalThis).__zod_globalRegistry??(Wu.__zod_globalRegistry=rg());var et=globalThis.__zod_globalRegistry;function Yu(e){if(e.checks)e.checks=[...e.checks];return e}function Xu(e,t){return new e(Yu({type:"string",...C(t)}))}function Qu(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})}function ed(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})}function td(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})}function sd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})}function id(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})}function ad(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})}function cd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})}function ud(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})}function dd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})}function ld(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})}function fd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})}function hd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})}function pd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})}function md(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})}function gd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})}function yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})}function _d(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})}function wd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})}function Sd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})}function vd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})}function xd(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})}function bd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})}function Ed(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})}function Id(e,t){return new e(Yu({type:"number",checks:[],...C(t)}))}function kd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})}function Cd(e,t){return new e({type:"boolean",...C(t)})}function Rd(e){return new e({type:"unknown"})}function Od(e,t){return new e({type:"never",...C(t)})}function Yr(e,t){return new go({check:"less_than",...C(t),value:e,inclusive:!1})}function qt(e,t){return new go({check:"less_than",...C(t),value:e,inclusive:!0})}function Xr(e,t){return new yo({check:"greater_than",...C(t),value:e,inclusive:!1})}function Gt(e,t){return new yo({check:"greater_than",...C(t),value:e,inclusive:!0})}function Qr(e,t){return new wc({check:"multiple_of",...C(t),value:e})}function en(e,t){return new vc({check:"max_length",...C(t),maximum:e})}function gt(e,t){return new xc({check:"min_length",...C(t),minimum:e})}function tn(e,t){return new bc({check:"length_equals",...C(t),length:e})}function Ro(e,t){return new Ec({check:"string_format",format:"regex",...C(t),pattern:e})}function Oo(e){return new Ic({check:"string_format",format:"lowercase",...C(e)})}function To(e){return new kc({check:"string_format",format:"uppercase",...C(e)})}function Ao(e,t){return new Cc({check:"string_format",format:"includes",...C(t),includes:e})}function $o(e,t){return new Rc({check:"string_format",format:"starts_with",...C(t),prefix:e})}function Po(e,t){return new Oc({check:"string_format",format:"ends_with",...C(t),suffix:e})}function He(e){return new Tc({check:"overwrite",tx:e})}function No(e){return He((t)=>t.normalize(e))}function zo(){return He((e)=>e.trim())}function Mo(){return He((e)=>e.toLowerCase())}function Do(){return He((e)=>e.toUpperCase())}function Lo(){return He((e)=>wa(e))}function Td(e,t,r){return new e({type:"array",element:t,...C(r)})}function Ad(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})}function $d(e,t){let r=ng((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Qe(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Qe(s))}},e(n.value,n)),t);return r}function ng(e,t){let r=new V({check:"custom",...C(t)});return r._zod.check=e,r}function Kt(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))fe(e,n,r[n]);return e}function Zo(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??et,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function $e(e,t,r,n,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(r,s),!0}function j(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[o.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,u)}let l=e._zod.parent;if(l){if(!i.ref)i.ref=l;j(l,t,u),t.seen.get(l).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Kt(i.schema,c);if(t.io==="input"&&ee(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Pd(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function jo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,p=e.external.uri??((m)=>m);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${Pd(f)}`}}let c="#",d=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+Pd(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:d}=o(i);if(a.def={...a.schema},d)a.defId=d;let u=a.schema;for(let l in u)delete u[l];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
62
62
 
63
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Md(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Md(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Dd=new Set(["type","properties","required","additionalProperties"]),Nd=["oneOf","anyOf"];function zd(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function Lo(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Dd.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let d of t){let u=d.properties?.[i]??zd(d);if(u===null||u===void 0)continue;if(!a.some((l)=>JSON.stringify(l)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:Lo(a)??{allOf:a};fe(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=zd(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function rg(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Dd)if(o in e)return;let r=t.filter((o)=>Nd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=Lo(t);else{let o=r[0],s=Nd.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>Lo([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Kt(e,n)}function jo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,u={...d},l=c.ref;if(c.ref=null,l){n(l);let f=e.seen.get(l),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(m);else Kt(d,m);if(Kt(d,u),a._zod.parent===l)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete d[g]}if(m.$ref&&f.def)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(d[g])===JSON.stringify(f.def[g]))delete d[g]}}let p=a._zod.parent;if(p&&p!==l){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(d.$ref=f.schema.$ref,f.def)for(let m in d){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(d[m])===JSON.stringify(f.def[m]))delete d[m]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Md(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let l=a.get(u);if(l)l.push(d);else a.set(u,[d])}for(let c of e.intersections)for(let d of a.get(c)??[])rg(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Kt(o,r.defId?r.schema:r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;fe(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Vt(t,"input",e.processors),output:Vt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function ee(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ee(n.element,r);if(n.type==="set")return ee(n.valueType,r);if(n.type==="lazy")return ee(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return ee(n.innerType,r);if(n.type==="intersection")return ee(n.left,r)||ee(n.right,r);if(n.type==="record"||n.type==="map")return ee(n.keyType,r)||ee(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ee(n.in,r)||ee(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(ee(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ee(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ee(o,r))return!0;if(n.rest&&ee(n.rest,r))return!0;return!1}return!1}var Ld=(e,t={})=>(r)=>{let n=Uo({...r,processors:t});return j(e,n),Zo(n,e),jo(n,e)},Vt=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=Uo({...o??{},target:s,io:t,processors:r});return j(e,i),Zo(i,e),jo(i,e)};var _t=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},wt=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},Ud=(e,t)=>{_t(e,"minimum",t),wt(e,"maximum",t)},Hd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Bd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},qd=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Gd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Zd=(e,t)=>_t(e,"minimum",t.minimum),jd=(e,t)=>wt(e,"maximum",t.maximum),Fd=(e)=>(t,r)=>{Gd(t,r.format);let[n,o]=e[r.format];_t(t,"minimum",n),wt(t,"maximum",o)},ng={greater_than:(e,t)=>_t(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>wt(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Hd(e,t.value),number_format:Fd(Tr),bigint_format:Fd(no),min_length:Zd,max_length:jd,length_equals:(e,t)=>Ud(e,t.length),min_size:Zd,max_size:jd,size_equals:(e,t)=>Ud(e,t.size),string_format:(e,t)=>{if(Gd(e,t.format),t.pattern)Bd(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>qd(e,t.mime)};function ue(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)ng[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)_t(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)_t(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)wt(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)wt(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Hd(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)qd(t,o.mime);for(let s of o.patterns??[])Bd(t,s);return t}var og={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sg=new Map([[So,ac],[Gr,cc]]),Kd=(e)=>sg.get(e)??e,Vd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=ue(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=og[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c].map(Kd);if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Wd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=ue(e);o.type=u?"integer":"number";let l=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(l)if(f)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let m=new Set;for(let w of a)if(Number.isFinite(w)&&w!==0)m.add(Math.abs(w));else $e(e,t,o,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[y,...g]=m;if(y!==void 0)o.multipleOf=y;if(g.length)o.allOf=[...o.allOf??[],...g.map((w)=>({multipleOf:w}))]}},Jd=(e,t,r,n)=>{r.type="boolean"};var Yd=(e,t,r,n)=>{r.not={}};var Xd=(e,t,r,n)=>{};var Qd=(e,t,r,n)=>{let o=e._zod.def,s=zt(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},el=(e,t,r,n)=>{let o=e._zod.def;if(o.values.length===0){r.not={};return}let s=[];for(let i of o.values)if(i===void 0){if($e(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if($e(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}};var tl=(e,t,r,n)=>{$e(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var rl=(e,t,r,n)=>{$e(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var nl=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=ue(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=j(s.element,t,{...n,path:[...n.path,"items"]})};function Wt(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Wt(t.out);if(t.type==="catch")return Wt(t.innerType);return e._zod.optin}var ol=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&$e(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in i)fe(o.properties,d,j(i[d],t,{...n,path:[...n.path,"properties",d]}));let c=[];for(let d of Object.keys(i)){let u=s.shape[d];if(t.io==="input"?Wt(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=j(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},sl=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>j(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},il=(e,t,r,n)=>{let o=e._zod.def,s=j(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=j(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},al=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((y,g)=>j(y,t,{...n,path:[...n.path,i,g]})),d=s.rest?j(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let y=s.items[u-1];if(!(t.io==="input"?Wt(y)!==void 0:y._zod.optout==="optional"))break;u--}let l=s.items.length,p=!s.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,p)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(p)o.maxItems=l}else{if(o.items=c,p)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}let{minimum:f,maximum:m}=ue(e);if(typeof f==="number")o.minItems=f;if(typeof m==="number")o.maxItems=m};function Fo(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let y=Fo(e,m,r);return y===m?t:y}for(let m of["anyOf","oneOf"]){let y=t[m];if(!Array.isArray(y))continue;let g=y.map((w)=>Fo(e,w,r));if(g.some((w,b)=>w!==y[b]))t={...t,[m]:g}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((m)=>m==="number"||m==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((m)=>typeof m==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:l,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((m)=>typeof m==="number"?String(m):m);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(n.includes("number")?Zt:ho).source;return f}var Ho=new WeakMap;function ig(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of Ho.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Fo(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var cl=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=ue(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=j(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)fe(o.patternProperties,Kd(l).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=j(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=Ho.get(t);if(!u)u=[],Ho.set(t,u),t.deferred.push(()=>ig(t));u.push(e)}o.additionalProperties=j(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,d=t.io==="input"&&Wt(s.valueType)!==void 0;if(c&&!s.partial&&!d){let u=[...c].filter((l)=>typeof l==="string"||typeof l==="number");if(u.length>0)o.required=u.map(String)}},ul=(e,t,r,n)=>{let o=e._zod.def,s=j(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},dl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Bo=Symbol();function ll(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return $e(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),Bo}var fl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=ll(o.defaultValue,e,t,r,n);if(i!==Bo)r.default=i},hl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=ll(o.defaultValue,e,t,r,n);if(i!==Bo)r._prefault=i},pl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{$e(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},ml=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;j(i,t,n);let a=t.seen.get(e);a.ref=i},gl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var qo=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var yl=new WeakSet([Object.prototype,Error.prototype]);function rn(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var pg=(e,t)=>{Na.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(yl.has(r))return;yl.add(r),rn(r,"format",(n)=>(o)=>Ma(n,o)),rn(r,"flatten",(n)=>(o)=>za(n,o)),rn(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Mt,2)}),rn(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Mt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var de=_("ZodError",pg,void 0,{Parent:Error});var _l=Dr(de),wl=Lr(de),Sl=Ur(de),vl=Zr(de),xl=La(de),bl=Ua(de),El=Za(de),Il=ja(de),kl=Fa(de),Rl=Ha(de),Cl=Ba(de),Ol=qa(de);function gg(){if(!Q.localeError)ce(ko())}function Jt(){if(!Q.memoizer)ce({memoizer:Vu()})}var U=_("ZodType",(e,t)=>(gg(),M.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ae(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(hy(e,t))},superRefine(e,t){return this.check(py(e,t))},overwrite(e){return this.check(He(e))},optional(){return $l(this)},exactOptional(){return ey(this)},nullable(){return Pl(this)},nullish(){return $l(Pl(this))},nonoptional(e){return iy(this,e)},array(){return K(this)},or(e){return on([this,e])},and(e){return Wg(this,e)},transform(e){return Nl(this,Qg(e))},default(e){return ny(this,e)},prefault(e){return sy(this,e)},catch(e){return cy(this,e)},pipe(e){return Nl(this,e)},readonly(){return ly(this)},describe(e){let t=this.clone();return tt.add(t,{description:e}),t},meta(...e){if(e.length===0)return tt.get(this);let t=this.clone();return tt.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return zr(this,"~standard",{...wo(this),jsonSchema:{input:Vt(this,"input"),output:Vt(this,"output")}})},set "~standard"(e){Ae(this,"~standard",e)},parse:function e(t,r){return _l(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wl(this,t,r,{callee:e})},safeParse(e,t){return Sl(this,e,t)},async safeParseAsync(e,t){return vl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ae(this,"spa",e)},validate(e,t){return co(this,e,t)},validateAsync(e,t){return uo(this,e,t)},encode:function e(t,r){return xl(this,t,r,{callee:e})},decode:function e(t,r){return bl(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await El(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Il(this,t,r,{callee:e})},safeEncode(e,t){return kl(this,e,t)},safeDecode(e,t){return Rl(this,e,t)},async safeEncodeAsync(e,t){return Cl(this,e,t)},async safeDecodeAsync(e,t){return Ol(this,e,t)},toJSONSchema(e){return Ld(this,{})(e)},get description(){return tt.get(this)?.description},get _def(){return this._zod.def}}),zl=_("_ZodString",(e,t)=>{qr.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vd(e,r,n,o)},Ca({format:(e)=>ue(e).format??null,minLength:(e)=>ue(e).minimum??null,maxLength:(e)=>ue(e).maximum??null},{regex(...e){return this.check(Ro(...e))},includes(...e){return this.check(To(...e))},startsWith(...e){return this.check(Ao(...e))},endsWith(...e){return this.check($o(...e))},min(...e){return this.check(yt(...e))},max(...e){return this.check(en(...e))},length(...e){return this.check(tn(...e))},nonempty(...e){return this.check(yt(1,...e))},lowercase(e){return this.check(Co(e))},uppercase(e){return this.check(Oo(e))},trim(){return this.check(No())},normalize(...e){return this.check(Po(...e))},toLowerCase(){return this.check(zo())},toUpperCase(){return this.check(Mo())},slugify(){return this.check(Do())}})),yg=_("ZodString",(e,t)=>{qr.init(e,t),zl.init(e,t)},{email(e){return this.check(Qu(xg,e))},url(e){return this.check(sd(Eg,e))},jwt(e){return this.check(Sd(Ug,e))},emoji(e){return this.check(id(Ig,e))},guid(e){return this.check(ed(bg,e))},uuid(e){return this.check(td(nn,e))},uuidv4(e){return this.check(rd(nn,e))},uuidv6(e){return this.check(nd(nn,e))},uuidv7(e){return this.check(od(nn,e))},nanoid(e){return this.check(ad(kg,e))},cuid(e){return this.check(cd(Rg,e))},cuid2(e){return this.check(ud(Cg,e))},ulid(e){return this.check(dd(Og,e))},base64(e){return this.check(yd(Mg,e))},base64url(e){return this.check(_d(Dg,e))},xid(e){return this.check(ld(Tg,e))},ksuid(e){return this.check(fd(Ag,e))},ipv4(e){return this.check(hd($g,e))},ipv6(e){return this.check(pd(Pg,e))},cidrv4(e){return this.check(md(Ng,e))},cidrv6(e){return this.check(gd(zg,e))},e164(e){return this.check(wd(Lg,e))},datetime(e){return this.check(vd(_g,e))},date(e){return this.check(xd(wg,e))},time(e){return this.check(bd(Sg,e))},duration(e){return this.check(Ed(vg,e))}});function S(e){return Xu(yg,e)}var F=_("ZodStringFormat",(e,t)=>{L.init(e,t),zl.init(e,t)}),_g=_("ZodISODateTime",(e,t)=>{iu.init(e,t),F.init(e,t)}),wg=_("ZodISODate",(e,t)=>{au.init(e,t),F.init(e,t)}),Sg=_("ZodISOTime",(e,t)=>{cu.init(e,t),F.init(e,t)}),vg=_("ZodISODuration",(e,t)=>{uu.init(e,t),F.init(e,t)}),xg=_("ZodEmail",(e,t)=>{Wc.init(e,t),F.init(e,t)});var bg=_("ZodGUID",(e,t)=>{Kc.init(e,t),F.init(e,t)});var nn=_("ZodUUID",(e,t)=>{Vc.init(e,t),F.init(e,t)});var Eg=_("ZodURL",(e,t)=>{Xc.init(e,t),F.init(e,t)});var Ig=_("ZodEmoji",(e,t)=>{Qc.init(e,t),F.init(e,t)});var kg=_("ZodNanoID",(e,t)=>{eu.init(e,t),F.init(e,t)});var Rg=_("ZodCUID",(e,t)=>{tu.init(e,t),F.init(e,t)});var Cg=_("ZodCUID2",(e,t)=>{ru.init(e,t),F.init(e,t)});var Og=_("ZodULID",(e,t)=>{nu.init(e,t),F.init(e,t)});var Tg=_("ZodXID",(e,t)=>{ou.init(e,t),F.init(e,t)});var Ag=_("ZodKSUID",(e,t)=>{su.init(e,t),F.init(e,t)});var $g=_("ZodIPv4",(e,t)=>{du.init(e,t),F.init(e,t)});var Pg=_("ZodIPv6",(e,t)=>{fu.init(e,t),F.init(e,t)});var Ng=_("ZodCIDRv4",(e,t)=>{hu.init(e,t),F.init(e,t)});var zg=_("ZodCIDRv6",(e,t)=>{pu.init(e,t),F.init(e,t)});var Mg=_("ZodBase64",(e,t)=>{gu.init(e,t),F.init(e,t)});var Dg=_("ZodBase64URL",(e,t)=>{yu.init(e,t),F.init(e,t)});var Lg=_("ZodE164",(e,t)=>{_u.init(e,t),F.init(e,t)});var Ug=_("ZodJWT",(e,t)=>{wu.init(e,t),F.init(e,t)});var Ml=_("ZodNumber",(e,t)=>{vo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o),e.isFinite=!0},Ca({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=ue(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=ue(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=ue(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>ue(e).format??null},{gt(e,t){return this.check(Xr(e,t))},gte(e,t){return this.check(Gt(e,t))},min(e,t){return this.check(Gt(e,t))},lt(e,t){return this.check(Yr(e,t))},lte(e,t){return this.check(qt(e,t))},max(e,t){return this.check(qt(e,t))},int(e){return this.check(Tl(e))},safe(e){return this.check(Tl(e))},positive(e){return this.check(Xr(0,e))},nonnegative(e){return this.check(Gt(0,e))},negative(e){return this.check(Yr(0,e))},nonpositive(e){return this.check(qt(0,e))},multipleOf(e,t){return this.check(Qr(e,t))},step(e,t){return this.check(Qr(e,t))},finite(){return this}}));function Pe(e){return Id(Ml,e)}var Zg=_("ZodNumberFormat",(e,t)=>{Su.init(e,t),Ml.init(e,t)});function Tl(e){return kd(Zg,e)}var jg=_("ZodBoolean",(e,t)=>{vu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jd(e,r,n,o)});function Yt(e){return Rd(jg,e)}var Fg=_("ZodUnknown",(e,t)=>{xu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o)});function Ee(){return Cd(Fg)}var Hg=_("ZodNever",(e,t)=>{bu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o)});function Bg(e){return Od(Hg,e)}var qg=_("ZodArray",(e,t)=>{Jt(),Eu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nl(e,r,n,o),e.element=t.element},{min(e,t){return this.check(yt(e,t))},nonempty(e){return this.check(yt(1,e))},max(e,t){return this.check(en(e,t))},length(e,t){return this.check(tn(e,t))},unwrap(){return this.element}});function K(e,t){return Td(qg,e,t)}var Gg=_("ZodObject",(e,t)=>{Jt(),Ru.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ol(e,r,n,o),xm(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return ne(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ae(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},loose(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},strict(){return this.clone(ae(this._zod.def,{catchall:Bg()}))},strip(){return this.clone(ae(this._zod.def,{catchall:void 0}))},extend(e){return pm(this,e)},safeExtend(e){return mm(this,e)},merge(e){return gm(this,e)},pick(e){return fm(this,e)},omit(e){return hm(this,e)},partial(...e){return Ea(Vo,this,e[0])},exactPartial(...e){return Ea(Zl,this,e[0],"exactPartial")},required(...e){return ym(jl,this,e[0])}});function k(e,t){let r={type:"object",shape:e??{},...R(t)};return new Gg(r)}var Dl=_("ZodUnion",(e,t)=>{xo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sl(e,r,n,o),e.options=t.options});function on(e,t){return new Dl({type:"union",options:e,...R(t)})}var Kg=_("ZodDiscriminatedUnion",(e,t)=>{Dl.init(e,t),Cu.init(e,t)});function Ll(e,t,r){return new Kg({type:"union",options:t,discriminator:e,...R(r)})}var Vg=_("ZodIntersection",(e,t)=>{Ou.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>il(e,r,n,o)});function Wg(e,t){return new Vg({type:"intersection",left:e,right:t})}var Jg=_("ZodTuple",(e,t)=>{Jt(),Tu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>al(e,r,n,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Vo({type:"optional",innerType:t}))})}});function Be(e,t,r){let n=t instanceof M,o=n?r:t;return new Jg({type:"tuple",items:e,rest:n?t:null,...R(o)})}var Al=_("ZodRecord",(e,t)=>{Jt(),Au.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cl(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ul(e,t,r){if(!t||!t._zod)return new Al({type:"record",keyType:S(),valueType:e,...R(t)});return new Al({type:"record",keyType:e,valueType:t,...R(r)})}var Ko=_("ZodEnum",(e,t)=>{$u.init(e,t),U.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Qd(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Ko({...t,checks:[],...R(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Ko({...t,checks:[],...R(o),entries:s})}});function ne(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Ko({type:"enum",entries:r,...R(t)})}var Yg=_("ZodLiteral",(e,t)=>{Pu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>el(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function H(e,t){return new Yg({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var Xg=_("ZodTransform",(e,t)=>{Jt(),Nu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rl(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(et(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(et(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function Qg(e){return new Xg({type:"transform",transform:e})}var Vo=_("ZodOptional",(e,t)=>{bo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qo(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $l(e){return new Vo({type:"optional",innerType:e})}var Zl=_("ZodExactOptional",(e,t)=>{zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qo(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ey(e){return new Zl({type:"optional",innerType:e})}var ty=_("ZodNullable",(e,t)=>{Mu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ul(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new ty({type:"nullable",innerType:e})}var ry=_("ZodDefault",(e,t)=>{Du.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ny(e,t){return new ry({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():to(t)}})}var oy=_("ZodPrefault",(e,t)=>{Lu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function sy(e,t){return new oy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():to(t)}})}var jl=_("ZodNonOptional",(e,t)=>{Uu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function iy(e,t){return new jl({type:"nonoptional",innerType:e,...R(t)})}var ay=_("ZodCatch",(e,t)=>{Zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cy(e,t){return new ay({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Oa(t)})}var uy=_("ZodPipe",(e,t)=>{ju.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ml(e,r,n,o),e.in=t.in,e.out=t.out});function Nl(e,t){return new uy({type:"pipe",in:e,out:t})}var dy=_("ZodReadonly",(e,t)=>{Fu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ly(e){return new dy({type:"readonly",innerType:e})}var fy=_("ZodCustom",(e,t)=>{Hu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tl(e,r,n,o)});function hy(e,t={}){return Ad(fy,e,t)}function py(e,t){return $d(e,t)}var Jo=["SOURCE_UNBOUND","SOURCE_UNAVAILABLE","SERVICE_IDENTITY_UNAVAILABLE","SERVICE_IDENTITY_NOT_GRANTED","AGENT_NOT_MAPPED","NOT_MAPPED","INVALID_ADDRESS","HOST_OFFLINE","SOURCE_GAP","FRAME_TOO_LARGE","ITEM_TOO_LARGE","STALE_EXPECTATION","SOURCE_READER_RESTARTING"],cn=524288,st=262144,my=1000;function te(e){return new TextEncoder().encode(JSON.stringify(e)).length}var W=S().min(1).max(256),ot=S().min(1).max(1024),gy=S().regex(/^(0|[1-9][0-9]{0,17})$/u),un=k({epoch:W,ordinal:gy}).strict(),nt={workspaceId:W,sourceId:W,hostId:W},St=k({address:ot,version:W,scope:W,columns:k({title:S().max(4096),state:W,owner:W.nullable(),parent:ot.nullable(),project:ot.nullable(),labels:K(W).max(256),url:S().max(2048).nullable(),updatedAt:S().max(64).nullable()}).strict(),extra:Ee()}).strict(),Yo=k({position:un,change:Ll("op",[k({op:H("upsert"),row:St}).strict(),k({op:H("delete"),address:ot}).strict()])}).strict(),yy=k({address:ot}).strict(),_y=k({page:S().min(1).max(4096).optional(),limit:Pe().int().min(1).max(my)}).strict(),wy=k({address:ot,ownerMemberId:W,expectedOwner:W.nullable(),intentId:W,ifRevision:S().min(1).max(256).optional()}).strict(),Sy=k({on:Yt()}).strict(),vy=k({memberId:W}).strict(),sn=(e,t)=>k({...nt,caller:vy,op:H(e),args:t}).strict(),Hl=Ll("op",[sn("read",yy),sn("list",_y),sn("assign",wy),sn("watch",Sy)]),xy=k({generation:W,snapshot:W,base:un,rows:K(St),next:S().min(1).max(4096).nullable(),complete:Yt(),progressAsOf:S().min(1).max(64).optional(),progressStale:k({since:S().min(1).max(64),reason:S().min(1).max(4096)}).strict().optional()}).strict().refine((e)=>e.rows.length>0||e.complete&&e.next===null,{message:"a page carries at least one item"}).refine((e)=>e.complete===(e.next===null),{message:"a page is complete exactly when it has no next token"}),by=k({intentId:W,result:Ee(),observation:Yo,revision:W.nullable().optional()}).strict(),Wo={read:k({observation:Yo}).strict(),list:xy,assign:by,watch:k({on:Yt()}).strict()},Fl=ne(Jo),Ey=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],an=(e)=>on([k({...nt,op:H(e),outcome:ne(["applied","noop"]),body:Wo[e]}).strict(),k({...nt,op:H(e),outcome:ne(["applied","noop"]),code:H("SOURCE_READER_RESTARTING"),body:Wo[e]}).strict(),k({...nt,op:H(e),outcome:H("rejected"),code:Fl,body:Wo[e]}).strict(),k({...nt,op:H(e),outcome:ne(["unknown","refused"]),code:on([Fl.exclude(["ITEM_TOO_LARGE"]),ne(Ey)])}).strict(),k({...nt,op:H(e),outcome:H("refused"),code:H("ITEM_TOO_LARGE"),item:ot}).strict()]),Bl=on([an("read"),an("list"),an("assign"),an("watch")]),oI=k({...nt,position:un,observations:K(Yo).min(1)}).strict().refine((e)=>{let{observations:t,position:r}=e,n=t[t.length-1];if(n===void 0||n.position.epoch!==r.epoch||n.position.ordinal!==r.ordinal)return!1;return t.every((o,s)=>o.position.epoch===r.epoch&&(s===0||BigInt(o.position.ordinal)===BigInt(t[s-1].position.ordinal)+1n))},{message:"a push is one epoch of consecutive ordinals, numbered by its last"}),ql=k({applied:un.nullable(),seq:Pe().int().min(0),relist:Yt()}).strict();var qe="x-hh-records";var Iy=`${qe}/changed`,Ie="assign",dn="records:assign",Gl=k({address:S().min(1).max(1024),ownerMemberId:S().min(1).max(256),expectedOwner:S().min(1).max(256).nullable().optional(),ifRevision:S().min(1).max(256),intentId:S().min(1).max(256)}).strict(),Kl=S().min(1).max(256),Vl=S().min(1).max(1024),Wl=k({address:Vl,revision:S().min(1).max(256),scope:S().min(1).max(256),columns:Ul(S(),Ee()),extra:Ee().optional()}).strict(),aI=k({source:Kl,epoch:S().min(1).max(256),records:K(Wl)}).strict(),ky=k({type:H(Iy),source:Kl,revision:S().min(1).max(256),address:Vl,deleted:H(!0).optional(),record:Wl.optional()}).strict(),cI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),action:ky}),Ry=new RegExp(`^${qe}://[^/?#]+$`,"u"),Jl=(e)=>e===`${qe}://`||Ry.test(e);var Cy=k({id:S().min(1),revision:Pe().int().min(0),state:S(),operations:K(S())}).passthrough();var Xo=Pe().int().min(0),lI=k({id:S().min(1),engine:S().min(1),owner:S().min(1),name:S().min(1),description:S().optional(),tags:K(S()).optional(),model:Ee().optional(),config:Ul(S(),Ee()),ifRevision:Xo}).passthrough(),fI=k({id:S().min(1),ifRevision:Xo}).strict(),hI=k({id:S().min(1),ifRevision:Xo}).strict(),Yl=-32602,pI=k({code:H(Yl),message:S(),data:k({staleRevision:Pe().int().min(1),row:Cy})}),mI=k({code:H(Yl),message:S(),data:k({staleRevision:H(0)})});var Qo=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],Ge="x-hh-services://",Oy=`${Ge} and ${qe}://<sourceId>`,Xl=["put","remove","start","stop","restart","accept"];var Ty="hh-services://backup",Ay="hh-services://changes",$y=/^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;function Ql(e,t){let r=(n)=>typeof t[n]==="string"?JSON.stringify(t[n]):`no ${n}`;switch(e){case"subscribe":{let n=t.channel;if(Object.keys(t).length===1&&typeof n==="string"&&(n===Ge||Jl(n)))return;return`subscribe to ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ${Oy}`}case"x-ahpd/invokeOperation":{if(t.channel===Ge){if(typeof t.operationId==="string"&&Xl.includes(t.operationId))return;return`x-ahpd/invokeOperation ${r("operationId")} on ${Ge} is not one Hightea sends; only ${Xl.join(", ")}`}if(t.channel===`${qe}://`){if(t.operationId===Ie)return;return`x-ahpd/invokeOperation ${r("operationId")} on ${qe}:// is not one Hightea sends; only ${Ie} (${dn})`}return`x-ahpd/invokeOperation on ${r("channel")} is not one Hightea sends; only ${Ge} and ${qe}://`}case"resourceRead":if(typeof t.uri==="string"&&$y.test(t.uri))return;return`resourceRead of ${r("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${Ty} and ${Ay}`;case"listSessions":if(t.channel==="ahp-root://"&&Object.keys(t).length===1)return;return`listSessions on ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ahp-root://`;case"authenticate":{let n=Object.keys(t).sort().join(",");if(n!=="resource,target,token"&&n!=="expiresIn,resource,target,token")return`authenticate naming ${JSON.stringify(n)} is not one Hightea sends; only target, resource, token and expiresIn`;if(typeof t.token!=="string")return"authenticate names no token";if(typeof t.resource!=="string"||t.resource==="")return`authenticate names ${r("resource")}`;let o=t.expiresIn;if(o!==void 0&&!(typeof o==="number"&&Number.isInteger(o)&&o>0))return"authenticate's expiresIn is not a positive integer of seconds";let s=t.target;if(typeof s!=="object"||s===null||Array.isArray(s))return"authenticate names no target";let i=s;if(Object.keys(i).sort().join(",")!=="customizationId,kind,session")return"authenticate's target carries more than kind, session and customizationId";if(i.kind!=="mcpServer")return`authenticate's target kind is ${JSON.stringify(i.kind)}; only mcpServer`;if(typeof i.session!=="string"||i.session==="")return"authenticate's target names no session";if(typeof i.customizationId!=="string"||i.customizationId==="")return"authenticate's target names no server";return}default:return`${JSON.stringify(e)} is not a host-scoped method; only ${Qo.join(", ")}`}}var ef=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...Qo];function Xt(e){return Qo.includes(e)}var Py=1e4,Qt=Py-1000,tf="host-request:",rf="1.1.0";var es="signed-envelopes";var nf=k({workspaceId:S().min(1),hostId:S().min(1),agentMemberId:S().min(1).optional(),caller:S().min(1).max(256).optional()}).strict(),Ny=["unmapped","timedOut","outside"],wI=k({reason:ne(Ny)}).strict();function of(e){if(e.ok)return{result:e.result};if(e.reason==="refused")return{error:{code:e.code,message:e.message,...e.data===void 0?{}:{data:e.data}}};return{error:{code:-32000,message:e.reason,data:{reason:e.reason}}}}var zy=k({resource:S().min(1),customizationId:S().min(1)}).strict(),er=k({available:Yt(),reason:S().min(1).max(200).optional(),server:zy.optional()}).strict(),it="ahpd/hostTools",SI=k({resource:S().min(1),_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er.optional()}).strict()}).strict(),vI=k({channel:H("ahp-root://"),session:S().min(1),changes:k({_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er}).strict()}).strict()}).strict();function tr(e,t,r){let n=ye(e)?e:{},o=n["hh/agentMemberId"];if(o!==void 0&&o!==t)return;let s=er.safeParse(n[it]);if(!s.success)return{"hh/agentMemberId":t};let i=s.data.available&&r!==void 0;return{"hh/agentMemberId":t,"hh/hostTools":{available:s.data.available,...s.data.reason===void 0?{}:{reason:s.data.reason},...i?{server:r}:{}}}}function sf(e,t,r){if(!ye(e)||typeof e.resource!=="string"||e.resource==="")return;let n=tr(e._meta,t,r);return n===void 0?void 0:{resource:e.resource,_meta:n}}var xI=k({channel:S().min(1),resource:S().min(1),reason:H("expired")}).strict();function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ts="event:all",af="tool:all";var My=["session/ready","chat/turnStarted","chat/turnComplete","x-hh/turnFailed"];var rr=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID","INVALID_OPERATION_SHAPE","WORKSPACE_OR_MEMBER_UNKNOWN","UNKNOWN_HOUSE_OR_MEMBER","AGENT_NOT_MAPPED","UNMAPPED_LOCAL_AGENT","FOREIGN_SESSION","FOREIGN_SESSION_REFUSED","TOKEN_EXPIRED_OR_REVOKED","HOST_REVOKED","HOST_RESTARTED","INPUT_REQUIRED","APPROVAL_REQUIRED","VERSION_UNSUPPORTED","WAKE_NOT_SENT","TURN_TIMED_OUT","HOST_START_FAILED","WAKE_TEXT_NOT_ALLOWED","ROOM_ASKS_UNTRUSTED","ASK_UNSIGNED","KEY_NOT_FOR_AUTHOR","ASK_STALE","ASK_REPLAYED","SERVICE_NOT_ALLOWED","TURN_CANCELLED",...Jo],cf=16,uf=49152,df=262144,Dy=k({id:S().min(1),from:k({memberId:S().min(1)}).strict(),text:S(),replyTo:S().min(1).optional(),deleted:H(!0).optional(),signed:k({keyId:S().min(1),createdAt:S().min(1),signature:S().min(1),clientId:S().min(1),attachmentIds:K(S().min(1))}).strict().optional()}).strict(),Ly=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,Uy=K(Dy).min(1).superRefine((e,t)=>{if(e.length>cf){t.addIssue({code:"custom",message:`a wake carries at most ${cf} triggering envelopes, not ${e.length}`});return}if(new Set(e.map((n)=>n.id)).size!==e.length){t.addIssue({code:"custom",message:"a wake names each triggering message once"});return}let r=0;for(let n of e){let o=Ly(n);if(o>uf){t.addIssue({code:"custom",message:`triggering envelope ${n.id} is ${o} bytes, over the ${uf}-byte limit`});return}r+=o}if(r>df)t.addIssue({code:"custom",message:`the triggering envelopes take ${r} bytes, over the ${df}-byte limit`})}),lf=k({workspaceId:S().min(1),deliveryId:S().min(1),turnId:S().min(1).optional(),agentMemberId:S().min(1),threadRef:S().min(1),afterMessageId:S().min(1).optional(),triggeringMessageIds:K(S().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:Uy.optional(),agentToken:S().min(1).max(4096).optional()}).strict().superRefine((e,t)=>{if(e.agentToken!==void 0&&e.triggering!==void 0)t.addIssue({code:"custom",message:"a wake carries its triggering envelopes or the older bearer, never both"})}),ln=k({event:ne(My),channel:S().min(1),workspaceId:S().min(1),deliveryId:S().min(1),session:S().min(1),chat:S().min(1),turnId:S().min(1).optional(),clientSeq:Pe().int().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict();function ff(e){return ln.parse(e)}var Zy=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],RI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),origin:k({clientId:S().min(1),clientSeq:Pe().int().min(1)}).optional(),action:k({type:ne(Zy),turnId:S().min(1).optional(),part:k({error:k({errorType:S().min(1)})}).optional()})});var hf="Hightea-Host",pf="x-hightea-host";import{createHash as Pf}from"node:crypto";var jy=(e,t,r)=>JSON.stringify([e,t,r]),or=/^ahp-session:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,Fy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,D=(e)=>({ok:!1,code:e});function nr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function at(e,t,r=[]){let n=new Set([...t,...r]);return t.every((o)=>(o in e))&&Object.keys(e).every((o)=>n.has(o))}function Hy(e){let t=lf.safeParse(e._meta);return t.success?t.data:void 0}function mf(e,t){if(!nr(e)||typeof e.method!=="string")return D("OPERATION_SHAPE_INVALID");if(!at(e,["method"],["jsonrpc","id","params"]))return D("OPERATION_SHAPE_INVALID");let r=e.method;if(r!=="createSession"&&r!=="subscribe"&&r!=="dispatchAction")return D("OPERATION_NOT_ALLOWLISTED");let n=e.params;if(!nr(n))return D("OPERATION_SHAPE_INVALID");let o=Hy(n);if(o===void 0)return D("OPERATION_SHAPE_INVALID");if(o.workspaceId!==t.workspaceId)return D("WORKSPACE_OR_MEMBER_UNKNOWN");let s=t.agents.get(o.agentMemberId);if(s===void 0)return D("AGENT_NOT_MAPPED");let i=jy(o.workspaceId,o.agentMemberId,o.threadRef),a=t.sessions.get(i),{triggering:c,agentToken:d,...u}=o,l=e.id,p={jsonrpc:"2.0",...l===void 0?{}:{id:l}},f=n.channel;if(r==="createSession"){if(!at(n,["channel","_meta"]))return D("OPERATION_SHAPE_INVALID");if(typeof f!=="string"||!or.test(f))return D("OPERATION_SHAPE_INVALID");if(a!==void 0)return D("OPERATION_SHAPE_INVALID");if(By(t,f))return D("FOREIGN_SESSION");return{ok:!0,operation:"createSession",frame:{...p,method:r,params:{channel:f,provider:s.provider,workingDirectories:[s.workingDirectory]}},meta:u,...c===void 0?{}:{triggering:c},sessionKey:i}}if(r==="subscribe"){if(!at(n,["channel","_meta"]))return D("OPERATION_SHAPE_INVALID");if(typeof f!=="string")return D("OPERATION_SHAPE_INVALID");if(a===void 0||a.sessionUri!==f)return D("FOREIGN_SESSION");return{ok:!0,operation:"subscribe",frame:{...p,method:r,params:{channel:f}},meta:u,...c===void 0?{}:{triggering:c},sessionKey:i}}if(!at(n,["channel","clientSeq","action","_meta"]))return D("OPERATION_SHAPE_INVALID");if(typeof n.clientSeq!=="number"||!Number.isInteger(n.clientSeq)||n.clientSeq<1)return D("OPERATION_SHAPE_INVALID");if(typeof f!=="string")return D("OPERATION_SHAPE_INVALID");if(a?.chatUri===void 0||a.chatUri!==f){if(t.parked?.has(i)===!0)return D("AGENT_NOT_MAPPED");return D("FOREIGN_SESSION")}let m=n.action;if(!nr(m)||m.type!=="chat/turnStarted")return D("OPERATION_NOT_ALLOWLISTED");if(!at(m,["type","turnId","message"],["startedAt"]))return D("OPERATION_SHAPE_INVALID");if(typeof m.turnId!=="string"||!Fy.test(m.turnId))return D("OPERATION_SHAPE_INVALID");if(m.startedAt!==void 0&&typeof m.startedAt!=="number")return D("OPERATION_SHAPE_INVALID");let y=m.message;if(!nr(y)||!at(y,["text","origin"])||typeof y.text!=="string")return D("OPERATION_SHAPE_INVALID");if(!nr(y.origin)||!at(y.origin,["kind"])||y.origin.kind!=="user")return D("OPERATION_SHAPE_INVALID");if(y.text!==`wake ${o.threadRef}`)return D("WAKE_TEXT_NOT_ALLOWED");return{ok:!0,operation:"dispatchAction",frame:{...p,method:r,params:{channel:f,clientSeq:n.clientSeq,action:{type:"chat/turnStarted",turnId:m.turnId,...m.startedAt===void 0?{}:{startedAt:m.startedAt},message:{text:y.text,origin:{kind:"user"}}}}},meta:u,...c===void 0?{}:{triggering:c},...d===void 0?{}:{readBearer:d},sessionKey:i,turnId:m.turnId}}function By(e,t){for(let r of e.sessions.values())if(r.sessionUri===t)return!0;return!1}import{fileURLToPath as I_}from"node:url";var qy="host",fn=(e)=>{if(typeof e!=="object"||e===null)return;let{code:t,message:r}=e;if(typeof t!=="number"||typeof r!=="string")return;let n=e.data;return n===void 0?{code:t,message:r}:{code:t,message:r,data:n}},Gy=(e)=>e.ifRevision===0,hn=(e)=>e instanceof Error&&/timed? ?out|timeout/iu.test(e.message),gf="x-ahpd-agents://";async function Ky(e){let t,r=!1;try{let n=await e.peer.request("subscribe",{channel:Ge},Qt);r=!0;let o=typeof n==="object"&&n!==null?n.snapshot:void 0;if(t=typeof o==="object"&&o!==null?o.state:void 0,typeof t!=="object"||t===null)throw Error("hightea-pipe: the services snapshot holds no state")}catch(n){let o=fn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};if(e.log.error(`hightea-pipe: ${n instanceof Error?n.message:"the services snapshot is unreadable"}`),hn(n))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's services"}}finally{if(r)try{e.peer.notify("unsubscribe",{channel:Ge})}catch(n){e.log.error(`hightea-pipe: dropping the services subscription failed: ${n instanceof Error?n.name:typeof n}`)}}return{ok:!0,result:t}}function Vy(e){let t=typeof e==="object"&&e!==null?e.snapshot:void 0,r=typeof t==="object"&&t!==null?t.state:void 0,n=typeof r==="object"&&r!==null?r.records:void 0;if(!Array.isArray(n))throw Error("hightea-pipe: the agents snapshot holds no records");return n.map((o)=>{if(typeof o!=="object"||o===null)throw Error("hightea-pipe: an agents snapshot entry is not an object");let s=o;if(typeof s.record==="object"&&s.record!==null&&!Array.isArray(s.record)){if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return{id:s.id,...s.record}}if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return s})}async function Wy(e){let t=new Set([...e.agents.values()].map((s)=>s.provider)),r,n;try{r=await e.peer.request("subscribe",{channel:gf},Qt),n=Vy(r)}catch(s){let i=fn(s);if(i!==void 0)return{ok:!1,reason:"refused",...i};if(e.log.error(`hightea-pipe: ${s instanceof Error?s.message:"the agents snapshot is unreadable"}`),hn(s))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's agent list"}}let o=n.filter((s)=>typeof s.id==="string"&&t.has(s.id));o.sort((s,i)=>String(s.id)<String(i.id)?-1:String(s.id)>String(i.id)?1:0);try{e.peer.notify("unsubscribe",{channel:gf})}catch(s){e.log.error(`hightea-pipe: dropping the agents subscription failed: ${s instanceof Error?s.name:typeof s}`)}return{ok:!0,result:{rows:o}}}async function Jy(e){let t;try{t=await e.peer.request("listSessions",{channel:"ahp-root://"},Qt)}catch(i){let a=fn(i);if(a!==void 0)return{ok:!1,reason:"refused",...a};if(e.log.error(`hightea-pipe: the session list is unreadable: ${i instanceof Error?i.name:typeof i}`),hn(i))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"}}let r=rs(t)&&Array.isArray(t.items)?t.items:void 0;if(r===void 0)return e.log.error("hightea-pipe: ahpd's listSessions result holds no items"),{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"};let n=[],o=[];for(let i of r){let a=rs(i)&&typeof i.resource==="string"&&i.resource!==""?i.resource:void 0;if(a===void 0){o.push("a summary with no resource");continue}let c;try{c=e.memberOf(a)}catch(l){o.push(`${a}: ${l instanceof Error?l.message:String(l)}`);continue}if(c===void 0)continue;let d=sf(i,c,e.hostToolsServer(a));if(d===void 0){o.push(`${a}: its summary names another member`);continue}let u=d._meta["hh/hostTools"];if(u!==void 0)e.rememberHostTools?.(a,u);n.push(d)}let s=new Set(n.map((i)=>i.resource));for(let i of e.ownSessions?.()??[]){if(s.has(i))continue;let a=e.memberOf(i);if(a===void 0)continue;let c=e.toolsAnswerOf?.(i);if(c===void 0){o.push(`${i}: provisional, and this pipe holds no tools answer for it yet`);continue}let d=tr({[it]:c},a,e.hostToolsServer(i));if(d===void 0)continue;n.push({resource:i,_meta:d})}if(o.length>0)e.log.error(`hightea-pipe: skipped ${o.length} unreadable session row(s): ${o.join("; ").slice(0,500)}`);return{ok:!0,result:{items:n}}}async function yf(e,t){let r=Xy(e.meta);if(r===void 0)return{ok:!1,reason:"outside"};let n=e.method;if(!Qy(n)&&!Xt(n))return{ok:!1,reason:"outside"};let o=e.params;if(!rs(o))return{ok:!1,reason:"outside"};let s="agentMemberId"in o;if(s&&(typeof o.agentMemberId!=="string"||o.agentMemberId===""))return{ok:!1,reason:"outside"};let i=s?o.agentMemberId:r.agentMemberId;if(Xt(n)){if(i!==void 0)return{ok:!1,reason:"outside"};let u=Ql(n,o);if(u!==void 0)return t.log.error(`hightea-pipe: refused a host request: ${u}`),{ok:!1,reason:"outside"};if(n==="subscribe")return Ky(t);if(n==="listSessions")return Jy(t);if(n==="authenticate")return e_(t,o);return ns(t,n,o)}if(n==="x-ahpd/agents/list"){if(i!==void 0)return{ok:!1,reason:"outside"};if(Object.keys(o).length!==0)return{ok:!1,reason:"outside"};return Wy(t)}if(i===void 0)return{ok:!1,reason:"outside"};let a=t.agents.get(i);if(a===void 0||a.provider!==o.id)return{ok:!1,reason:"unmapped"};let c=s?Yy(o):o,d=n==="x-ahpd/agents/put"&&Gy(c)?{...c,owner:qy}:c;return ns(t,n,d)}function Yy(e){let{agentMemberId:t,...r}=e;return r}function Xy(e){let t=nf.safeParse(e);return t.success?t.data:void 0}function rs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Qy(e){return e==="x-ahpd/agents/list"||e==="x-ahpd/agents/put"||e==="x-ahpd/agents/remove"||e==="x-ahpd/agents/enable"||e==="x-ahpd/agents/pause"||e==="x-ahpd/agents/disable"}async function e_(e,t){let r=t.target;if(typeof r.session!=="string"||e.memberOf(r.session)===void 0)return e.log.error("hightea-pipe: refused an authenticate aimed at a session this pipe did not make"),{ok:!1,reason:"outside"};let n=typeof r.session==="string"?e.hostToolsServer(r.session):void 0;if(n===void 0)return e.log.error("hightea-pipe: refused an authenticate: this host serves no Hightea MCP server, or the session has not yet said which customization is ours"),{ok:!1,reason:"outside"};if(r.customizationId!==n.customizationId)return e.log.error("hightea-pipe: refused an authenticate aimed at a server that is not this host's"),{ok:!1,reason:"outside"};if(t.resource!==n.resource)return e.log.error("hightea-pipe: refused an authenticate for a resource that is not this host's server"),{ok:!1,reason:"outside"};return ns(e,"authenticate",t)}async function ns(e,t,r){try{return{ok:!0,result:await e.peer.request(t,r,Qt)??null}}catch(n){let o=fn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};return e.log.error(`hightea-pipe: host request ${t} ended without an answer`+(hn(n)?" (timed out)":"")+`: ${n instanceof Error?n.name:typeof n}`),{ok:!1,reason:"timedOut"}}}import{createPrivateKey as h_,createPublicKey as p_,generateKeyPairSync as m_,sign as g_}from"node:crypto";import{appendFile as y_,chmod as __,readFile as bf,rename as Ef,writeFile as If}from"node:fs/promises";import{join as is}from"node:path";function t_(e){return JSON.stringify({v:1,workspaceId:e.workspaceId,roomId:e.roomId,rootMessageId:e.rootMessageId,authorMemberId:e.authorMemberId,clientId:e.clientId,body:e.body,attachmentIds:[...e.attachmentIds],createdAt:e.createdAt})}function pn(e){return new TextEncoder().encode(t_(e))}import{createPublicKey as r_,verify as n_}from"node:crypto";var o_=Buffer.from("302a300506032b6570032100","hex");function os(e,t){let r=e.signed;if(r===void 0)return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id} carries no signature`};let n=t.keys.find((a)=>a.keyId===r.keyId);if(n===void 0)return{ok:!1,code:"ROOM_ASKS_UNTRUSTED",why:`message ${e.id} is signed by key ${r.keyId}, which this host does not trust yet; its owner approves that browser with \`hightea approve\` and the ask goes through`};let o=pn({workspaceId:t.workspaceId,roomId:t.roomId,rootMessageId:e.replyTo??null,authorMemberId:e.from.memberId,clientId:r.clientId,body:e.text,attachmentIds:r.attachmentIds,createdAt:r.createdAt}),s=Buffer.from(r.signature,"base64url"),i=r_({key:Buffer.concat([o_,Buffer.from(n.publicKey,"base64url")]),format:"der",type:"spki"});if(s.length!==64||!n_(null,o,i,s))return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id}'s signature by ${n.name} does not match what the room returned (text, thread, author ${e.from.memberId}, or attachments)`};if(t.ownKeyId!==void 0&&n.keyId===t.ownKeyId&&!t.ownAgents.has(e.from.memberId))return{ok:!1,code:"KEY_NOT_FOR_AUTHOR",why:`message ${e.id} is signed by this host's key but attributed to ${e.from.memberId}, which this host does not run`};return{ok:!0,keyName:n.name,clientId:r.clientId,createdAt:r.createdAt}}function _f(e,t){let r=(a)=>a.deleted===!0?{id:a.id,deleted:!0}:a,n=(a)=>a.deleted===!0||os(a,t).ok,o=n(e.root),s=e.replies.filter(n).map(r),i=(o?0:1)+e.replies.length-e.replies.filter(n).length;return{...e,root:o?r(e.root):{id:e.root.id,omitted:!0},replies:s,...i===0?{}:{omitted:`${String(i)} unsigned messages omitted`}}}import{createHash as s_}from"node:crypto";import{existsSync as i_,readFileSync as a_}from"node:fs";import{join as c_}from"node:path";var u_="trusted-keys.json",d_=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,l_=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,f_=(e)=>Buffer.from(e).toString("base64url");function ss(e){if(!l_.test(e))return{error:"TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it"};return{keyId:f_(s_("sha256").update(Buffer.from(e,"base64url")).digest())}}function wf(e){let t=c_(e,u_);if(!i_(t))return{state:"missing",file:t};let r;try{r=JSON.parse(a_(t,"utf8"))}catch(o){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${o.message})`)}let n=r;if(typeof r!=="object"||r===null||n.v!==1||!Array.isArray(n.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let o of n.keys){let s=o,i=typeof s.publicKey==="string"?ss(s.publicKey):void 0;if(typeof s.name!=="string"||!d_.test(s.name)||i===void 0||"error"in i||s.keyId!==i.keyId||typeof s.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(o)}`)}return{state:"read",file:t,keys:n.keys}}class Z extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var w_="host-signing-key",Sf="hightea-acted-asks.jsonl",mn=600000,S_=2592000000,v_=20;async function kf(e,t=()=>Date.now()){let r=is(e,w_),n;try{n=await bf(r,"utf8")}catch(a){if(a.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${r} exists but cannot be read (${String(a)}); it is never regenerated, fix or remove it by hand`)}if(n===void 0){let a=m_("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),c=`${r}.${String(process.pid)}.tmp`;await If(c,a,{mode:384,flag:"wx"}),await __(c,384),await Ef(c,r),n=a}let o;try{if(o=h_({key:n,format:"pem"}),o.asymmetricKeyType!=="ed25519")throw Error(`a ${String(o.asymmetricKeyType)} key, not Ed25519`)}catch(a){throw Error(`HOST_KEY_UNREADABLE: ${r} is not an Ed25519 PKCS8 key (${String(a)}); it is never regenerated, fix or remove it by hand`)}let s=p_(o).export({format:"jwk"}).x,i=s===void 0?{error:"no public key"}:ss(s);if("error"in i)throw Error(`HOST_KEY_UNREADABLE: ${r}: ${i.error}`);return{privateKey:o,trusted:{name:"this-host",keyId:i.keyId,publicKey:s,addedAt:new Date(t()).toISOString()}}}function Rf(e,t,r=()=>Date.now()){let n=new Date(r()).toISOString(),o=pn({...t,attachmentIds:[],createdAt:n});return{keyId:e.trusted.keyId,createdAt:n,signature:g_(null,o,e.privateKey).toString("base64url")}}async function vf(e,t){if(e.configDir===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host's ahpd is too old for signed asks (it names no configDir)");let r=await e.hostKey;if(r instanceof Error)throw new Z("ROOM_ASKS_UNTRUSTED",r.message);let n;try{let s=await wf(e.configDir);n=s.state==="read"?s.keys:[]}catch(s){throw new Z("ROOM_ASKS_UNTRUSTED",String(s instanceof Error?s.message:s))}if(n.length===0)throw new Z("ROOM_ASKS_UNTRUSTED","this host trusts no key yet; its owner runs `hightea host trust add`");let o=r?.trusted;return{workspaceId:e.workspaceId,roomId:t,keys:o===void 0||n.some((s)=>s.keyId===o.keyId)?n:[...n,o],...o===void 0?{}:{ownKeyId:o.keyId},ownAgents:e.ownAgents}}function xf(e){let[t,r,n]=e.split("/");if(!t||!r||n!==void 0)throw new Z("ASK_UNSIGNED",`the wake's thread ref ${e} names no room thread`);return{roomId:t,rootMessageId:r}}function x_(e,t,r){if(t===void 0||t==="")throw new Z("ASK_UNSIGNED",`wake ${r.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);return t}function b_(e,t,r,n){let o=new Map;for(let i of e){let a=i.replyTo??i.id;if(a!==r)throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} carries message ${i.id} from thread ${a}, not ${n.threadRef}`);o.set(i.id,{id:i.id,from:{memberId:i.from.memberId},text:i.text,...i.replyTo===void 0?{}:{replyTo:i.replyTo},...i.deleted===void 0?{}:{deleted:!0},...i.signed===void 0?{}:{signed:i.signed}})}let s=new Set(o.keys());if(s.size!==t.length||t.some((i)=>!s.has(i)))throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} froze ${t.length} triggering messages and carried ${s.size}, not the same ones`);return o}class sr{#e;#o;#r=Promise.resolve();constructor(e){this.#e=e}async admit(e,t){let{roomId:r,rootMessageId:n}=xf(e.threadRef),o=await vf(this.#e,r),s=e.triggering,i=s===void 0?e.triggeringMessageIds:s.map((l)=>l.id);if(i===void 0||i.length===0)throw new Z("ASK_UNSIGNED",`wake ${e.deliveryId} names no triggering message to check`);let a=s===void 0?await this.#s(x_(this.#e,t,e),r,n,e.afterMessageId,new Set(i)):b_(s,i,n,e),c=(this.#e.now??Date.now)(),d=await this.#n(c),u=[];for(let l of i){let p=a.get(l);if(p===void 0)throw new Z("ASK_UNSIGNED",`triggering message ${l} is not in thread ${e.threadRef}`);let f=os(p,o);if(!f.ok)throw new Z(f.code,f.why);let m=d.filter((g)=>g.clientId===f.clientId);if(m.some((g)=>g.deliveryId!==e.deliveryId))throw new Z("ASK_REPLAYED",`the ask signed as ${f.clientId} (message ${l}) was already acted on under another wake`);if(m.length>0){let g=Math.min(...m.map((w)=>w.at));if(c-g>mn)throw new Z("ASK_REPLAYED",`wake ${e.deliveryId} was first admitted at ${new Date(g).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);continue}let y=Date.parse(f.createdAt);if(!Number.isFinite(y)||Math.abs(c-y)>mn)throw new Z("ASK_STALE",`message ${l} was signed at ${f.createdAt}, more than 10 minutes from this host's clock`);u.push({clientId:f.clientId,deliveryId:e.deliveryId,at:c})}if(u.length>0)await this.#c(d,u)}async view(e,t){return _f(t,await vf(this.#e,xf(e).roomId))}async#s(e,t,r,n,o){let s=new Map,i=n??r;for(let a=0;a<v_;a++){let c=await this.#e.readThread(e,{roomId:t,messageId:r,after:i});if(!E_(c))throw new Z("ASK_UNSIGNED",`read_thread answered no root and replies for ${t}/${r}`);for(let u of[c.root,...c.replies])if(o.has(u.id))s.set(u.id,u);let d=c.replies.at(-1);if(s.size===o.size||c.more!==!0||d===void 0)break;i=d.id}return s}async#n(e){this.#o??=(async()=>{let r=is(this.#e.configDir,Sf),n="";try{n=await bf(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} cannot be read: ${String(i)}`)}let o=[];for(let[i,a]of n.split(`
64
- `).entries()){if(a.trim()==="")continue;let c=JSON.parse(a);if(typeof c.clientId!=="string"||typeof c.deliveryId!=="string"||typeof c.at!=="number")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} line ${String(i+1)} is not an acted ask; fix or remove the file by hand`);o.push(c)}let s=o.filter((i)=>e-i.at<S_);if(s.length<o.length)await this.#l(r,s);return s})();let t=this.#o;return t.catch(()=>{if(this.#o===t)this.#o=void 0}),t}async#l(e,t){let r=`${e}.${String(process.pid)}.tmp`;await If(r,t.map((n)=>`${JSON.stringify(n)}
65
- `).join(""),{mode:384}),await Ef(r,e)}async#c(e,t){e.push(...t);let r=is(this.#e.configDir,Sf),n=this.#r.then(()=>y_(r,t.map((o)=>`${JSON.stringify(o)}
66
- `).join(""),{mode:384}));this.#r=n.catch(()=>{return}),await n}}function E_(e){if(e===null||typeof e!=="object")return!1;let t=e,r=(n)=>n!==null&&typeof n==="object"&&typeof n.id==="string";return r(t.root)&&Array.isArray(t.replies)&&t.replies.every(r)}class vt extends Error{}class us extends Error{}function k_(e,t){if(!ef.includes(e))return!1;return!Xt(e)||typeof t==="string"&&t.startsWith(tf)}function R_(e){let t=e.params.clientSeq;if(typeof t!=="number"||!Number.isInteger(t)||t<1)throw new us("ahp-host: a dispatch names no clientSeq");return t}var C_=[/No agent provider registered for: /u,/: this conversation has no matching configured ACP process authority/u];function Cf(e){if(e instanceof Z)return e.code;if(e instanceof us)return"OPERATION_SHAPE_INVALID";if(e instanceof vt)return"AGENT_NOT_MAPPED";let t=e instanceof Error?e.message:String(e);if(C_.some((r)=>r.test(t)))return"AGENT_NOT_MAPPED";return"WAKE_NOT_SENT"}var Ke=rf,as=15000,O_="x-hh/actions";function T_(e,t={}){let r=t.startedAtMs??Date.now(),n=Math.max(0,Date.now()-r),o=e.turnId===void 0||e.turnId===""?{}:{turnId:e.turnId};if(e.event==="session/ready")return{channel:e.session,action:{type:"session/ready",...o}};if(e.event==="chat/turnStarted")return{channel:e.chat,action:{type:"chat/turnStarted",...o,startedAt:new Date(r).toISOString()},...e.clientSeq===void 0?{}:{origin:{clientId:t.clientId??"hightea-gateway",clientSeq:e.clientSeq}}};if(e.event==="chat/turnComplete")return{channel:e.chat,action:{type:"chat/turnComplete",...o,duration:n}};let s=e.errorCode??"OPERATION_SHAPE_INVALID";if(s==="TURN_CANCELLED")return{channel:e.chat,action:{type:"chat/turnCancelled",...o,duration:n}};return{channel:e.chat,action:{type:"chat/error",...o,duration:n,part:{kind:"error",error:{errorType:s,message:""}}}}}var ir=(e,t)=>JSON.stringify([e,t]);function A_(e){let t;for(let r of e.triggering??[]){let n=r.signed===void 0?Number.NaN:Date.parse(r.signed.createdAt);if(!Number.isFinite(n))continue;if(t===void 0||n>t)t=n}return t}var sk=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Be([S().min(1),ln]))}).strict(),$_=k({event:ne(["session.created","turn.started","turn.finished","turn.error"]),houseId:S().min(1),deliveryId:S().min(1),sessionId:S().min(1),chatId:S().min(1),turnId:S().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict(),P_={"session.created":"session/ready","turn.started":"chat/turnStarted","turn.finished":"chat/turnComplete","turn.error":"x-hh/turnFailed"};function N_(e){return{event:P_[e.event],channel:e.event==="session.created"?e.sessionId:e.chatId,workspaceId:e.houseId,deliveryId:e.deliveryId,session:e.sessionId,chat:e.chatId,...e.turnId===void 0?{}:{turnId:e.turnId},turnState:e.turnState,statusCode:e.statusCode,...e.errorCode===void 0?{}:{errorCode:e.errorCode},...e.errorDetail===void 0?{}:{errorDetail:e.errorDetail}}}var z_=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Ee())}).strict(),M_=(e)=>e.turnId===void 0?e.deliveryId:ir(e.deliveryId,e.turnId);function cs(e){return`${e.issues.slice(0,3).map((r)=>`${r.path.join(".")||"(record)"} ${r.message}`).join("; ")}${e.issues.length>3?`; and ${e.issues.length-3} more`:""}`}function Of(e){let t=Array.isArray(e)?e[1]:e;if(typeof t==="object"&&t!==null){let r=t.event;if(typeof r==="string")return`event=${r}`}return Array.isArray(e)?`a frame of ${typeof t}`:`${e===null?"null":typeof e}`}function ds(e,t){let r=z_.safeParse(e);if(!r.success)throw Error(`ahp-host: invalid durable state: ${cs(r.error)}`);let n=[],o=0,s=0;if(r.data.lastStatus.forEach((a,c)=>{let d=Be([S().min(1),Ee()]).safeParse(a),u=d.success?d.data[0]:"",l=d.success?ln.safeParse(d.data[1]):void 0,p=d.success&&l?.success===!1?$_.safeParse(d.data[1]):void 0,f=l?.success===!0?l.data:p?.success===!0?N_(p.data):void 0;if(f===void 0){s+=1;let m=d.success&&typeof d.data[1]==="object"&&d.data[1]!==null&&"houseId"in d.data[1],y=p?.success===!1&&m?`pre-0.1.11 shape: ${cs(p.error)}`:l?.success===!1?cs(l.error):"not a [key, frame] entry";t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (${Of(a)}): ${y}`);return}if(M_(f)!==u){s+=1,t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (event=${f.event}): its key names a different delivery or turn`);return}if(l?.success!==!0)o+=1,t.error(`ahp-host: upgraded durable status frame lastStatus[${c}] (${Of(a)} -> event=${f.event}) from the pre-0.1.11 shape`);n.push([u,f])}),o>0||s>0)t.error(`ahp-host: durable state repaired: ${o} status frame(s) upgraded from the pre-0.1.11 shape, ${s} dropped; the pipe starts and rewrites the state`);return{sessions:r.data.sessions.map(([a,c])=>[a,{sessionUri:c.sessionUri,...c.chatUri===void 0?{}:{chatUri:c.chatUri}}]),dispatched:r.data.dispatched,lastStatus:n}}class ls{#e=new Map;#o=new Map;#r=new Map;#s=[];#n=new Map;#l=new Set;#c=new Map;#f=new Map;#u=new Map;#h=new Map;#a=new Map;#m=Promise.resolve();#d;#y=!1;#w=0;#_=0;#S=!1;#v="";peer;cloud;options;constructor(e,t,r){this.peer=e,this.cloud=t,this.options=r,e.onMessage((n)=>{this.#B(n).catch((o)=>{if(o!==this.#d)this.options.log.error(`ahp-host: local turn handling failed: ${String(o)}`)})})}get registry(){return{workspaceId:this.options.workspaceId,agents:this.options.agents,sessions:this.#e,parked:this.#f}}agentMemberOf(e){for(let[t,r]of this.#e){if(r.sessionUri!==e)continue;let n;try{n=JSON.parse(t)}catch(o){throw Error(`ahp-host: session key ${t} of ${e} is not a session key: ${String(o)}`)}if(!Array.isArray(n)||typeof n[1]!=="string"||n[1]==="")throw Error(`ahp-host: session key ${t} of ${e} names no member`);return n[1]}return}async start(e){this.#y=!1;let t=await this.peer.request("initialize",{channel:"ahp-root://",protocolVersions:[Ke],clientId:e},as);if(t?.protocolVersion!==Ke)throw Error(`ahp-host: the local ahpd answered protocol ${String(t?.protocolVersion)}, not ${Ke}`);let r=await this.options.store?.load();if(r===void 0){this.#x();return}let n=ds(r,this.options.log);for(let[a,c]of n.sessions){if(c.chatUri!==void 0){this.#e.set(a,{sessionUri:c.sessionUri,chatUri:c.chatUri});continue}let d;try{d=await this.#D(c.sessionUri)}catch(u){if(Cf(u)==="AGENT_NOT_MAPPED"){this.#k(a,c.sessionUri,u);continue}throw u}this.#l.delete(c.sessionUri),this.peer.notify("unsubscribe",{channel:c.sessionUri}),this.#e.set(a,{sessionUri:c.sessionUri,chatUri:d})}let o=[],s=this.#e,i=new Map(n.lastStatus);for(let[a,c]of n.dispatched)for(let d of c){let u;try{u=Be([S().min(1),S().min(1)]).parse(JSON.parse(d))}catch{throw Error("ahp-host: invalid durable state attempt")}let[l,p]=u,f=i.get(d);if(f!==void 0&&(f.deliveryId!==l||f.turnId!==p))throw Error("ahp-host: invalid durable state attempt status");if(f?.event==="chat/turnComplete"||f?.event==="x-hh/turnFailed")continue;let m=s.get(a);if(m?.chatUri===void 0)throw Error("ahp-host: invalid durable state attempt session");o.push({event:"x-hh/turnFailed",workspaceId:this.options.workspaceId,deliveryId:l,turnId:p,channel:m.chatUri,session:m.sessionUri,chat:m.chatUri,turnState:"error",statusCode:"HOST_RESTARTED",errorCode:"HOST_RESTARTED"})}for(let[a,c]of n.dispatched)this.#o.set(a,new Set(c));for(let[a,c]of n.lastStatus)this.#a.set(a,c);for(let a of o)await this.#E(a);await this.#b(),this.#x()}#x(){this.#y=!0;for(let e of this.#s.splice(0))this.#O(e)}#k(e,t,r){let n=r instanceof Error?r.message:String(r);this.#f.set(e,n),this.#e.set(e,{sessionUri:t}),this.options.log.error(`hightea-pipe: saved session ${t} is parked: ahpd will not resume it and its agent is not mapped (AGENT_NOT_MAPPED), so its wakes are refused by name; every other agent on this host carries on: ${n}`)}#C(e,t){if(!(typeof t==="object"&&t!==null&&Array.isArray(t.protocolVersions)?t.protocolVersions.filter((s)=>typeof s==="string"):[]).includes(Ke)){this.cloud.reply(e,{error:{code:-32005,message:"UnsupportedProtocolVersion",data:{supportedVersions:[Ke]}}});return}let n=t._meta;if(typeof n==="object"&&n!==null&&n[O_]===!0)this.#S=!0;let o=t.clientId;if(typeof o==="string"&&o!=="")this.#v=o;if(!this.#y){this.#s.push(e);return}this.#O(e)}#O(e){let t=this.options.handshake,r=t?.sources?.(),n={...t===void 0?{}:{ahpd:t.ahpd},...t?.capabilities===void 0||t.capabilities.length===0?{}:{capabilities:t.capabilities},...r===void 0||r.length===0?{}:{sources:r}};this.cloud.reply(e,{result:{protocolVersion:Ke,serverSeq:0,...t===void 0?{}:{serverInfo:t.plugin},...Object.keys(n).length===0?{}:{_meta:n},snapshots:[]}})}#b(){let e={sessions:[...this.#e],dispatched:[...this.#o].map(([t,r])=>[t,[...r]]),lastStatus:[...this.#a]};return this.#m=this.#m.then(()=>this.options.store?.save(e)).catch((t)=>{if(this.#d===void 0){this.#d=Error("ahp-host: durable state write failed",{cause:t});for(let r of this.#r.values())r.cancelled=!0;this.options.log.error(`${this.#d.message}: ${String(t)}`)}throw this.#d}),this.#m}async#j(e,t){if(!(typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).sort().join(",")==="agentMemberId,workspaceId"&&t.workspaceId===this.options.workspaceId&&typeof t.agentMemberId==="string")){if(e!==void 0)this.cloud.answer(e,{ok:!1,code:"OPERATION_SHAPE_INVALID"});return}let n=t.agentMemberId;for(let s of this.#r.values())if(s.workspaceId===this.options.workspaceId&&s.agentMemberId===n)s.cancelled=!0;let o=[];for(let[s,i]of this.#n){let a=i.filter((d)=>d.meta.agentMemberId!==n),c=this.#e.get(s);for(let d of i.filter((u)=>u.meta.agentMemberId===n))o.push(this.#E({event:"x-hh/turnFailed",workspaceId:d.meta.workspaceId,deliveryId:d.meta.deliveryId,channel:c?.chatUri??"",session:c?.sessionUri??"",chat:c?.chatUri??"",turnId:d.turnId,turnState:"error",statusCode:"GRANT_REVOKED",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}));this.#n.set(s,a)}if(await Promise.all(o),e!==void 0)this.cloud.answer(e,{ok:!0})}async fromCloud(e){let t=e?.id;if(e?.method==="initialize"){if(t===void 0){this.options.log.error("hightea-pipe: an initialize frame carries no id; nothing to answer");return}this.#C(t,e.params);return}if(!this.#y||this.#d!==void 0){if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"WAKE_NOT_SENT"});return}let r=typeof e?.method==="string"?e.method:void 0;if(r!==void 0&&k_(r,t)){let o=String(t??""),s=await yf({method:r,params:e.params,meta:e._meta},{agents:this.options.agents,memberOf:(i)=>this.agentMemberOf(i),peer:this.peer,log:this.options.log,hostToolsServer:(i)=>this.#P(i),rememberHostTools:(i,a)=>this.#h.set(i,a),ownSessions:()=>[...this.#e.values()].map((i)=>i.sessionUri),toolsAnswerOf:(i)=>this.#h.get(i)});this.cloud.hostRequestAnswer(o,s);return}if(e?.method==="x-hightea/revoke")return this.#j(t,e.params).catch(()=>{if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"OPERATION_SHAPE_INVALID"})});let n=mf(e,this.registry);if(!n.ok){if(n.code==="WAKE_TEXT_NOT_ALLOWED")this.options.log.error(`hightea: refused turn ${String(t??"")}: its text is not the delivery's own wake (WAKE_TEXT_NOT_ALLOWED); nothing reached the agent`);if(t===void 0){let o=e?.params?._meta,s=typeof o?.deliveryId==="string"?o.deliveryId:"unknown";this.options.log.error(`hightea-pipe: refused ${String(e.method)} for delivery ${s}: ${n.code}; nothing reached the agent`)}else this.cloud.answer(t,n);return}try{let o;if(n.operation==="createSession"){let s=this.options.agents.get(n.meta.agentMemberId);if(s===void 0)throw new vt("ahp-host: local agent mapping disappeared");let i,a;try{a=await this.options.startSession({owner:this.options.owner,provider:s.provider,workingDirectory:I_(s.workingDirectory),tools:this.options.tools,...s.settings===void 0?{}:{config:s.settings}},async(d)=>{if(this.options.store?.reserve!==void 0){let u=await this.options.store.reserve(n.sessionKey,d);if(this.#e.set(n.sessionKey,{sessionUri:u}),u!==d)throw i=u,Error("ahp-host: durable session mapping already won by an existing URI");await this.#b();return}this.#e.set(n.sessionKey,{sessionUri:d}),await this.#b()})}catch(d){if(i===void 0)throw d;a=i}if(this.#e.get(n.sessionKey)?.sessionUri!==a)throw Error("ahp-host: created session differs from its durable reservation");let c=i!==void 0?await this.#D(a):await this.#F(a);this.#e.set(n.sessionKey,{sessionUri:a,chatUri:c}),this.#c.set(a,Promise.resolve()),await this.#b(),await this.#E({event:"session/ready",workspaceId:n.meta.workspaceId,deliveryId:n.meta.deliveryId,...n.meta.turnId===void 0?{}:{turnId:n.meta.turnId},channel:c,session:a,chat:c,turnState:"created",statusCode:"SESSION_CREATED"})}else if(n.operation==="subscribe"){let s=n.frame.params.channel,i=this.#e.get(n.sessionKey);if(i?.sessionUri!==s||i.chatUri===void 0)throw Error("ahp-host: a subscribe reached a session this host has no chat for");o={snapshot:{resource:s,state:{defaultChat:i.chatUri}}}}else await this.#T(n.sessionKey,n.frame,{...n.meta,...n.triggering===void 0?{}:{triggering:n.triggering},...n.readBearer===void 0?{}:{readBearer:n.readBearer}},n.turnId);if(t!==void 0)if(o===void 0)this.cloud.answer(t,{ok:!0});else this.cloud.reply(t,{result:o})}catch(o){let s=Cf(o);if(this.options.log.error(`ahp-host: cloud operation ${n.operation} failed (${s}): ${String(o)}`),t!==void 0)this.cloud.answer(t,{ok:!1,code:s})}}async#M(e,t){let r=this.#c.get(e);if(r===void 0)r=this.#D(e).then((n)=>{if(n!==t)throw Error("ahp-host: saved session answered a different chat")}),this.#c.set(e,r),r.catch(()=>{if(this.#c.get(e)===r)this.#c.delete(e)});await r}async#D(e){let t=await this.options.startSession({owner:this.options.owner,resume:e});if(t!==e)throw Error(`ahp-host: resumed session ${t} differs from ${e}`);return this.#F(e)}async#F(e){let t=await this.peer.request("subscribe",{channel:e},as);this.#l.add(e),this.#L(e,t?.snapshot?.state?.customizations),this.#U(e,t?.snapshot?.state);let r=t?.snapshot?.state?.defaultChat;if(typeof r!=="string"||r.length===0)throw Error(`ahp-host: ${e} answered no defaultChat`);return r}async#T(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0||n===void 0)throw Error("ahp-host: a turn reached dispatch without its mapping or turn id");let s=this.#o.get(e)??new Set,i=ir(r.deliveryId,n);if(s.has(i)){let c=this.#a.get(i);if(await this.#m,c!==void 0)this.#N(c);return}if(this.options.admitTurn!==void 0)await this.options.admitTurn(r,r.readBearer);await this.#M(o.sessionUri,o.chatUri);let a=this.#r.get(e);if(a!==void 0){if(a.deliveryId===r.deliveryId)a.cancelled=!0;let c=this.#n.get(e)??[];for(let u of c)if(u.meta.deliveryId===r.deliveryId&&u.turnId!==n)s.add(ir(u.meta.deliveryId,u.turnId));s.add(i),this.#o.set(e,s);let d=c.filter((u)=>u.meta.deliveryId!==r.deliveryId||u.turnId===n);if(!d.some((u)=>u.meta.deliveryId===r.deliveryId))d.push({frame:t,meta:r,turnId:n});this.#n.set(e,d),await this.#b();return}await this.#R(e,t,r,n)}async#R(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0)throw Error("ahp-host: dispatch has no mapped chat");if(this.#$(o.sessionUri,o.chatUri).length>0)throw Error("ahp-host: wake already active for this session and chat");let s={key:e,deliveryId:r.deliveryId,workspaceId:r.workspaceId,agentMemberId:r.agentMemberId,sessionUri:o.sessionUri,chatUri:o.chatUri,turnId:n,startedAtMs:Date.now(),clientSeq:R_(t),cancelled:!1,stopReason:void 0,finishing:!1},i=this.#o.get(e)??new Set;if(i.add(ir(r.deliveryId,n)),this.#o.set(e,i),this.#r.set(e,s),await this.#b(),s.cancelled){this.#r.delete(e),await this.#E({event:"x-hh/turnFailed",workspaceId:r.workspaceId,deliveryId:r.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:n,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}),await this.#t(s);return}if(!this.#l.has(o.chatUri))this.#l.add(o.chatUri),this.peer.request("subscribe",{channel:o.chatUri},as);this.peer.notify("dispatchAction",{...t.params,clientSeq:++this.#w})}#$(e,t){return[...this.#r.values()].filter((r)=>r.sessionUri===e&&r.chatUri===t)}#g(e){this.#p(e)}#A(e,t){let r=this.#P(e);if(r===void 0||t.id!==r.customizationId)return;if(e===""||this.agentMemberOf(e)===void 0)return;let n=ye(t.state)?t.state:void 0;if(n?.kind!=="authRequired"||n.reason!=="expired")return;this.cloud.authRequired({channel:e,resource:r.resource,reason:"expired"})}#P(e){let t=this.options.hostTools;if(t===void 0)return;let r=this.#u.get(e);return r===void 0?void 0:{resource:t.resource,customizationId:r}}#L(e,t){let r=this.options.hostTools;if(r===void 0||!Array.isArray(t))return;let n=t.find((s)=>ye(s)&&s.type==="mcpServer"&&s.name===r.name),o=n!==void 0&&typeof n.id==="string"&&n.id!==""?n.id:void 0;if(o===void 0)this.#u.delete(e);else this.#u.set(e,o);if(o===void 0)this.#h.set(e,{available:!1,reason:"its backend published no Hightea MCP server"});else this.#h.set(e,{available:!0})}#U(e,t){if(this.options.hostTools===void 0)return;let r=ye(t)?ye(t._meta)?t._meta:t:void 0,n=er.safeParse(r?.[it]);if(n.success)this.#h.set(e,n.data)}#H(e){let t=this.agentMemberOf(e),r=this.#h.get(e);if(t===void 0||r===void 0)return;let n=this.#P(e),o={available:r.available,...r.reason===void 0?{}:{reason:r.reason},...r.available&&n!==void 0?{server:n}:{}};this.cloud.sessionChanged({channel:"ahp-root://",session:e,changes:{_meta:{"hh/agentMemberId":t,"hh/hostTools":o}}})}#p(e){if(!ye(e)){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged carries no params object");return}let t=e.session;if(typeof t!=="string"||t===""){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged names no session");return}let r=this.agentMemberOf(t);if(r===void 0)return;let n=ye(e.changes)?e.changes:void 0,o=n!==void 0&&ye(n._meta)?n._meta:void 0,s=tr(o,r,this.#P(t));if(s===void 0){this.options.log.error(`hightea-pipe: ${t} changed under another member's name; nothing was sent`);return}let i=s["hh/hostTools"];if(i===void 0){if(o?.[it]!==void 0)this.options.log.error(`hightea-pipe: ${t} changed ${it} to a shape this host does not read`);return}this.#h.set(t,i),this.cloud.sessionChanged({channel:"ahp-root://",session:t,changes:{_meta:{"hh/agentMemberId":s["hh/agentMemberId"],"hh/hostTools":i}}})}async#B(e){let t=e?.params;if(t?.action?.type==="session/customizationsChanged"){if(typeof t.channel==="string"&&this.agentMemberOf(t.channel)!==void 0){let i=this.#u.get(t.channel);if(this.#L(t.channel,t.action.customizations),this.#u.get(t.channel)!==i)this.#H(t.channel)}return}if(t?.action?.type==="session/mcpServerStateChanged"){this.#A(typeof t.channel==="string"?t.channel:"",t.action);return}if(ye(e)&&e.method==="root/sessionSummaryChanged")return this.#g(e.params);let r=e?.params,n=r?.action;if(n===void 0||typeof r?.channel!=="string")return;if(n.type==="session/inputNeededSet"){let i=n.request,a=i?.kind==="toolConfirmation"&&i.toolCall?.status==="pending-confirmation",c=i?.kind==="chatInput";if(!a&&!c)return;let d=typeof i.request?.id==="string"&&i.request.id!==""?i.request.id:typeof i.id==="string"&&i.id!==""?i.id:"unknown",u=typeof i.chat==="string"?i.chat:"",l=r.channel,p=this.#$(l,u),f=a&&typeof i.turnId==="string"?i.turnId:"",m=p.filter((w)=>!w.cancelled&&!w.finishing&&w.stopReason===void 0),y=a&&f==="",g=f!==""?p.find((w)=>w.turnId===f):m.length===1?m[0]:void 0;if(g===void 0||y){this.#_++;let w=f!==""?"INPUT_REQUEST_UNMATCHED_TURN":"INPUT_REQUEST_UNATTRIBUTED";this.options.log.error(`hightea-pipe: ${w} ${JSON.stringify({sessionId:l,chatId:u,kind:i.kind,requestId:d,droppedCount:this.#_,...f===""?{liveWakeCount:m.length}:{turnId:f}})}`)}if(g===void 0||g.cancelled||g.finishing||g.stopReason!==void 0)return;if(g.stopReason=y?"OPERATION_SHAPE_INVALID":c?"INPUT_REQUIRED":"APPROVAL_REQUIRED",g.stopStatusCode=y?"INPUT_REQUEST_UNATTRIBUTED":g.stopReason,y)g.stopDetail=`INPUT_REQUEST_UNATTRIBUTED:${d}`.slice(0,256);this.peer.notify("dispatchAction",{channel:g.chatUri,clientSeq:++this.#w,action:{type:"chat/turnCancelled",turnId:g.turnId,duration:Math.max(0,Date.now()-g.startedAtMs)}});return}let o=[...this.#r.values()].find((i)=>i.chatUri===r.channel&&i.turnId===n.turnId);if(o===void 0||o.finishing)return;let s={workspaceId:o.workspaceId,deliveryId:o.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:o.turnId,clientSeq:o.clientSeq};if(n.type==="chat/turnStarted"){if(o.stopReason!==void 0)return;await this.#E({event:"chat/turnStarted",...s,turnState:"running",statusCode:"TURN_RUNNING"},o.startedAtMs)}else if(n.type==="chat/turnComplete"||n.type==="chat/turnCancelled"||n.type==="chat/error"){o.finishing=!0;let i=n.type==="chat/turnComplete"&&o.stopReason===void 0,a=n.type==="chat/turnCancelled"&&o.stopReason===void 0,c=o.stopReason??(a?"TURN_CANCELLED":"OPERATION_SHAPE_INVALID"),d=o.stopStatusCode??o.stopReason??(a?"TURN_CANCELLED":"TURN_ENDED");await this.#E(i?{event:"chat/turnComplete",...s,turnState:"finished",statusCode:"TURN_FINISHED"}:{event:"x-hh/turnFailed",...s,turnState:"error",statusCode:d,errorCode:c,...o.stopDetail===void 0?{}:{errorDetail:o.stopDetail}},o.startedAtMs),this.#r.delete(o.key),await this.#t(o)}}async#t(e){if(this.#r.has(e.key))return;let r=(this.#n.get(e.key)??[]).shift();if(r===void 0){this.#l.delete(e.chatUri),this.#l.delete(e.sessionUri),this.peer.notify("unsubscribe",{channel:e.chatUri}),this.peer.notify("unsubscribe",{channel:e.sessionUri}),this.#c.delete(e.sessionUri);return}let n=A_(r.meta),o=n===void 0&&r.meta.readBearer===void 0,s=n!==void 0&&Date.now()-n>mn;if(!s&&!o)try{await this.#R(e.key,r.frame,r.meta,r.turnId);return}catch(a){if(this.#d!==void 0)throw a}if(s||o)this.options.log.error(`ahp-host: queued wake ${r.meta.deliveryId} retired before dispatch (${n===void 0?"ASK_UNSIGNED: no signed triggering envelope and no bearer":`ASK_STALE: newest trigger signed at ${new Date(n).toISOString()}`})`);let i=this.#e.get(e.key);await this.#E({event:"x-hh/turnFailed",workspaceId:r.meta.workspaceId,deliveryId:r.meta.deliveryId,channel:i?.chatUri??e.chatUri,session:i?.sessionUri??e.sessionUri,chat:i?.chatUri??e.chatUri,turnId:r.turnId,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:o?"ASK_UNSIGNED":"ASK_STALE"}),await this.#t(e)}#E(e,t){let r=ff(e);if(this.#a.set(r.turnId===void 0?r.deliveryId:ir(r.deliveryId,r.turnId),r),this.options.store===void 0)return this.#N(r,t),Promise.resolve();return this.#b().then(()=>{this.#N(r,t)})}#N(e,t){if(!this.#S)return this.cloud.status(e);this.cloud.action(T_(e,{...this.#v===""?{}:{clientId:this.#v},...t===void 0?{}:{startedAtMs:t}}))}}var gn=Be([S().min(1),S().min(1),S().min(1)]),D_=k({id:S(),version:H(1),tuple:gn,owner:S().min(1),sessionUri:S().regex(or)}).strict(),Tf=(e)=>`session-${Pf("sha256").update(e).digest("hex").slice(0,32)}`,Af=k({id:S(),version:H(1),tuple:gn,sessionUri:S().regex(or),chatUri:S().min(1)}).strict(),$f=(e)=>`chat-${Pf("sha256").update(e).digest("hex").slice(0,32)}`;function Nf(e,t,r,n,o){let s=new Map,i=new Map,a=async(f,m)=>{if(o===void 0||m.chatUri===void 0||i.get(f)===m.chatUri)return;let y=gn.parse(JSON.parse(f)),g=$f(f);try{await o.put({id:g,version:1,tuple:y,sessionUri:m.sessionUri,chatUri:m.chatUri},{createOnly:!0})}catch(w){if(w?.code!==-32010)throw w;let b=Af.safeParse(await o.get(g));if(!b.success||b.data.sessionUri!==m.sessionUri||b.data.chatUri!==m.chatUri)throw Error("ahp-host: conflicting durable session chat",{cause:w})}i.set(f,m.chatUri)},c=async()=>{let f=new Map;for(let m of await o?.list()??[]){let y=Af.safeParse(m);if(!y.success)throw Error("ahp-host: invalid durable session chat");let g=JSON.stringify(y.data.tuple);if(y.data.id!==$f(g))throw Error("ahp-host: durable session chat has a different key");f.set(g,{sessionUri:y.data.sessionUri,chatUri:y.data.chatUri})}return f},d=(f)=>{let m=D_.safeParse(f);if(!m.success)throw Error("ahp-host: invalid durable session mapping");let y=m.data,g=JSON.stringify(y.tuple);if(y.id!==Tf(g)||y.owner!==t)throw Error("ahp-host: durable session mapping has a different key or owner");return[g,{sessionUri:y.sessionUri}]},u=async(f,m)=>{let y=gn.parse(JSON.parse(f));if(JSON.stringify(y)!==f||!or.test(m))throw Error("ahp-host: invalid session mapping to publish");let g=s.get(f);if(g!==void 0)return g.sessionUri;let w=Tf(f),b=m;try{await e.put({id:w,version:1,tuple:y,owner:t,sessionUri:m},{createOnly:!0})}catch(v){if(v?.code!==-32010)throw v;let x=await e.get(w);if(x===void 0)throw v;let[I,C]=d(x);if(I!==f)throw Error("ahp-host: conflicting durable session mapping",{cause:v});if(C.sessionUri!==m&&await r(C.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner",{cause:v});b=C.sessionUri}return s.set(f,{sessionUri:b}),b},l=async(f,m)=>{if(await u(f,m.sessionUri)!==m.sessionUri)throw Error("ahp-host: conflicting durable session mapping")},p=(f)=>e.put({id:"state",version:2,state:{dispatched:f.dispatched,lastStatus:f.lastStatus}});return{reserve:u,load:async()=>{let f=await e.get("state"),m={sessions:[],dispatched:[],lastStatus:[]};if(f!==void 0){if(f.id!=="state"||f.version!==1&&f.version!==2||!("state"in f))throw Error("ahp-host: invalid durable state record");let g=f.version===1?f.state:typeof f.state==="object"&&f.state!==null?{sessions:[],...f.state}:f.state,w=ds(g,n);if(f.version===2&&w.sessions.length!==0)throw Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");m=w}let y=new Map;for(let g of await e.list()){if(g.id==="state")continue;let[w,b]=d(g);if(await r(b.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner");y.set(w,b)}s.clear();for(let[g,w]of y)s.set(g,w);for(let[,g]of m.sessions)if(await r(g.sessionUri)!==t)throw Error("ahp-host: legacy session belongs to an unknown or different owner");for(let[g,w]of m.sessions)await l(g,w),y.set(g,w);if(f?.version===1)await p(m);i.clear();for(let[g,w]of await c()){let b=y.get(g);if(b===void 0||b.sessionUri!==w.sessionUri)throw Error("ahp-host: durable session chat names no mapping or a different session");y.set(g,{sessionUri:b.sessionUri,chatUri:w.chatUri}),i.set(g,w.chatUri)}return{sessions:[...y],dispatched:m.dispatched,lastStatus:m.lastStatus}},save:async(f)=>{for(let[m,y]of f.sessions)await l(m,y),await a(m,y);await p(f)}}}import{randomUUID as L_}from"node:crypto";var U_=15000,Z_=(e)=>{if(e===null||typeof e!=="object")return;let t=e.message;return typeof t==="string"&&rr.includes(t)?t:void 0};function zf(e){let{log:t,receive:r}=e,n=!1,o=1000,s,i,a=new Map,c=(g,w=!0)=>{if(w)t.error(`hightea-pipe: ${g}`);for(let b of a.values())clearTimeout(b.timer),b.reject(Error(g));a.clear()},d=(g,w)=>{if(!n&&g!==void 0&&g===i&&g.live&&g.socket?.readyState===1)try{return g.socket.send(JSON.stringify(w)),!0}catch{}return t.error("hightea-pipe: CONTROL_SOCKET_UNAVAILABLE"),!1},u=(g)=>d(i,g),l=(g,w,b)=>{if(g===void 0||g.readyState>=2)return;try{if(w===void 0)g.close();else g.close(w,b)}catch{t.error("hightea-pipe: CONTROL_SOCKET_CLOSE_FAILED")}},p=(g,w)=>{if(n)return;if(n=!0,s!==void 0)clearTimeout(s);if(s=void 0,i!==void 0)i.live=!1;c("CONTROL_SOCKET_CLOSED",!1),l(i?.socket,g,w)},f=(g,w)=>{let b;try{b=JSON.parse(String(g.data))}catch{t.error("hightea-pipe: CONTROL_FRAME_INVALID");return}if(b!==null&&typeof b==="object"&&!Array.isArray(b)){let v=b;if(v.method===void 0&&(("result"in v)||("error"in v))){let x=typeof v.id==="string"?a.get(v.id):void 0;if(x===void 0){t.error("hightea-pipe: CONTROL_RESPONSE_UNKNOWN");return}if(a.delete(v.id),clearTimeout(x.timer),v.jsonrpc==="2.0"&&"result"in v&&!("error"in v))x.resolve(v.result);else{let I="error"in v?Z_(v.error):void 0;t.error(`hightea-pipe: CONTROL_REQUEST_REFUSED${I===void 0?"":` ${I}`}`),x.reject(Error(I===void 0?"CONTROL_REQUEST_REFUSED":`CONTROL_REQUEST_REFUSED ${I}`))}return}}r(b,w)},m=()=>{if(n)return;let g={live:!0,opened:!1};i=g;let w=()=>{if(n||s!==void 0)return;let x=o;o=Math.min(o*2,60000),s=setTimeout(()=>{s=void 0,m()},x)},b=(x)=>{if(n||i!==g||!g.live)return;g.live=!1,c(x),l(g.socket),w()},v=(x,I)=>{if(n||i!==g)return;t.error(`${I===void 0||I===""?`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}`:`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}: ${I}`}`),p()};try{let x=e.dial((E)=>{if(E===401||E===403)v(E);else b("CONTROL_SOCKET_ERROR")});g.socket=x;let I={send:(E)=>d(g,E),close:(E,A)=>p(E,A)};x.addEventListener("message",(E)=>{if(!n&&i===g&&g.live)f(E,I)}),x.addEventListener("error",()=>b("CONTROL_SOCKET_ERROR")),x.addEventListener("close",(E)=>{if(E.code===4003||E.code===4004)v(E.code,E.reason);else b("CONTROL_SOCKET_CLOSED")});let C=()=>{if(n||i!==g||!g.live||g.opened)return;g.opened=!0,o=1000,e.opened?.(I)};if(x.addEventListener("open",C),n||!g.live)l(x);else if(x.readyState===1)C()}catch{b("CONTROL_SOCKET_ERROR")}},y=(g,w,b)=>new Promise((v,x)=>{let I=setTimeout(()=>{a.delete(g),t.error("hightea-pipe: CONTROL_REQUEST_TIMEOUT"),x(Error("CONTROL_REQUEST_TIMEOUT"))},U_);if(a.set(g,{resolve:v,reject:x,timer:I}),!u({jsonrpc:"2.0",id:g,method:w,params:b}))a.delete(g),clearTimeout(I),x(Error("CONTROL_SOCKET_UNAVAILABLE"))});return queueMicrotask(m),{send:u,close:p,answer:(g,w)=>u(w.ok?{jsonrpc:"2.0",id:g,result:null}:{jsonrpc:"2.0",id:g,error:{code:-32000,message:w.code}}),reply:(g,w)=>u("result"in w?{jsonrpc:"2.0",id:g,result:w.result}:{jsonrpc:"2.0",id:g,error:w.error}),status:(g)=>u({jsonrpc:"2.0",method:"x-hightea/status",params:g}),sessionChanged:(g)=>void u({jsonrpc:"2.0",method:"root/sessionSummaryChanged",params:g}),action:(g)=>u({jsonrpc:"2.0",method:"action",params:g}),authRequired:(g)=>u({jsonrpc:"2.0",method:"auth/required",params:g}),sourcePush:(g)=>y(`push:${L_()}`,"x-hightea/source/push",g),hostRequestAnswer:(g,w)=>void u({jsonrpc:"2.0",id:g,...of(w)})}}import{spawn as V_}from"node:child_process";import{createHash as Gf}from"node:crypto";import{createInterface as W_}from"node:readline";import{randomUUID as Mf}from"node:crypto";var yn=1e4,j_=1024;function F_(e,t,r){let n=0;while(n<e.length&&t+te(e[n])>r)n++;let o=[],s=t;for(let i=n;i<e.length;i++){let a=e[i],c=te(a)+(o.length===0?0:1);if(o.length>0&&s+c>r)break;o.push(a),s+=c}return{dropped:e.slice(0,n),batch:o}}class ar{sourceId;#e="e_"+Mf();#o=0n;#r=[];#s=!1;#n;#l=-1/0;#c=0;#f=-1/0;#u=!0;#h=new AbortController;#a;#m;#d;#y;constructor(e){this.#a=e,this.sourceId=e.sourceId,this.#m=e.coalesceMs??2000,this.#d=e.now??Date.now,this.#y=e.unackedMax??yn}get epoch(){return this.#e}get ordinal(){return this.#o}get watching(){return this.#u}get unacknowledged(){return this.#r.length}get stopped(){return this.#h.signal.aborted}#w(){return this.#o++,{epoch:this.#e,ordinal:String(this.#o)}}next(){return this.#w()}watch(e){if(this.#u=e,!e){if(this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0;return}this.#_()}enqueue(e){if(this.#r.push(...e),this.#r.length>this.#y){this.#a.log.error(`hightea-source: ${this.sourceId} has more than ${this.#y} unacknowledged observations; starting a new epoch`),this.#r.length=0,this.#e="e_"+Mf(),this.#o=0n,this.#a.onOverflow();return}this.#_()}#_(){if(!this.#u||this.#s||this.#r.length===0||this.#n!==void 0||this.#h.signal.aborted)return;let e=this.#f-this.#d();if(e>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#_()},e);return}let t=this.#l+this.#m-this.#d();if(t>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#_()},t);return}let r=cn-j_,n=te({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:{epoch:this.#e,ordinal:"0"},observations:[]}),{dropped:o,batch:s}=F_(this.#r,n,r);if(o.length>0){this.#r.splice(0,o.length);for(let c of o)this.#a.onOmit?.(c.change.op==="upsert"?c.change.row.address:c.change.address,`${te(c)} bytes cannot fit a ${r}-byte push frame even alone; a later change to that row is what reports it`)}if(s.length===0)return;let i=s[s.length-1],a=this.#e;this.#s=!0,this.#l=this.#d(),this.#a.push({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:i.position,observations:s}).then((c)=>{if(this.#c>0)this.#a.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#c} refusal(s)`),this.#c=0,this.#f=-1/0;let d=ql.safeParse(c);if(!d.success){this.#a.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);return}let u=d.data.applied;if(u===null||u.epoch!==a||u.epoch!==this.#e)return;let l=BigInt(u.ordinal),p=0;while(p<this.#r.length&&BigInt(this.#r[p].position.ordinal)<=l)p++;this.#r.splice(0,p)},(c)=>{this.#c++;let d=Math.min(this.#m*2**Math.min(this.#c-1,5),60000);if(this.#f=this.#d()+d,this.#c===1){let u=c instanceof Error?c.message:String(c);this.#a.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${u}; retrying with backoff, next in ${Math.round(d/1000)} s`)}}).finally(()=>{this.#s=!1,this.#_()})}stop(){if(this.#h.abort(),this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}}import{spawn as H_}from"node:child_process";import{createInterface as B_}from"node:readline";var Df=65536,q_=2000,Lf=16777216,G_=8,K_=5000;class pe extends Error{code;constructor(e,t){super(t);this.code=e}}function _n(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function xt(e){let t=e.stderr.trim().split(`
67
- `).filter((n)=>n!=="").pop(),r=e.code===null?"on a signal":`exit ${e.code}`;return t===void 0?r:`${r}: ${t.slice(0,400)}`}var Uf=(e,t)=>{let[r,...n]=e;if(r===void 0)throw new pe("page-serve-no-command","the page reader has no command to run");let o=H_(r,n,{stdio:["pipe","pipe","pipe"],detached:!0}),s="",i,a,c=[],d=0,u=()=>{return},l=new Promise((v)=>{u=v}),p=(v)=>{let x=a;if(x===void 0)return;if(a=void 0,x.timer!==void 0)clearTimeout(x.timer);x.reject(v)};function f(){if(a!==void 0||c.length===0||i!==void 0)return;let v=c.shift();if(v.timer!==void 0)clearTimeout(v.timer);m(v.request,v.timeoutMs,v.resolve,v.reject)}function m(v,x,I,C){let E={seq:++d,traverse:"traverse"in v&&v.traverse===!0,pages:[],bytes:0,askedAt:Date.now(),deadline:Date.now()+x,resolve:I,reject:C,timer:void 0};a=E,E.timer=setTimeout(()=>{y("page-serve-timeout",`the reader did not answer seq ${E.seq} in ${x} ms`)},x);try{o.stdin.write(JSON.stringify({seq:E.seq,request:v})+`
68
- `)}catch(A){y("page-serve-write-failed",`the request could not be written: ${A instanceof Error?A.message:String(A)}`)}}let y=(v,x)=>{p(new pe(v,x)),_n(o,"SIGKILL")},g=(v)=>{if(v.trim()==="")return;let x;try{x=JSON.parse(v)}catch{y("page-serve-frame-unparsable",`the reader answered a line that is not JSON: ${v.slice(0,120)}`);return}let I=x,C=typeof I.rss==="number"&&Number.isFinite(I.rss)?I.rss:void 0,E=a;if(E===void 0){y("page-serve-frame-unasked",`the reader answered seq ${String(I.seq)} with no request outstanding`);return}if(I.seq!==E.seq){y("page-serve-frame-out-of-order",`the reader answered seq ${String(I.seq)} while seq ${E.seq} was asked`);return}let A=I.refusal;if(A!==void 0&&A!==null){if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({...C===void 0?{}:{rss:C},refusal:{code:typeof A.code==="string"?A.code:"page-serve-refused",message:typeof A.message==="string"?A.message:"the reader refused without a message",...typeof A.hint==="string"?{hint:A.hint}:{}}}),f();return}if(I.page===void 0&&I.progress!==void 0){if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({...C===void 0?{}:{rss:C},progress:I.progress}),f();return}if(I.page===null||typeof I.page!=="object"||Array.isArray(I.page)){y("page-serve-frame-malformed",`the reader answered seq ${E.seq} outside the page shape`);return}if(E.bytes+=v.length,E.bytes>Lf){y("page-serve-answer-too-large",`the reader's answer to seq ${E.seq} exceeded its byte budget (${Lf} bytes)`);return}let q=I.page.complete;if(E.pages.push(I.page),E.traverse&&q!==!0)return;if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({pages:E.pages,...C===void 0?{}:{rss:C}}),f()};B_({input:o.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",g),o.stderr.setEncoding("utf8").on("data",(v)=>{if(s.length<Df)s+=v}),o.stdin.on("error",()=>{if(s.length<Df)s+=`
63
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Md(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Md(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Dd=new Set(["type","properties","required","additionalProperties"]),Nd=["oneOf","anyOf"];function zd(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function Uo(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Dd.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let d of t){let u=d.properties?.[i]??zd(d);if(u===null||u===void 0)continue;if(!a.some((l)=>JSON.stringify(l)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:Uo(a)??{allOf:a};fe(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=zd(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function og(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Dd)if(o in e)return;let r=t.filter((o)=>Nd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=Uo(t);else{let o=r[0],s=Nd.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>Uo([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Kt(e,n)}function Fo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,u={...d},l=c.ref;if(c.ref=null,l){n(l);let f=e.seen.get(l),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(m);else Kt(d,m);if(Kt(d,u),a._zod.parent===l)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete d[g]}if(m.$ref&&f.def)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(d[g])===JSON.stringify(f.def[g]))delete d[g]}}let p=a._zod.parent;if(p&&p!==l){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(d.$ref=f.schema.$ref,f.def)for(let m in d){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(d[m])===JSON.stringify(f.def[m]))delete d[m]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Md(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let l=a.get(u);if(l)l.push(d);else a.set(u,[d])}for(let c of e.intersections)for(let d of a.get(c)??[])og(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Kt(o,r.defId?r.schema:r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;fe(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Vt(t,"input",e.processors),output:Vt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function ee(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ee(n.element,r);if(n.type==="set")return ee(n.valueType,r);if(n.type==="lazy")return ee(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return ee(n.innerType,r);if(n.type==="intersection")return ee(n.left,r)||ee(n.right,r);if(n.type==="record"||n.type==="map")return ee(n.keyType,r)||ee(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ee(n.in,r)||ee(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(ee(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ee(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ee(o,r))return!0;if(n.rest&&ee(n.rest,r))return!0;return!1}return!1}var Ld=(e,t={})=>(r)=>{let n=Zo({...r,processors:t});return j(e,n),jo(n,e),Fo(n,e)},Vt=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=Zo({...o??{},target:s,io:t,processors:r});return j(e,i),jo(i,e),Fo(i,e)};var yt=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},_t=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},Ud=(e,t)=>{yt(e,"minimum",t),_t(e,"maximum",t)},Hd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Bd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},qd=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Gd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Zd=(e,t)=>yt(e,"minimum",t.minimum),jd=(e,t)=>_t(e,"maximum",t.maximum),Fd=(e)=>(t,r)=>{Gd(t,r.format);let[n,o]=e[r.format];yt(t,"minimum",n),_t(t,"maximum",o)},sg={greater_than:(e,t)=>yt(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>_t(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Hd(e,t.value),number_format:Fd(Tr),bigint_format:Fd(oo),min_length:Zd,max_length:jd,length_equals:(e,t)=>Ud(e,t.length),min_size:Zd,max_size:jd,size_equals:(e,t)=>Ud(e,t.size),string_format:(e,t)=>{if(Gd(e,t.format),t.pattern)Bd(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>qd(e,t.mime)};function ue(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)sg[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)yt(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)yt(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)_t(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)_t(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Hd(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)qd(t,o.mime);for(let s of o.patterns??[])Bd(t,s);return t}var ig={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ag=new Map([[vo,ac],[Gr,cc]]),Kd=(e)=>ag.get(e)??e,Vd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=ue(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=ig[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c].map(Kd);if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Wd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=ue(e);o.type=u?"integer":"number";let l=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(l)if(f)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let m=new Set;for(let w of a)if(Number.isFinite(w)&&w!==0)m.add(Math.abs(w));else $e(e,t,o,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[y,...g]=m;if(y!==void 0)o.multipleOf=y;if(g.length)o.allOf=[...o.allOf??[],...g.map((w)=>({multipleOf:w}))]}},Jd=(e,t,r,n)=>{r.type="boolean"};var Yd=(e,t,r,n)=>{r.not={}};var Xd=(e,t,r,n)=>{};var Qd=(e,t,r,n)=>{let o=e._zod.def,s=zt(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},el=(e,t,r,n)=>{let o=e._zod.def;if(o.values.length===0){r.not={};return}let s=[];for(let i of o.values)if(i===void 0){if($e(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if($e(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}};var tl=(e,t,r,n)=>{$e(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var rl=(e,t,r,n)=>{$e(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var nl=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=ue(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=j(s.element,t,{...n,path:[...n.path,"items"]})};function Wt(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Wt(t.out);if(t.type==="catch")return Wt(t.innerType);return e._zod.optin}var ol=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&$e(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in i)fe(o.properties,d,j(i[d],t,{...n,path:[...n.path,"properties",d]}));let c=[];for(let d of Object.keys(i)){let u=s.shape[d];if(t.io==="input"?Wt(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=j(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},sl=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>j(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},il=(e,t,r,n)=>{let o=e._zod.def,s=j(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=j(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},al=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((y,g)=>j(y,t,{...n,path:[...n.path,i,g]})),d=s.rest?j(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let y=s.items[u-1];if(!(t.io==="input"?Wt(y)!==void 0:y._zod.optout==="optional"))break;u--}let l=s.items.length,p=!s.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,p)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(p)o.maxItems=l}else{if(o.items=c,p)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}let{minimum:f,maximum:m}=ue(e);if(typeof f==="number")o.minItems=f;if(typeof m==="number")o.maxItems=m};function Ho(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let y=Ho(e,m,r);return y===m?t:y}for(let m of["anyOf","oneOf"]){let y=t[m];if(!Array.isArray(y))continue;let g=y.map((w)=>Ho(e,w,r));if(g.some((w,b)=>w!==y[b]))t={...t,[m]:g}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((m)=>m==="number"||m==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((m)=>typeof m==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:l,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((m)=>typeof m==="number"?String(m):m);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(n.includes("number")?Zt:po).source;return f}var Bo=new WeakMap;function cg(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of Bo.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Ho(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var cl=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=ue(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=j(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)fe(o.patternProperties,Kd(l).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=j(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=Bo.get(t);if(!u)u=[],Bo.set(t,u),t.deferred.push(()=>cg(t));u.push(e)}o.additionalProperties=j(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,d=t.io==="input"&&Wt(s.valueType)!==void 0;if(c&&!s.partial&&!d){let u=[...c].filter((l)=>typeof l==="string"||typeof l==="number");if(u.length>0)o.required=u.map(String)}},ul=(e,t,r,n)=>{let o=e._zod.def,s=j(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},dl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},qo=Symbol();function ll(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return $e(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),qo}var fl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r.default=i},hl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r._prefault=i},pl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{$e(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},ml=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;j(i,t,n);let a=t.seen.get(e);a.ref=i},gl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Go=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var yl=new WeakSet([Object.prototype,Error.prototype]);function rn(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var gg=(e,t)=>{Na.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(yl.has(r))return;yl.add(r),rn(r,"format",(n)=>(o)=>Ma(n,o)),rn(r,"flatten",(n)=>(o)=>za(n,o)),rn(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Mt,2)}),rn(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Mt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var de=_("ZodError",gg,void 0,{Parent:Error});var _l=Dr(de),wl=Lr(de),Sl=Ur(de),vl=Zr(de),xl=La(de),bl=Ua(de),El=Za(de),Il=ja(de),kl=Fa(de),Cl=Ha(de),Rl=Ba(de),Ol=qa(de);function _g(){if(!Q.localeError)ce(Co())}function Jt(){if(!Q.memoizer)ce({memoizer:Vu()})}var U=_("ZodType",(e,t)=>(_g(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ae(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(my(e,t))},superRefine(e,t){return this.check(gy(e,t))},overwrite(e){return this.check(He(e))},optional(){return $l(this)},exactOptional(){return ry(this)},nullable(){return Pl(this)},nullish(){return $l(Pl(this))},nonoptional(e){return cy(this,e)},array(){return K(this)},or(e){return on([this,e])},and(e){return Yg(this,e)},transform(e){return Nl(this,ty(e))},default(e){return sy(this,e)},prefault(e){return ay(this,e)},catch(e){return dy(this,e)},pipe(e){return Nl(this,e)},readonly(){return hy(this)},describe(e){let t=this.clone();return et.add(t,{description:e}),t},meta(...e){if(e.length===0)return et.get(this);let t=this.clone();return et.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return zr(this,"~standard",{...So(this),jsonSchema:{input:Vt(this,"input"),output:Vt(this,"output")}})},set "~standard"(e){Ae(this,"~standard",e)},parse:function e(t,r){return _l(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wl(this,t,r,{callee:e})},safeParse(e,t){return Sl(this,e,t)},async safeParseAsync(e,t){return vl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ae(this,"spa",e)},validate(e,t){return uo(this,e,t)},validateAsync(e,t){return lo(this,e,t)},encode:function e(t,r){return xl(this,t,r,{callee:e})},decode:function e(t,r){return bl(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await El(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Il(this,t,r,{callee:e})},safeEncode(e,t){return kl(this,e,t)},safeDecode(e,t){return Cl(this,e,t)},async safeEncodeAsync(e,t){return Rl(this,e,t)},async safeDecodeAsync(e,t){return Ol(this,e,t)},toJSONSchema(e){return Ld(this,{})(e)},get description(){return et.get(this)?.description},get _def(){return this._zod.def}}),zl=_("_ZodString",(e,t)=>{qr.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vd(e,r,n,o)},Ra({format:(e)=>ue(e).format??null,minLength:(e)=>ue(e).minimum??null,maxLength:(e)=>ue(e).maximum??null},{regex(...e){return this.check(Ro(...e))},includes(...e){return this.check(Ao(...e))},startsWith(...e){return this.check($o(...e))},endsWith(...e){return this.check(Po(...e))},min(...e){return this.check(gt(...e))},max(...e){return this.check(en(...e))},length(...e){return this.check(tn(...e))},nonempty(...e){return this.check(gt(1,...e))},lowercase(e){return this.check(Oo(e))},uppercase(e){return this.check(To(e))},trim(){return this.check(zo())},normalize(...e){return this.check(No(...e))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Do())},slugify(){return this.check(Lo())}})),wg=_("ZodString",(e,t)=>{qr.init(e,t),zl.init(e,t)},{email(e){return this.check(Qu(Eg,e))},url(e){return this.check(sd(kg,e))},jwt(e){return this.check(Sd(jg,e))},emoji(e){return this.check(id(Cg,e))},guid(e){return this.check(ed(Ig,e))},uuid(e){return this.check(td(nn,e))},uuidv4(e){return this.check(rd(nn,e))},uuidv6(e){return this.check(nd(nn,e))},uuidv7(e){return this.check(od(nn,e))},nanoid(e){return this.check(ad(Rg,e))},cuid(e){return this.check(cd(Og,e))},cuid2(e){return this.check(ud(Tg,e))},ulid(e){return this.check(dd(Ag,e))},base64(e){return this.check(yd(Lg,e))},base64url(e){return this.check(_d(Ug,e))},xid(e){return this.check(ld($g,e))},ksuid(e){return this.check(fd(Pg,e))},ipv4(e){return this.check(hd(Ng,e))},ipv6(e){return this.check(pd(zg,e))},cidrv4(e){return this.check(md(Mg,e))},cidrv6(e){return this.check(gd(Dg,e))},e164(e){return this.check(wd(Zg,e))},datetime(e){return this.check(vd(Sg,e))},date(e){return this.check(xd(vg,e))},time(e){return this.check(bd(xg,e))},duration(e){return this.check(Ed(bg,e))}});function S(e){return Xu(wg,e)}var F=_("ZodStringFormat",(e,t)=>{D.init(e,t),zl.init(e,t)}),Sg=_("ZodISODateTime",(e,t)=>{iu.init(e,t),F.init(e,t)}),vg=_("ZodISODate",(e,t)=>{au.init(e,t),F.init(e,t)}),xg=_("ZodISOTime",(e,t)=>{cu.init(e,t),F.init(e,t)}),bg=_("ZodISODuration",(e,t)=>{uu.init(e,t),F.init(e,t)}),Eg=_("ZodEmail",(e,t)=>{Wc.init(e,t),F.init(e,t)});var Ig=_("ZodGUID",(e,t)=>{Kc.init(e,t),F.init(e,t)});var nn=_("ZodUUID",(e,t)=>{Vc.init(e,t),F.init(e,t)});var kg=_("ZodURL",(e,t)=>{Xc.init(e,t),F.init(e,t)});var Cg=_("ZodEmoji",(e,t)=>{Qc.init(e,t),F.init(e,t)});var Rg=_("ZodNanoID",(e,t)=>{eu.init(e,t),F.init(e,t)});var Og=_("ZodCUID",(e,t)=>{tu.init(e,t),F.init(e,t)});var Tg=_("ZodCUID2",(e,t)=>{ru.init(e,t),F.init(e,t)});var Ag=_("ZodULID",(e,t)=>{nu.init(e,t),F.init(e,t)});var $g=_("ZodXID",(e,t)=>{ou.init(e,t),F.init(e,t)});var Pg=_("ZodKSUID",(e,t)=>{su.init(e,t),F.init(e,t)});var Ng=_("ZodIPv4",(e,t)=>{du.init(e,t),F.init(e,t)});var zg=_("ZodIPv6",(e,t)=>{fu.init(e,t),F.init(e,t)});var Mg=_("ZodCIDRv4",(e,t)=>{hu.init(e,t),F.init(e,t)});var Dg=_("ZodCIDRv6",(e,t)=>{pu.init(e,t),F.init(e,t)});var Lg=_("ZodBase64",(e,t)=>{gu.init(e,t),F.init(e,t)});var Ug=_("ZodBase64URL",(e,t)=>{yu.init(e,t),F.init(e,t)});var Zg=_("ZodE164",(e,t)=>{_u.init(e,t),F.init(e,t)});var jg=_("ZodJWT",(e,t)=>{wu.init(e,t),F.init(e,t)});var Ml=_("ZodNumber",(e,t)=>{xo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o),e.isFinite=!0},Ra({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=ue(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=ue(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=ue(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>ue(e).format??null},{gt(e,t){return this.check(Xr(e,t))},gte(e,t){return this.check(Gt(e,t))},min(e,t){return this.check(Gt(e,t))},lt(e,t){return this.check(Yr(e,t))},lte(e,t){return this.check(qt(e,t))},max(e,t){return this.check(qt(e,t))},int(e){return this.check(Tl(e))},safe(e){return this.check(Tl(e))},positive(e){return this.check(Xr(0,e))},nonnegative(e){return this.check(Gt(0,e))},negative(e){return this.check(Yr(0,e))},nonpositive(e){return this.check(qt(0,e))},multipleOf(e,t){return this.check(Qr(e,t))},step(e,t){return this.check(Qr(e,t))},finite(){return this}}));function Pe(e){return Id(Ml,e)}var Fg=_("ZodNumberFormat",(e,t)=>{Su.init(e,t),Ml.init(e,t)});function Tl(e){return kd(Fg,e)}var Hg=_("ZodBoolean",(e,t)=>{vu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jd(e,r,n,o)});function Yt(e){return Cd(Hg,e)}var Bg=_("ZodUnknown",(e,t)=>{xu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o)});function Ee(){return Rd(Bg)}var qg=_("ZodNever",(e,t)=>{bu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o)});function Gg(e){return Od(qg,e)}var Kg=_("ZodArray",(e,t)=>{Jt(),Eu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nl(e,r,n,o),e.element=t.element},{min(e,t){return this.check(gt(e,t))},nonempty(e){return this.check(gt(1,e))},max(e,t){return this.check(en(e,t))},length(e,t){return this.check(tn(e,t))},unwrap(){return this.element}});function K(e,t){return Td(Kg,e,t)}var Vg=_("ZodObject",(e,t)=>{Jt(),Cu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ol(e,r,n,o),Em(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return ne(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ae(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},loose(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},strict(){return this.clone(ae(this._zod.def,{catchall:Gg()}))},strip(){return this.clone(ae(this._zod.def,{catchall:void 0}))},extend(e){return gm(this,e)},safeExtend(e){return ym(this,e)},merge(e){return _m(this,e)},pick(e){return pm(this,e)},omit(e){return mm(this,e)},partial(...e){return Ea(Wo,this,e[0])},exactPartial(...e){return Ea(Zl,this,e[0],"exactPartial")},required(...e){return wm(jl,this,e[0])}});function k(e,t){let r={type:"object",shape:e??{},...C(t)};return new Vg(r)}var Dl=_("ZodUnion",(e,t)=>{bo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sl(e,r,n,o),e.options=t.options});function on(e,t){return new Dl({type:"union",options:e,...C(t)})}var Wg=_("ZodDiscriminatedUnion",(e,t)=>{Dl.init(e,t),Ru.init(e,t)});function Ll(e,t,r){return new Wg({type:"union",options:t,discriminator:e,...C(r)})}var Jg=_("ZodIntersection",(e,t)=>{Ou.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>il(e,r,n,o)});function Yg(e,t){return new Jg({type:"intersection",left:e,right:t})}var Xg=_("ZodTuple",(e,t)=>{Jt(),Tu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>al(e,r,n,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Wo({type:"optional",innerType:t}))})}});function Be(e,t,r){let n=t instanceof z,o=n?r:t;return new Xg({type:"tuple",items:e,rest:n?t:null,...C(o)})}var Al=_("ZodRecord",(e,t)=>{Jt(),Au.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cl(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ul(e,t,r){if(!t||!t._zod)return new Al({type:"record",keyType:S(),valueType:e,...C(t)});return new Al({type:"record",keyType:e,valueType:t,...C(r)})}var Vo=_("ZodEnum",(e,t)=>{$u.init(e,t),U.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Qd(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})}});function ne(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Vo({type:"enum",entries:r,...C(t)})}var Qg=_("ZodLiteral",(e,t)=>{Pu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>el(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function H(e,t){return new Qg({type:"literal",values:Array.isArray(e)?e:[e],...C(t)})}var ey=_("ZodTransform",(e,t)=>{Jt(),Nu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rl(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Qe(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(Qe(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function ty(e){return new ey({type:"transform",transform:e})}var Wo=_("ZodOptional",(e,t)=>{Eo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $l(e){return new Wo({type:"optional",innerType:e})}var Zl=_("ZodExactOptional",(e,t)=>{zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ry(e){return new Zl({type:"optional",innerType:e})}var ny=_("ZodNullable",(e,t)=>{Mu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ul(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new ny({type:"nullable",innerType:e})}var oy=_("ZodDefault",(e,t)=>{Du.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sy(e,t){return new oy({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var iy=_("ZodPrefault",(e,t)=>{Lu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ay(e,t){return new iy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var jl=_("ZodNonOptional",(e,t)=>{Uu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cy(e,t){return new jl({type:"nonoptional",innerType:e,...C(t)})}var uy=_("ZodCatch",(e,t)=>{Zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dy(e,t){return new uy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Oa(t)})}var ly=_("ZodPipe",(e,t)=>{ju.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ml(e,r,n,o),e.in=t.in,e.out=t.out});function Nl(e,t){return new ly({type:"pipe",in:e,out:t})}var fy=_("ZodReadonly",(e,t)=>{Fu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function hy(e){return new fy({type:"readonly",innerType:e})}var py=_("ZodCustom",(e,t)=>{Hu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tl(e,r,n,o)});function my(e,t={}){return Ad(py,e,t)}function gy(e,t){return $d(e,t)}var Yo=["SOURCE_UNBOUND","SOURCE_UNAVAILABLE","SERVICE_IDENTITY_UNAVAILABLE","SERVICE_IDENTITY_NOT_GRANTED","AGENT_NOT_MAPPED","NOT_MAPPED","INVALID_ADDRESS","HOST_OFFLINE","SOURCE_GAP","FRAME_TOO_LARGE","ITEM_TOO_LARGE","STALE_EXPECTATION","SOURCE_READER_RESTARTING"],cn=524288,ot=262144,yy=1000;function te(e){return new TextEncoder().encode(JSON.stringify(e)).length}var W=S().min(1).max(256),nt=S().min(1).max(1024),_y=S().regex(/^(0|[1-9][0-9]{0,17})$/u),un=k({epoch:W,ordinal:_y}).strict(),rt={workspaceId:W,sourceId:W,hostId:W},wt=k({address:nt,version:W,scope:W,columns:k({title:S().max(4096),state:W,owner:W.nullable(),parent:nt.nullable(),project:nt.nullable(),labels:K(W).max(256),url:S().max(2048).nullable(),updatedAt:S().max(64).nullable()}).strict(),extra:Ee()}).strict(),Xo=k({position:un,change:Ll("op",[k({op:H("upsert"),row:wt}).strict(),k({op:H("delete"),address:nt}).strict()])}).strict(),wy=k({address:nt}).strict(),Sy=k({page:S().min(1).max(4096).optional(),limit:Pe().int().min(1).max(yy)}).strict(),vy=k({address:nt,ownerMemberId:W,expectedOwner:W.nullable(),intentId:W,ifRevision:S().min(1).max(256).optional()}).strict(),xy=k({on:Yt()}).strict(),by=k({memberId:W}).strict(),sn=(e,t)=>k({...rt,caller:by,op:H(e),args:t}).strict(),Hl=Ll("op",[sn("read",wy),sn("list",Sy),sn("assign",vy),sn("watch",xy)]),Ey=k({generation:W,snapshot:W,base:un,rows:K(wt),next:S().min(1).max(4096).nullable(),complete:Yt(),progressAsOf:S().min(1).max(64).optional(),progressStale:k({since:S().min(1).max(64),reason:S().min(1).max(4096)}).strict().optional()}).strict().refine((e)=>e.rows.length>0||e.complete&&e.next===null,{message:"a page carries at least one item"}).refine((e)=>e.complete===(e.next===null),{message:"a page is complete exactly when it has no next token"}),Iy=k({intentId:W,result:Ee(),observation:Xo,revision:W.nullable().optional()}).strict(),Jo={read:k({observation:Xo}).strict(),list:Ey,assign:Iy,watch:k({on:Yt()}).strict()},Fl=ne(Yo),ky=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],an=(e)=>on([k({...rt,op:H(e),outcome:ne(["applied","noop"]),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["applied","noop"]),code:H("SOURCE_READER_RESTARTING"),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:H("rejected"),code:Fl,body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["unknown","refused"]),code:on([Fl.exclude(["ITEM_TOO_LARGE"]),ne(ky)])}).strict(),k({...rt,op:H(e),outcome:H("refused"),code:H("ITEM_TOO_LARGE"),item:nt}).strict()]),Bl=on([an("read"),an("list"),an("assign"),an("watch")]),iI=k({...rt,position:un,observations:K(Xo).min(1)}).strict().refine((e)=>{let{observations:t,position:r}=e,n=t[t.length-1];if(n===void 0||n.position.epoch!==r.epoch||n.position.ordinal!==r.ordinal)return!1;return t.every((o,s)=>o.position.epoch===r.epoch&&(s===0||BigInt(o.position.ordinal)===BigInt(t[s-1].position.ordinal)+1n))},{message:"a push is one epoch of consecutive ordinals, numbered by its last"}),ql=k({applied:un.nullable(),seq:Pe().int().min(0),relist:Yt()}).strict();var qe="x-hh-records";var Cy=`${qe}/changed`,Ie="assign",dn="records:assign",Gl=k({address:S().min(1).max(1024),ownerMemberId:S().min(1).max(256),expectedOwner:S().min(1).max(256).nullable().optional(),ifRevision:S().min(1).max(256),intentId:S().min(1).max(256)}).strict(),Kl=S().min(1).max(256),Vl=S().min(1).max(1024),Wl=k({address:Vl,revision:S().min(1).max(256),scope:S().min(1).max(256),columns:Ul(S(),Ee()),extra:Ee().optional()}).strict(),uI=k({source:Kl,epoch:S().min(1).max(256),records:K(Wl)}).strict(),Ry=k({type:H(Cy),source:Kl,revision:S().min(1).max(256),address:Vl,deleted:H(!0).optional(),record:Wl.optional()}).strict(),dI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),action:Ry}),Oy=new RegExp(`^${qe}://[^/?#]+$`,"u"),Jl=(e)=>e===`${qe}://`||Oy.test(e);var Ty=k({id:S().min(1),revision:Pe().int().min(0),state:S(),operations:K(S())}).passthrough();var Qo=Pe().int().min(0),hI=k({id:S().min(1),engine:S().min(1),owner:S().min(1),name:S().min(1),description:S().optional(),tags:K(S()).optional(),model:Ee().optional(),config:Ul(S(),Ee()),ifRevision:Qo}).passthrough(),pI=k({id:S().min(1),ifRevision:Qo}).strict(),mI=k({id:S().min(1),ifRevision:Qo}).strict(),Yl=-32602,gI=k({code:H(Yl),message:S(),data:k({staleRevision:Pe().int().min(1),row:Ty})}),yI=k({code:H(Yl),message:S(),data:k({staleRevision:H(0)})});var es=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],Ge="x-hh-services://",Ay=`${Ge} and ${qe}://<sourceId>`,Xl=["put","remove","start","stop","restart","accept"];var $y="hh-services://backup",Py="hh-services://changes",Ny=/^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;function Ql(e,t){let r=(n)=>typeof t[n]==="string"?JSON.stringify(t[n]):`no ${n}`;switch(e){case"subscribe":{let n=t.channel;if(Object.keys(t).length===1&&typeof n==="string"&&(n===Ge||Jl(n)))return;return`subscribe to ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ${Ay}`}case"x-ahpd/invokeOperation":{if(t.channel===Ge){if(typeof t.operationId==="string"&&Xl.includes(t.operationId))return;return`x-ahpd/invokeOperation ${r("operationId")} on ${Ge} is not one Hightea sends; only ${Xl.join(", ")}`}if(t.channel===`${qe}://`){if(t.operationId===Ie)return;return`x-ahpd/invokeOperation ${r("operationId")} on ${qe}:// is not one Hightea sends; only ${Ie} (${dn})`}return`x-ahpd/invokeOperation on ${r("channel")} is not one Hightea sends; only ${Ge} and ${qe}://`}case"resourceRead":if(typeof t.uri==="string"&&Ny.test(t.uri))return;return`resourceRead of ${r("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${$y} and ${Py}`;case"listSessions":if(t.channel==="ahp-root://"&&Object.keys(t).length===1)return;return`listSessions on ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ahp-root://`;case"authenticate":{let n=Object.keys(t).sort().join(",");if(n!=="resource,target,token"&&n!=="expiresIn,resource,target,token")return`authenticate naming ${JSON.stringify(n)} is not one Hightea sends; only target, resource, token and expiresIn`;if(typeof t.token!=="string")return"authenticate names no token";if(typeof t.resource!=="string"||t.resource==="")return`authenticate names ${r("resource")}`;let o=t.expiresIn;if(o!==void 0&&!(typeof o==="number"&&Number.isInteger(o)&&o>0))return"authenticate's expiresIn is not a positive integer of seconds";let s=t.target;if(typeof s!=="object"||s===null||Array.isArray(s))return"authenticate names no target";let i=s;if(Object.keys(i).sort().join(",")!=="customizationId,kind,session")return"authenticate's target carries more than kind, session and customizationId";if(i.kind!=="mcpServer")return`authenticate's target kind is ${JSON.stringify(i.kind)}; only mcpServer`;if(typeof i.session!=="string"||i.session==="")return"authenticate's target names no session";if(typeof i.customizationId!=="string"||i.customizationId==="")return"authenticate's target names no server";return}default:return`${JSON.stringify(e)} is not a host-scoped method; only ${es.join(", ")}`}}var ef=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...es];function Xt(e){return es.includes(e)}var zy=1e4,Qt=zy-1000,tf="host-request:",rf="1.1.0";var nf="signed-envelopes",of="meta-routing-ids@1",ln="host-frames-slim@1";var sf=k({workspaceId:S().min(1).optional(),hostId:S().min(1).optional(),agentMemberId:S().min(1).optional(),caller:S().min(1).max(256).optional()}).strict(),My=["unmapped","timedOut","outside"],vI=k({reason:ne(My)}).strict();function af(e){if(e.ok)return{result:e.result};if(e.reason==="refused")return{error:{code:e.code,message:e.message,...e.data===void 0?{}:{data:e.data}}};return{error:{code:-32000,message:e.reason,data:{reason:e.reason}}}}var Dy=k({resource:S().min(1),customizationId:S().min(1)}).strict(),er=k({available:Yt(),reason:S().min(1).max(200).optional(),server:Dy.optional()}).strict(),st="ahpd/hostTools",xI=k({resource:S().min(1),_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er.optional()}).strict()}).strict(),bI=k({channel:H("ahp-root://"),session:S().min(1),changes:k({_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er}).strict()}).strict()}).strict();function tr(e,t,r){let n=ye(e)?e:{},o=n["hh/agentMemberId"];if(o!==void 0&&o!==t)return;let s=er.safeParse(n[st]);if(!s.success)return{"hh/agentMemberId":t};let i=s.data.available&&r!==void 0;return{"hh/agentMemberId":t,"hh/hostTools":{available:s.data.available,...s.data.reason===void 0?{}:{reason:s.data.reason},...i?{server:r}:{}}}}function cf(e,t,r){if(!ye(e)||typeof e.resource!=="string"||e.resource==="")return;let n=tr(e._meta,t,r);return n===void 0?void 0:{resource:e.resource,_meta:n}}var EI=k({channel:S().min(1),resource:S().min(1),reason:H("expired")}).strict();function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ts="event:all",uf="tool:all";var Ly=["session/ready","chat/turnStarted","chat/turnComplete","x-hh/turnFailed"];var rr=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID","INVALID_OPERATION_SHAPE","WORKSPACE_OR_MEMBER_UNKNOWN","UNKNOWN_HOUSE_OR_MEMBER","AGENT_NOT_MAPPED","UNMAPPED_LOCAL_AGENT","FOREIGN_SESSION","FOREIGN_SESSION_REFUSED","TOKEN_EXPIRED_OR_REVOKED","HOST_REVOKED","HOST_RESTARTED","INPUT_REQUIRED","APPROVAL_REQUIRED","VERSION_UNSUPPORTED","WAKE_NOT_SENT","TURN_TIMED_OUT","WAKE_ATTEMPTS_EXHAUSTED","HOST_START_FAILED","WAKE_TEXT_NOT_ALLOWED","ROOM_ASKS_UNTRUSTED","ASK_UNSIGNED","KEY_NOT_FOR_AUTHOR","ASK_STALE","ASK_REPLAYED","SERVICE_NOT_ALLOWED","TURN_CANCELLED",...Yo],df=16,lf=49152,ff=262144,Uy=k({id:S().min(1),from:k({memberId:S().min(1)}).strict(),text:S(),replyTo:S().min(1).optional(),deleted:H(!0).optional(),signed:k({keyId:S().min(1),createdAt:S().min(1),signature:S().min(1),clientId:S().min(1),attachmentIds:K(S().min(1))}).strict().optional()}).strict(),Zy=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,jy=K(Uy).min(1).superRefine((e,t)=>{if(e.length>df){t.addIssue({code:"custom",message:`a wake carries at most ${df} triggering envelopes, not ${e.length}`});return}if(new Set(e.map((n)=>n.id)).size!==e.length){t.addIssue({code:"custom",message:"a wake names each triggering message once"});return}let r=0;for(let n of e){let o=Zy(n);if(o>lf){t.addIssue({code:"custom",message:`triggering envelope ${n.id} is ${o} bytes, over the ${lf}-byte limit`});return}r+=o}if(r>ff)t.addIssue({code:"custom",message:`the triggering envelopes take ${r} bytes, over the ${ff}-byte limit`})}),hf=k({workspaceId:S().min(1),deliveryId:S().min(1),turnId:S().min(1).optional(),agentMemberId:S().min(1),threadRef:S().min(1),afterMessageId:S().min(1).optional(),triggeringMessageIds:K(S().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:jy.optional()}).strict(),fn=k({event:ne(Ly),channel:S().min(1),workspaceId:S().min(1),deliveryId:S().min(1),session:S().min(1),chat:S().min(1),turnId:S().min(1).optional(),clientSeq:Pe().int().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict();function pf(e){return fn.parse(e)}var Fy=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],OI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),origin:k({clientId:S().min(1),clientSeq:Pe().int().min(1)}).optional(),action:k({type:ne(Fy),turnId:S().min(1).optional(),part:k({error:k({errorType:S().min(1)})}).optional()})});var mf="Hightea-Host",gf="x-hightea-host";import{createHash as zf}from"node:crypto";var Hy=(e,t,r)=>JSON.stringify([e,t,r]),or=/^ahp-session:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,By=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,M=(e)=>({ok:!1,code:e});function nr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function it(e,t,r=[]){let n=new Set([...t,...r]);return t.every((o)=>(o in e))&&Object.keys(e).every((o)=>n.has(o))}function qy(e){let t=hf.safeParse(e._meta);return t.success?t.data:void 0}function yf(e,t){if(!nr(e)||typeof e.method!=="string")return M("OPERATION_SHAPE_INVALID");if(!it(e,["method"],["jsonrpc","id","params"]))return M("OPERATION_SHAPE_INVALID");let r=e.method;if(r!=="createSession"&&r!=="subscribe"&&r!=="dispatchAction")return M("OPERATION_NOT_ALLOWLISTED");let n=e.params;if(!nr(n))return M("OPERATION_SHAPE_INVALID");let o=qy(n);if(o===void 0)return M("OPERATION_SHAPE_INVALID");if(o.workspaceId!==t.workspaceId)return M("WORKSPACE_OR_MEMBER_UNKNOWN");let s=t.agents.get(o.agentMemberId);if(s===void 0)return M("AGENT_NOT_MAPPED");let i=Hy(o.workspaceId,o.agentMemberId,o.threadRef),a=t.sessions.get(i),{triggering:c,...d}=o,u=e.id,l={jsonrpc:"2.0",...u===void 0?{}:{id:u}},p=n.channel;if(r==="createSession"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string"||!or.test(p))return M("OPERATION_SHAPE_INVALID");if(a!==void 0)return M("OPERATION_SHAPE_INVALID");if(Gy(t,p))return M("FOREIGN_SESSION");return{ok:!0,operation:"createSession",frame:{...l,method:r,params:{channel:p,provider:s.provider,workingDirectories:[s.workingDirectory]}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(r==="subscribe"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a===void 0||a.sessionUri!==p)return M("FOREIGN_SESSION");return{ok:!0,operation:"subscribe",frame:{...l,method:r,params:{channel:p}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(!it(n,["channel","clientSeq","action","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof n.clientSeq!=="number"||!Number.isInteger(n.clientSeq)||n.clientSeq<1)return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a?.chatUri===void 0||a.chatUri!==p){if(t.parked?.has(i)===!0)return M("AGENT_NOT_MAPPED");return M("FOREIGN_SESSION")}let f=n.action;if(!nr(f)||f.type!=="chat/turnStarted")return M("OPERATION_NOT_ALLOWLISTED");if(!it(f,["type","turnId","message"],["startedAt"]))return M("OPERATION_SHAPE_INVALID");if(typeof f.turnId!=="string"||!By.test(f.turnId))return M("OPERATION_SHAPE_INVALID");if(f.startedAt!==void 0&&typeof f.startedAt!=="number")return M("OPERATION_SHAPE_INVALID");let m=f.message;if(!nr(m)||!it(m,["text","origin"])||typeof m.text!=="string")return M("OPERATION_SHAPE_INVALID");if(!nr(m.origin)||!it(m.origin,["kind"])||m.origin.kind!=="user")return M("OPERATION_SHAPE_INVALID");if(m.text!==`wake ${o.threadRef}`)return M("WAKE_TEXT_NOT_ALLOWED");return{ok:!0,operation:"dispatchAction",frame:{...l,method:r,params:{channel:p,clientSeq:n.clientSeq,action:{type:"chat/turnStarted",turnId:f.turnId,...f.startedAt===void 0?{}:{startedAt:f.startedAt},message:{text:m.text,origin:{kind:"user"}}}}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i,turnId:f.turnId}}function Gy(e,t){for(let r of e.sessions.values())if(r.sessionUri===t)return!0;return!1}import{fileURLToPath as C_}from"node:url";var Ky="host",hn=(e)=>{if(typeof e!=="object"||e===null)return;let{code:t,message:r}=e;if(typeof t!=="number"||typeof r!=="string")return;let n=e.data;return n===void 0?{code:t,message:r}:{code:t,message:r,data:n}},Vy=(e)=>e.ifRevision===0,pn=(e)=>e instanceof Error&&/timed? ?out|timeout/iu.test(e.message),_f="x-ahpd-agents://";async function Wy(e){let t,r=!1;try{let n=await e.peer.request("subscribe",{channel:Ge},Qt);r=!0;let o=typeof n==="object"&&n!==null?n.snapshot:void 0;if(t=typeof o==="object"&&o!==null?o.state:void 0,typeof t!=="object"||t===null)throw Error("hightea-pipe: the services snapshot holds no state")}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};if(e.log.error(`hightea-pipe: ${n instanceof Error?n.message:"the services snapshot is unreadable"}`),pn(n))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's services"}}finally{if(r)try{e.peer.notify("unsubscribe",{channel:Ge})}catch(n){e.log.error(`hightea-pipe: dropping the services subscription failed: ${n instanceof Error?n.name:typeof n}`)}}return{ok:!0,result:t}}function Jy(e){let t=typeof e==="object"&&e!==null?e.snapshot:void 0,r=typeof t==="object"&&t!==null?t.state:void 0,n=typeof r==="object"&&r!==null?r.records:void 0;if(!Array.isArray(n))throw Error("hightea-pipe: the agents snapshot holds no records");return n.map((o)=>{if(typeof o!=="object"||o===null)throw Error("hightea-pipe: an agents snapshot entry is not an object");let s=o;if(typeof s.record==="object"&&s.record!==null&&!Array.isArray(s.record)){if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return{id:s.id,...s.record}}if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return s})}async function Yy(e){let t=new Set([...e.agents.values()].map((s)=>s.provider)),r,n;try{r=await e.peer.request("subscribe",{channel:_f},Qt),n=Jy(r)}catch(s){let i=hn(s);if(i!==void 0)return{ok:!1,reason:"refused",...i};if(e.log.error(`hightea-pipe: ${s instanceof Error?s.message:"the agents snapshot is unreadable"}`),pn(s))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's agent list"}}let o=n.filter((s)=>typeof s.id==="string"&&t.has(s.id));o.sort((s,i)=>String(s.id)<String(i.id)?-1:String(s.id)>String(i.id)?1:0);try{e.peer.notify("unsubscribe",{channel:_f})}catch(s){e.log.error(`hightea-pipe: dropping the agents subscription failed: ${s instanceof Error?s.name:typeof s}`)}return{ok:!0,result:{rows:o}}}async function Xy(e){let t;try{t=await e.peer.request("listSessions",{channel:"ahp-root://"},Qt)}catch(i){let a=hn(i);if(a!==void 0)return{ok:!1,reason:"refused",...a};if(e.log.error(`hightea-pipe: the session list is unreadable: ${i instanceof Error?i.name:typeof i}`),pn(i))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"}}let r=rs(t)&&Array.isArray(t.items)?t.items:void 0;if(r===void 0)return e.log.error("hightea-pipe: ahpd's listSessions result holds no items"),{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"};let n=[],o=[];for(let i of r){let a=rs(i)&&typeof i.resource==="string"&&i.resource!==""?i.resource:void 0;if(a===void 0){o.push("a summary with no resource");continue}let c;try{c=e.memberOf(a)}catch(l){o.push(`${a}: ${l instanceof Error?l.message:String(l)}`);continue}if(c===void 0)continue;let d=cf(i,c,e.hostToolsServer(a));if(d===void 0){o.push(`${a}: its summary names another member`);continue}let u=d._meta["hh/hostTools"];if(u!==void 0)e.rememberHostTools?.(a,u);n.push(d)}let s=new Set(n.map((i)=>i.resource));for(let i of e.ownSessions?.()??[]){if(s.has(i))continue;let a=e.memberOf(i);if(a===void 0)continue;let c=e.toolsAnswerOf?.(i);if(c===void 0){o.push(`${i}: provisional, and this pipe holds no tools answer for it yet`);continue}let d=tr({[st]:c},a,e.hostToolsServer(i));if(d===void 0)continue;n.push({resource:i,_meta:d})}if(o.length>0)e.log.error(`hightea-pipe: skipped ${o.length} unreadable session row(s): ${o.join("; ").slice(0,500)}`);return{ok:!0,result:{items:n}}}async function wf(e,t){let r=e_(e.meta);if(r===void 0)return{ok:!1,reason:"outside"};let n=e.method;if(!t_(n)&&!Xt(n))return{ok:!1,reason:"outside"};let o=e.params;if(!rs(o))return{ok:!1,reason:"outside"};let s="agentMemberId"in o;if(s&&(typeof o.agentMemberId!=="string"||o.agentMemberId===""))return{ok:!1,reason:"outside"};let i=s?o.agentMemberId:r.agentMemberId;if(Xt(n)){if(i!==void 0)return{ok:!1,reason:"outside"};let u=Ql(n,o);if(u!==void 0)return t.log.error(`hightea-pipe: refused a host request: ${u}`),{ok:!1,reason:"outside"};if(n==="subscribe")return Wy(t);if(n==="listSessions")return Xy(t);if(n==="authenticate")return r_(t,o);return ns(t,n,o)}if(n==="x-ahpd/agents/list"){if(i!==void 0)return{ok:!1,reason:"outside"};if(Object.keys(o).length!==0)return{ok:!1,reason:"outside"};return Yy(t)}if(i===void 0)return{ok:!1,reason:"outside"};let a=t.agents.get(i);if(a===void 0||a.provider!==o.id)return{ok:!1,reason:"unmapped"};let c=s?Qy(o):o,d=n==="x-ahpd/agents/put"&&Vy(c)?{...c,owner:Ky}:c;return ns(t,n,d)}function Qy(e){let{agentMemberId:t,...r}=e;return r}function e_(e){let t=sf.safeParse(e);return t.success?t.data:void 0}function rs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function t_(e){return e==="x-ahpd/agents/list"||e==="x-ahpd/agents/put"||e==="x-ahpd/agents/remove"||e==="x-ahpd/agents/enable"||e==="x-ahpd/agents/pause"||e==="x-ahpd/agents/disable"}async function r_(e,t){let r=t.target;if(typeof r.session!=="string"||e.memberOf(r.session)===void 0)return e.log.error("hightea-pipe: refused an authenticate aimed at a session this pipe did not make"),{ok:!1,reason:"outside"};let n=typeof r.session==="string"?e.hostToolsServer(r.session):void 0;if(n===void 0)return e.log.error("hightea-pipe: refused an authenticate: this host serves no Hightea MCP server, or the session has not yet said which customization is ours"),{ok:!1,reason:"outside"};if(r.customizationId!==n.customizationId)return e.log.error("hightea-pipe: refused an authenticate aimed at a server that is not this host's"),{ok:!1,reason:"outside"};if(t.resource!==n.resource)return e.log.error("hightea-pipe: refused an authenticate for a resource that is not this host's server"),{ok:!1,reason:"outside"};return ns(e,"authenticate",t)}async function ns(e,t,r){try{return{ok:!0,result:await e.peer.request(t,r,Qt)??null}}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};return e.log.error(`hightea-pipe: host request ${t} ended without an answer`+(pn(n)?" (timed out)":"")+`: ${n instanceof Error?n.name:typeof n}`),{ok:!1,reason:"timedOut"}}}import{createPrivateKey as m_,createPublicKey as g_,generateKeyPairSync as y_,sign as __}from"node:crypto";import{appendFile as w_,chmod as S_,readFile as If,rename as kf,writeFile as Cf}from"node:fs/promises";import{join as is}from"node:path";function n_(e){return JSON.stringify({v:1,workspaceId:e.workspaceId,roomId:e.roomId,rootMessageId:e.rootMessageId,authorMemberId:e.authorMemberId,clientId:e.clientId,body:e.body,attachmentIds:[...e.attachmentIds],createdAt:e.createdAt})}function mn(e){return new TextEncoder().encode(n_(e))}import{createPublicKey as o_,verify as s_}from"node:crypto";var i_=Buffer.from("302a300506032b6570032100","hex");function os(e,t){let r=e.signed;if(r===void 0)return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id} carries no signature`};let n=t.keys.find((a)=>a.keyId===r.keyId);if(n===void 0)return{ok:!1,code:"ROOM_ASKS_UNTRUSTED",why:`message ${e.id} is signed by key ${r.keyId}, which this host does not trust yet; its owner approves that browser with \`hightea approve\` and the ask goes through`};let o=mn({workspaceId:t.workspaceId,roomId:t.roomId,rootMessageId:e.replyTo??null,authorMemberId:e.from.memberId,clientId:r.clientId,body:e.text,attachmentIds:r.attachmentIds,createdAt:r.createdAt}),s=Buffer.from(r.signature,"base64url"),i=o_({key:Buffer.concat([i_,Buffer.from(n.publicKey,"base64url")]),format:"der",type:"spki"});if(s.length!==64||!s_(null,o,i,s))return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id}'s signature by ${n.name} does not match what the room returned (text, thread, author ${e.from.memberId}, or attachments)`};if(t.ownKeyId!==void 0&&n.keyId===t.ownKeyId&&!t.ownAgents.has(e.from.memberId))return{ok:!1,code:"KEY_NOT_FOR_AUTHOR",why:`message ${e.id} is signed by this host's key but attributed to ${e.from.memberId}, which this host does not run`};return{ok:!0,keyName:n.name,clientId:r.clientId,createdAt:r.createdAt}}function Sf(e,t){let r=(a)=>a.deleted===!0?{id:a.id,deleted:!0}:a,n=(a)=>a.deleted===!0||os(a,t).ok,o=n(e.root),s=e.replies.filter(n).map(r),i=(o?0:1)+e.replies.length-e.replies.filter(n).length;return{...e,root:o?r(e.root):{id:e.root.id,omitted:!0},replies:s,...i===0?{}:{omitted:`${String(i)} unsigned messages omitted`}}}import{createHash as a_}from"node:crypto";import{existsSync as c_,readFileSync as u_}from"node:fs";import{join as d_}from"node:path";var l_="trusted-keys.json",f_=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,h_=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,p_=(e)=>Buffer.from(e).toString("base64url");function ss(e){if(!h_.test(e))return{error:"TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it"};return{keyId:p_(a_("sha256").update(Buffer.from(e,"base64url")).digest())}}function vf(e){let t=d_(e,l_);if(!c_(t))return{state:"missing",file:t};let r;try{r=JSON.parse(u_(t,"utf8"))}catch(o){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${o.message})`)}let n=r;if(typeof r!=="object"||r===null||n.v!==1||!Array.isArray(n.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let o of n.keys){let s=o,i=typeof s.publicKey==="string"?ss(s.publicKey):void 0;if(typeof s.name!=="string"||!f_.test(s.name)||i===void 0||"error"in i||s.keyId!==i.keyId||typeof s.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(o)}`)}return{state:"read",file:t,keys:n.keys}}class Z extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var v_="host-signing-key",xf="hightea-acted-asks.jsonl",gn=600000,x_=2592000000,b_=20;async function Rf(e,t=()=>Date.now()){let r=is(e,v_),n;try{n=await If(r,"utf8")}catch(a){if(a.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${r} exists but cannot be read (${String(a)}); it is never regenerated, fix or remove it by hand`)}if(n===void 0){let a=y_("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),c=`${r}.${String(process.pid)}.tmp`;await Cf(c,a,{mode:384,flag:"wx"}),await S_(c,384),await kf(c,r),n=a}let o;try{if(o=m_({key:n,format:"pem"}),o.asymmetricKeyType!=="ed25519")throw Error(`a ${String(o.asymmetricKeyType)} key, not Ed25519`)}catch(a){throw Error(`HOST_KEY_UNREADABLE: ${r} is not an Ed25519 PKCS8 key (${String(a)}); it is never regenerated, fix or remove it by hand`)}let s=g_(o).export({format:"jwk"}).x,i=s===void 0?{error:"no public key"}:ss(s);if("error"in i)throw Error(`HOST_KEY_UNREADABLE: ${r}: ${i.error}`);return{privateKey:o,trusted:{name:"this-host",keyId:i.keyId,publicKey:s,addedAt:new Date(t()).toISOString()}}}function Of(e,t,r=()=>Date.now()){let n=new Date(r()).toISOString(),o=mn({...t,attachmentIds:[],createdAt:n});return{keyId:e.trusted.keyId,createdAt:n,signature:__(null,o,e.privateKey).toString("base64url")}}async function bf(e,t){if(e.configDir===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host's ahpd is too old for signed asks (it names no configDir)");let r=await e.hostKey;if(r instanceof Error)throw new Z("ROOM_ASKS_UNTRUSTED",r.message);let n;try{let s=await vf(e.configDir);n=s.state==="read"?s.keys:[]}catch(s){throw new Z("ROOM_ASKS_UNTRUSTED",String(s instanceof Error?s.message:s))}if(n.length===0)throw new Z("ROOM_ASKS_UNTRUSTED","this host trusts no key yet; its owner runs `hightea host trust add`");let o=r?.trusted;return{workspaceId:e.workspaceId,roomId:t,keys:o===void 0||n.some((s)=>s.keyId===o.keyId)?n:[...n,o],...o===void 0?{}:{ownKeyId:o.keyId},ownAgents:e.ownAgents}}function Ef(e){let[t,r,n]=e.split("/");if(!t||!r||n!==void 0)throw new Z("ASK_UNSIGNED",`the wake's thread ref ${e} names no room thread`);return{roomId:t,rootMessageId:r}}function E_(e,t,r){if(t===void 0||t==="")throw new Z("ASK_UNSIGNED",`wake ${r.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);return t}function I_(e,t,r,n){let o=new Map;for(let i of e){let a=i.replyTo??i.id;if(a!==r)throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} carries message ${i.id} from thread ${a}, not ${n.threadRef}`);o.set(i.id,{id:i.id,from:{memberId:i.from.memberId},text:i.text,...i.replyTo===void 0?{}:{replyTo:i.replyTo},...i.deleted===void 0?{}:{deleted:!0},...i.signed===void 0?{}:{signed:i.signed}})}let s=new Set(o.keys());if(s.size!==t.length||t.some((i)=>!s.has(i)))throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} froze ${t.length} triggering messages and carried ${s.size}, not the same ones`);return o}class sr{#e;#o;#r=Promise.resolve();constructor(e){this.#e=e}async admit(e,t){let{roomId:r,rootMessageId:n}=Ef(e.threadRef),o=await bf(this.#e,r),s=e.triggering,i=s===void 0?e.triggeringMessageIds:s.map((l)=>l.id);if(i===void 0||i.length===0)throw new Z("ASK_UNSIGNED",`wake ${e.deliveryId} names no triggering message to check`);let a=s===void 0?await this.#s(E_(this.#e,t,e),r,n,e.afterMessageId,new Set(i)):I_(s,i,n,e),c=(this.#e.now??Date.now)(),d=await this.#n(c),u=[];for(let l of i){let p=a.get(l);if(p===void 0)throw new Z("ASK_UNSIGNED",`triggering message ${l} is not in thread ${e.threadRef}`);let f=os(p,o);if(!f.ok)throw new Z(f.code,f.why);let m=d.filter((g)=>g.clientId===f.clientId);if(m.some((g)=>g.deliveryId!==e.deliveryId))throw new Z("ASK_REPLAYED",`the ask signed as ${f.clientId} (message ${l}) was already acted on under another wake`);if(m.length>0){let g=Math.min(...m.map((w)=>w.at));if(c-g>gn)throw new Z("ASK_REPLAYED",`wake ${e.deliveryId} was first admitted at ${new Date(g).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);continue}let y=Date.parse(f.createdAt);if(!Number.isFinite(y)||Math.abs(c-y)>gn)throw new Z("ASK_STALE",`message ${l} was signed at ${f.createdAt}, more than 10 minutes from this host's clock`);u.push({clientId:f.clientId,deliveryId:e.deliveryId,at:c})}if(u.length>0)await this.#c(d,u)}async view(e,t){return Sf(t,await bf(this.#e,Ef(e).roomId))}async#s(e,t,r,n,o){let s=new Map,i=n??r;for(let a=0;a<b_;a++){let c=await this.#e.readThread(e,{roomId:t,messageId:r,after:i});if(!k_(c))throw new Z("ASK_UNSIGNED",`read_thread answered no root and replies for ${t}/${r}`);for(let u of[c.root,...c.replies])if(o.has(u.id))s.set(u.id,u);let d=c.replies.at(-1);if(s.size===o.size||c.more!==!0||d===void 0)break;i=d.id}return s}async#n(e){this.#o??=(async()=>{let r=is(this.#e.configDir,xf),n="";try{n=await If(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} cannot be read: ${String(i)}`)}let o=[];for(let[i,a]of n.split(`
64
+ `).entries()){if(a.trim()==="")continue;let c=JSON.parse(a);if(typeof c.clientId!=="string"||typeof c.deliveryId!=="string"||typeof c.at!=="number")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} line ${String(i+1)} is not an acted ask; fix or remove the file by hand`);o.push(c)}let s=o.filter((i)=>e-i.at<x_);if(s.length<o.length)await this.#d(r,s);return s})();let t=this.#o;return t.catch(()=>{if(this.#o===t)this.#o=void 0}),t}async#d(e,t){let r=`${e}.${String(process.pid)}.tmp`;await Cf(r,t.map((n)=>`${JSON.stringify(n)}
65
+ `).join(""),{mode:384}),await kf(r,e)}async#c(e,t){e.push(...t);let r=is(this.#e.configDir,xf),n=this.#r.then(()=>w_(r,t.map((o)=>`${JSON.stringify(o)}
66
+ `).join(""),{mode:384}));this.#r=n.catch(()=>{return}),await n}}function k_(e){if(e===null||typeof e!=="object")return!1;let t=e,r=(n)=>n!==null&&typeof n==="object"&&typeof n.id==="string";return r(t.root)&&Array.isArray(t.replies)&&t.replies.every(r)}class vt extends Error{}class us extends Error{}function R_(e,t){if(!ef.includes(e))return!1;return!Xt(e)||typeof t==="string"&&t.startsWith(tf)}function O_(e){let t=e.params.clientSeq;if(typeof t!=="number"||!Number.isInteger(t)||t<1)throw new us("ahp-host: a dispatch names no clientSeq");return t}var T_=[/No agent provider registered for: /u,/: this conversation has no matching configured ACP process authority/u];function Tf(e){if(e instanceof Z)return e.code;if(e instanceof us)return"OPERATION_SHAPE_INVALID";if(e instanceof vt)return"AGENT_NOT_MAPPED";let t=e instanceof Error?e.message:String(e);if(T_.some((r)=>r.test(t)))return"AGENT_NOT_MAPPED";return"WAKE_NOT_SENT"}var St=rf,as=15000,A_="x-hh/actions";function $_(e,t={}){let r=t.startedAtMs??Date.now(),n=Math.max(0,Date.now()-r),o=e.turnId===void 0||e.turnId===""?{}:{turnId:e.turnId};if(e.event==="session/ready")return{channel:e.session,action:{type:"session/ready",...o}};if(e.event==="chat/turnStarted")return{channel:e.chat,action:{type:"chat/turnStarted",...o,startedAt:new Date(r).toISOString()},...e.clientSeq===void 0?{}:{origin:{clientId:t.clientId??"hightea-gateway",clientSeq:e.clientSeq}}};if(e.event==="chat/turnComplete")return{channel:e.chat,action:{type:"chat/turnComplete",...o,duration:n}};let s=e.errorCode??"OPERATION_SHAPE_INVALID";if(s==="TURN_CANCELLED")return{channel:e.chat,action:{type:"chat/turnCancelled",...o,duration:n}};return{channel:e.chat,action:{type:"chat/error",...o,duration:n,part:{kind:"error",error:{errorType:s,message:""}}}}}var ir=(e,t)=>JSON.stringify([e,t]);function P_(e){let t;for(let r of e.triggering??[]){let n=r.signed===void 0?Number.NaN:Date.parse(r.signed.createdAt);if(!Number.isFinite(n))continue;if(t===void 0||n>t)t=n}return t}var ak=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Be([S().min(1),fn]))}).strict(),N_=k({event:ne(["session.created","turn.started","turn.finished","turn.error"]),houseId:S().min(1),deliveryId:S().min(1),sessionId:S().min(1),chatId:S().min(1),turnId:S().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict(),z_={"session.created":"session/ready","turn.started":"chat/turnStarted","turn.finished":"chat/turnComplete","turn.error":"x-hh/turnFailed"};function M_(e){return{event:z_[e.event],channel:e.event==="session.created"?e.sessionId:e.chatId,workspaceId:e.houseId,deliveryId:e.deliveryId,session:e.sessionId,chat:e.chatId,...e.turnId===void 0?{}:{turnId:e.turnId},turnState:e.turnState,statusCode:e.statusCode,...e.errorCode===void 0?{}:{errorCode:e.errorCode},...e.errorDetail===void 0?{}:{errorDetail:e.errorDetail}}}var D_=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Ee())}).strict(),L_=(e)=>e.turnId===void 0?e.deliveryId:ir(e.deliveryId,e.turnId);function cs(e){return`${e.issues.slice(0,3).map((r)=>`${r.path.join(".")||"(record)"} ${r.message}`).join("; ")}${e.issues.length>3?`; and ${e.issues.length-3} more`:""}`}function Af(e){let t=Array.isArray(e)?e[1]:e;if(typeof t==="object"&&t!==null){let r=t.event;if(typeof r==="string")return`event=${r}`}return Array.isArray(e)?`a frame of ${typeof t}`:`${e===null?"null":typeof e}`}function ds(e,t){let r=D_.safeParse(e);if(!r.success)throw Error(`ahp-host: invalid durable state: ${cs(r.error)}`);let n=[],o=0,s=0;if(r.data.lastStatus.forEach((a,c)=>{let d=Be([S().min(1),Ee()]).safeParse(a),u=d.success?d.data[0]:"",l=d.success?fn.safeParse(d.data[1]):void 0,p=d.success&&l?.success===!1?N_.safeParse(d.data[1]):void 0,f=l?.success===!0?l.data:p?.success===!0?M_(p.data):void 0;if(f===void 0){s+=1;let m=d.success&&typeof d.data[1]==="object"&&d.data[1]!==null&&"houseId"in d.data[1],y=p?.success===!1&&m?`pre-0.1.11 shape: ${cs(p.error)}`:l?.success===!1?cs(l.error):"not a [key, frame] entry";t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (${Af(a)}): ${y}`);return}if(L_(f)!==u){s+=1,t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (event=${f.event}): its key names a different delivery or turn`);return}if(l?.success!==!0)o+=1,t.error(`ahp-host: upgraded durable status frame lastStatus[${c}] (${Af(a)} -> event=${f.event}) from the pre-0.1.11 shape`);n.push([u,f])}),o>0||s>0)t.error(`ahp-host: durable state repaired: ${o} status frame(s) upgraded from the pre-0.1.11 shape, ${s} dropped; the pipe starts and rewrites the state`);return{sessions:r.data.sessions.map(([a,c])=>[a,{sessionUri:c.sessionUri,...c.chatUri===void 0?{}:{chatUri:c.chatUri}}]),dispatched:r.data.dispatched,lastStatus:n}}class ls{#e=new Map;#o=new Map;#r=new Map;#s=[];#n=new Map;#d=new Set;#c=new Map;#l=new Map;#u=new Map;#f=new Map;#a=new Map;#g=Promise.resolve();#h;#y=!1;#w=0;#v=0;#S=!1;#m="";peer;cloud;options;constructor(e,t,r){this.peer=e,this.cloud=t,this.options=r,e.onMessage((n)=>{this.#p(n).catch((o)=>{if(o!==this.#h)this.options.log.error(`ahp-host: local turn handling failed: ${String(o)}`)})})}get registry(){return{workspaceId:this.options.workspaceId,agents:this.options.agents,sessions:this.#e,parked:this.#l}}agentMemberOf(e){for(let[t,r]of this.#e){if(r.sessionUri!==e)continue;let n;try{n=JSON.parse(t)}catch(o){throw Error(`ahp-host: session key ${t} of ${e} is not a session key: ${String(o)}`)}if(!Array.isArray(n)||typeof n[1]!=="string"||n[1]==="")throw Error(`ahp-host: session key ${t} of ${e} names no member`);return n[1]}return}async start(e){this.#y=!1;let t=await this.peer.request("initialize",{channel:"ahp-root://",protocolVersions:[St],clientId:e},as);if(t?.protocolVersion!==St)throw Error(`ahp-host: the local ahpd answered protocol ${String(t?.protocolVersion)}, not ${St}`);let r=await this.options.store?.load();if(r===void 0){this.#x();return}let n=ds(r,this.options.log);for(let[a,c]of n.sessions){if(c.chatUri!==void 0){this.#e.set(a,{sessionUri:c.sessionUri,chatUri:c.chatUri});continue}let d;try{d=await this.#N(c.sessionUri)}catch(u){if(Tf(u)==="AGENT_NOT_MAPPED"){this.#k(a,c.sessionUri,u);continue}throw u}this.#d.delete(c.sessionUri),this.peer.notify("unsubscribe",{channel:c.sessionUri}),this.#e.set(a,{sessionUri:c.sessionUri,chatUri:d})}let o=[],s=this.#e,i=new Map(n.lastStatus);for(let[a,c]of n.dispatched)for(let d of c){let u;try{u=Be([S().min(1),S().min(1)]).parse(JSON.parse(d))}catch{throw Error("ahp-host: invalid durable state attempt")}let[l,p]=u,f=i.get(d);if(f!==void 0&&(f.deliveryId!==l||f.turnId!==p))throw Error("ahp-host: invalid durable state attempt status");if(f?.event==="chat/turnComplete"||f?.event==="x-hh/turnFailed")continue;let m=s.get(a);if(m?.chatUri===void 0)throw Error("ahp-host: invalid durable state attempt session");o.push({event:"x-hh/turnFailed",workspaceId:this.options.workspaceId,deliveryId:l,turnId:p,channel:m.chatUri,session:m.sessionUri,chat:m.chatUri,turnState:"error",statusCode:"HOST_RESTARTED",errorCode:"HOST_RESTARTED"})}for(let[a,c]of n.dispatched)this.#o.set(a,new Set(c));for(let[a,c]of n.lastStatus)this.#a.set(a,c);for(let a of o)await this.#t(a);await this.#b(),this.#x()}#x(){this.#y=!0;for(let e of this.#s.splice(0))this.#O(e)}#k(e,t,r){let n=r instanceof Error?r.message:String(r);this.#l.set(e,n),this.#e.set(e,{sessionUri:t}),this.options.log.error(`hightea-pipe: saved session ${t} is parked: ahpd will not resume it and its agent is not mapped (AGENT_NOT_MAPPED), so its wakes are refused by name; every other agent on this host carries on: ${n}`)}#R(e,t){if(!(typeof t==="object"&&t!==null&&Array.isArray(t.protocolVersions)?t.protocolVersions.filter((s)=>typeof s==="string"):[]).includes(St)){this.cloud.reply(e,{error:{code:-32005,message:"UnsupportedProtocolVersion",data:{supportedVersions:[St]}}});return}let n=t._meta;if(typeof n==="object"&&n!==null&&n[A_]===!0)this.#S=!0;let o=t.clientId;if(typeof o==="string"&&o!=="")this.#m=o;if(!this.#y){this.#s.push(e);return}this.#O(e)}#O(e){let t=this.options.handshake,r=t?.sources?.(),n=t?.capabilities?.filter((s)=>s!==ln||this.#S),o={...t===void 0?{}:{ahpd:t.ahpd},...n===void 0||n.length===0?{}:{capabilities:n},...r===void 0||r.length===0?{}:{sources:r}};this.cloud.reply(e,{result:{protocolVersion:St,serverSeq:0,...t?.plugin===void 0?{}:{serverInfo:t.plugin},...Object.keys(o).length===0?{}:{_meta:o},snapshots:[]}})}#b(){let e={sessions:[...this.#e],dispatched:[...this.#o].map(([t,r])=>[t,[...r]]),lastStatus:[...this.#a]};return this.#g=this.#g.then(()=>this.options.store?.save(e)).catch((t)=>{if(this.#h===void 0){this.#h=Error("ahp-host: durable state write failed",{cause:t});for(let r of this.#r.values())r.cancelled=!0;this.options.log.error(`${this.#h.message}: ${String(t)}`)}throw this.#h}),this.#g}async#U(e,t){if(!(typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).sort().join(",")==="agentMemberId,workspaceId"&&t.workspaceId===this.options.workspaceId&&typeof t.agentMemberId==="string")){if(e!==void 0)this.cloud.answer(e,{ok:!1,code:"OPERATION_SHAPE_INVALID"});return}let n=t.agentMemberId;for(let s of this.#r.values())if(s.workspaceId===this.options.workspaceId&&s.agentMemberId===n)s.cancelled=!0;let o=[];for(let[s,i]of this.#n){let a=i.filter((d)=>d.meta.agentMemberId!==n),c=this.#e.get(s);for(let d of i.filter((u)=>u.meta.agentMemberId===n))o.push(this.#t({event:"x-hh/turnFailed",workspaceId:d.meta.workspaceId,deliveryId:d.meta.deliveryId,channel:c?.chatUri??"",session:c?.sessionUri??"",chat:c?.chatUri??"",turnId:d.turnId,turnState:"error",statusCode:"GRANT_REVOKED",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}));this.#n.set(s,a)}if(await Promise.all(o),e!==void 0)this.cloud.answer(e,{ok:!0})}async fromCloud(e){let t=e?.id;if(e?.method==="initialize"){if(t===void 0){this.options.log.error("hightea-pipe: an initialize frame carries no id; nothing to answer");return}this.#R(t,e.params);return}if(!this.#y||this.#h!==void 0){if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"WAKE_NOT_SENT"});return}let r=typeof e?.method==="string"?e.method:void 0;if(r!==void 0&&R_(r,t)){let o=String(t??""),s=await wf({method:r,params:e.params,meta:e._meta},{agents:this.options.agents,memberOf:(i)=>this.agentMemberOf(i),peer:this.peer,log:this.options.log,hostToolsServer:(i)=>this.#E(i),rememberHostTools:(i,a)=>this.#f.set(i,a),ownSessions:()=>[...this.#e.values()].map((i)=>i.sessionUri),toolsAnswerOf:(i)=>this.#f.get(i)});this.cloud.hostRequestAnswer(o,s);return}if(e?.method==="x-hightea/revoke")return this.#U(t,e.params).catch(()=>{if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"OPERATION_SHAPE_INVALID"})});let n=yf(e,this.registry);if(!n.ok){if(n.code==="WAKE_TEXT_NOT_ALLOWED")this.options.log.error(`hightea: refused turn ${String(t??"")}: its text is not the delivery's own wake (WAKE_TEXT_NOT_ALLOWED); nothing reached the agent`);if(t===void 0){let o=e?.params?._meta,s=typeof o?.deliveryId==="string"?o.deliveryId:"unknown";this.options.log.error(`hightea-pipe: refused ${String(e.method)} for delivery ${s}: ${n.code}; nothing reached the agent`)}else this.cloud.answer(t,n);return}try{let o;if(n.operation==="createSession"){let s=this.options.agents.get(n.meta.agentMemberId);if(s===void 0)throw new vt("ahp-host: local agent mapping disappeared");let i,a;try{a=await this.options.startSession({owner:this.options.owner,provider:s.provider,workingDirectory:C_(s.workingDirectory),tools:this.options.tools,...s.settings===void 0?{}:{config:s.settings}},async(d)=>{if(this.options.store?.reserve!==void 0){let u=await this.options.store.reserve(n.sessionKey,d);if(this.#e.set(n.sessionKey,{sessionUri:u}),u!==d)throw i=u,Error("ahp-host: durable session mapping already won by an existing URI");await this.#b();return}this.#e.set(n.sessionKey,{sessionUri:d}),await this.#b()})}catch(d){if(i===void 0)throw d;a=i}if(this.#e.get(n.sessionKey)?.sessionUri!==a)throw Error("ahp-host: created session differs from its durable reservation");let c=i!==void 0?await this.#N(a):await this.#Z(a);this.#e.set(n.sessionKey,{sessionUri:a,chatUri:c}),this.#c.set(a,Promise.resolve()),await this.#b(),await this.#t({event:"session/ready",workspaceId:n.meta.workspaceId,deliveryId:n.meta.deliveryId,...n.meta.turnId===void 0?{}:{turnId:n.meta.turnId},channel:c,session:a,chat:c,turnState:"created",statusCode:"SESSION_CREATED"})}else if(n.operation==="subscribe"){let s=n.frame.params.channel,i=this.#e.get(n.sessionKey);if(i?.sessionUri!==s||i.chatUri===void 0)throw Error("ahp-host: a subscribe reached a session this host has no chat for");o={snapshot:{resource:s,state:{defaultChat:i.chatUri}}}}else await this.#T(n.sessionKey,n.frame,{...n.meta,...n.triggering===void 0?{}:{triggering:n.triggering}},n.turnId);if(t!==void 0)if(o===void 0)this.cloud.answer(t,{ok:!0});else this.cloud.reply(t,{result:o})}catch(o){let s=Tf(o);if(this.options.log.error(`ahp-host: cloud operation ${n.operation} failed (${s}): ${String(o)}`),t!==void 0)this.cloud.answer(t,{ok:!1,code:s})}}async#P(e,t){let r=this.#c.get(e);if(r===void 0)r=this.#N(e).then((n)=>{if(n!==t)throw Error("ahp-host: saved session answered a different chat")}),this.#c.set(e,r),r.catch(()=>{if(this.#c.get(e)===r)this.#c.delete(e)});await r}async#N(e){let t=await this.options.startSession({owner:this.options.owner,resume:e});if(t!==e)throw Error(`ahp-host: resumed session ${t} differs from ${e}`);return this.#Z(e)}async#Z(e){let t=await this.peer.request("subscribe",{channel:e},as);this.#d.add(e),this.#F(e,t?.snapshot?.state?.customizations),this.#H(e,t?.snapshot?.state);let r=t?.snapshot?.state?.defaultChat;if(typeof r!=="string"||r.length===0)throw Error(`ahp-host: ${e} answered no defaultChat`);return r}async#T(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0||n===void 0)throw Error("ahp-host: a turn reached dispatch without its mapping or turn id");let s=this.#o.get(e)??new Set,i=ir(r.deliveryId,n);if(s.has(i)){let c=this.#a.get(i);if(await this.#g,c!==void 0)this.#D(c);return}if(this.options.admitTurn!==void 0)await this.options.admitTurn(r);await this.#P(o.sessionUri,o.chatUri);let a=this.#r.get(e);if(a!==void 0){if(a.deliveryId===r.deliveryId)a.cancelled=!0;let c=this.#n.get(e)??[];for(let u of c)if(u.meta.deliveryId===r.deliveryId&&u.turnId!==n)s.add(ir(u.meta.deliveryId,u.turnId));s.add(i),this.#o.set(e,s);let d=c.filter((u)=>u.meta.deliveryId!==r.deliveryId||u.turnId===n);if(!d.some((u)=>u.meta.deliveryId===r.deliveryId))d.push({frame:t,meta:r,turnId:n});this.#n.set(e,d),await this.#b();return}await this.#C(e,t,r,n)}async#C(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0)throw Error("ahp-host: dispatch has no mapped chat");if(this.#A(o.sessionUri,o.chatUri).length>0)throw Error("ahp-host: wake already active for this session and chat");let s={key:e,deliveryId:r.deliveryId,workspaceId:r.workspaceId,agentMemberId:r.agentMemberId,sessionUri:o.sessionUri,chatUri:o.chatUri,turnId:n,startedAtMs:Date.now(),clientSeq:O_(t),cancelled:!1,stopReason:void 0,finishing:!1},i=this.#o.get(e)??new Set;if(i.add(ir(r.deliveryId,n)),this.#o.set(e,i),this.#r.set(e,s),await this.#b(),s.cancelled){this.#r.delete(e),await this.#t({event:"x-hh/turnFailed",workspaceId:r.workspaceId,deliveryId:r.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:n,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}),await this.#M(s);return}if(!this.#d.has(o.chatUri))this.#d.add(o.chatUri),this.peer.request("subscribe",{channel:o.chatUri},as);this.peer.notify("dispatchAction",{...t.params,clientSeq:++this.#w})}#A(e,t){return[...this.#r.values()].filter((r)=>r.sessionUri===e&&r.chatUri===t)}#_(e){this.#B(e)}#j(e,t){let r=this.#E(e);if(r===void 0||t.id!==r.customizationId)return;if(e===""||this.agentMemberOf(e)===void 0)return;let n=ye(t.state)?t.state:void 0;if(n?.kind!=="authRequired"||n.reason!=="expired")return;this.cloud.authRequired({channel:e,resource:r.resource,reason:"expired"})}#E(e){let t=this.options.hostTools;if(t===void 0)return;let r=this.#u.get(e);return r===void 0?void 0:{resource:t.resource,customizationId:r}}#F(e,t){let r=this.options.hostTools;if(r===void 0||!Array.isArray(t))return;let n=t.find((s)=>ye(s)&&s.type==="mcpServer"&&s.name===r.name),o=n!==void 0&&typeof n.id==="string"&&n.id!==""?n.id:void 0;if(o===void 0)this.#u.delete(e);else this.#u.set(e,o);if(o===void 0)this.#f.set(e,{available:!1,reason:"its backend published no Hightea MCP server"});else this.#f.set(e,{available:!0})}#H(e,t){if(this.options.hostTools===void 0)return;let r=ye(t)?ye(t._meta)?t._meta:t:void 0,n=er.safeParse(r?.[st]);if(n.success)this.#f.set(e,n.data)}#z(e){let t=this.agentMemberOf(e),r=this.#f.get(e);if(t===void 0||r===void 0)return;let n=this.#E(e),o={available:r.available,...r.reason===void 0?{}:{reason:r.reason},...r.available&&n!==void 0?{server:n}:{}};this.cloud.sessionChanged({channel:"ahp-root://",session:e,changes:{_meta:{"hh/agentMemberId":t,"hh/hostTools":o}}})}#B(e){if(!ye(e)){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged carries no params object");return}let t=e.session;if(typeof t!=="string"||t===""){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged names no session");return}let r=this.agentMemberOf(t);if(r===void 0)return;let n=ye(e.changes)?e.changes:void 0,o=n!==void 0&&ye(n._meta)?n._meta:void 0,s=tr(o,r,this.#E(t));if(s===void 0){this.options.log.error(`hightea-pipe: ${t} changed under another member's name; nothing was sent`);return}let i=s["hh/hostTools"];if(i===void 0){if(o?.[st]!==void 0)this.options.log.error(`hightea-pipe: ${t} changed ${st} to a shape this host does not read`);return}this.#f.set(t,i),this.cloud.sessionChanged({channel:"ahp-root://",session:t,changes:{_meta:{"hh/agentMemberId":s["hh/agentMemberId"],"hh/hostTools":i}}})}async#p(e){let t=e?.params;if(t?.action?.type==="session/customizationsChanged"){if(typeof t.channel==="string"&&this.agentMemberOf(t.channel)!==void 0){let i=this.#u.get(t.channel);if(this.#F(t.channel,t.action.customizations),this.#u.get(t.channel)!==i)this.#z(t.channel)}return}if(t?.action?.type==="session/mcpServerStateChanged"){this.#j(typeof t.channel==="string"?t.channel:"",t.action);return}if(ye(e)&&e.method==="root/sessionSummaryChanged")return this.#_(e.params);let r=e?.params,n=r?.action;if(n===void 0||typeof r?.channel!=="string")return;if(n.type==="session/inputNeededSet"){let i=n.request,a=i?.kind==="toolConfirmation"&&i.toolCall?.status==="pending-confirmation",c=i?.kind==="chatInput";if(!a&&!c)return;let d=typeof i.request?.id==="string"&&i.request.id!==""?i.request.id:typeof i.id==="string"&&i.id!==""?i.id:"unknown",u=typeof i.chat==="string"?i.chat:"",l=r.channel,p=this.#A(l,u),f=a&&typeof i.turnId==="string"?i.turnId:"",m=p.filter((w)=>!w.cancelled&&!w.finishing&&w.stopReason===void 0),y=a&&f==="",g=f!==""?p.find((w)=>w.turnId===f):m.length===1?m[0]:void 0;if(g===void 0||y){this.#v++;let w=f!==""?"INPUT_REQUEST_UNMATCHED_TURN":"INPUT_REQUEST_UNATTRIBUTED";this.options.log.error(`hightea-pipe: ${w} ${JSON.stringify({sessionId:l,chatId:u,kind:i.kind,requestId:d,droppedCount:this.#v,...f===""?{liveWakeCount:m.length}:{turnId:f}})}`)}if(g===void 0||g.cancelled||g.finishing||g.stopReason!==void 0)return;if(g.stopReason=y?"OPERATION_SHAPE_INVALID":c?"INPUT_REQUIRED":"APPROVAL_REQUIRED",a&&!y){let w=typeof i?.toolCall?.toolName==="string"?i.toolCall.toolName:"",b=/^[A-Za-z0-9_.:-]{1,64}$/u.test(w)?`tool ${w}`:w===""?"a tool it did not name":`tool name withheld (${w.length} chars)`;(this.options.log.warn??this.options.log.error)(`hightea-pipe: turn ${g.turnId} needs approval for ${b}`)}if(g.stopStatusCode=y?"INPUT_REQUEST_UNATTRIBUTED":g.stopReason,y)g.stopDetail=`INPUT_REQUEST_UNATTRIBUTED:${d}`.slice(0,256);this.peer.notify("dispatchAction",{channel:g.chatUri,clientSeq:++this.#w,action:{type:"chat/turnCancelled",turnId:g.turnId,duration:Math.max(0,Date.now()-g.startedAtMs)}});return}let o=[...this.#r.values()].find((i)=>i.chatUri===r.channel&&i.turnId===n.turnId);if(o===void 0||o.finishing)return;let s={workspaceId:o.workspaceId,deliveryId:o.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:o.turnId,clientSeq:o.clientSeq};if(n.type==="chat/turnStarted"){if(o.stopReason!==void 0)return;await this.#t({event:"chat/turnStarted",...s,turnState:"running",statusCode:"TURN_RUNNING"},o.startedAtMs)}else if(n.type==="chat/turnComplete"||n.type==="chat/turnCancelled"||n.type==="chat/error"){o.finishing=!0;let i=n.type==="chat/turnComplete"&&o.stopReason===void 0,a=n.type==="chat/turnCancelled"&&o.stopReason===void 0,c=o.stopReason??(a?"TURN_CANCELLED":"OPERATION_SHAPE_INVALID"),d=o.stopStatusCode??o.stopReason??(a?"TURN_CANCELLED":"TURN_ENDED");await this.#t(i?{event:"chat/turnComplete",...s,turnState:"finished",statusCode:"TURN_FINISHED"}:{event:"x-hh/turnFailed",...s,turnState:"error",statusCode:d,errorCode:c,...o.stopDetail===void 0?{}:{errorDetail:o.stopDetail}},o.startedAtMs),this.#r.delete(o.key),await this.#M(o)}}async#M(e){if(this.#r.has(e.key))return;let r=(this.#n.get(e.key)??[]).shift();if(r===void 0){this.#d.delete(e.chatUri),this.#d.delete(e.sessionUri),this.peer.notify("unsubscribe",{channel:e.chatUri}),this.peer.notify("unsubscribe",{channel:e.sessionUri}),this.#c.delete(e.sessionUri);return}let n=P_(r.meta),o=n===void 0,s=n!==void 0&&Date.now()-n>gn;if(!s&&!o)try{await this.#C(e.key,r.frame,r.meta,r.turnId);return}catch(a){if(this.#h!==void 0)throw a}if(s||o)this.options.log.error(`ahp-host: queued wake ${r.meta.deliveryId} retired before dispatch (${n===void 0?"ASK_UNSIGNED: no signed triggering envelope":`ASK_STALE: newest trigger signed at ${new Date(n).toISOString()}`})`);let i=this.#e.get(e.key);await this.#t({event:"x-hh/turnFailed",workspaceId:r.meta.workspaceId,deliveryId:r.meta.deliveryId,channel:i?.chatUri??e.chatUri,session:i?.sessionUri??e.sessionUri,chat:i?.chatUri??e.chatUri,turnId:r.turnId,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:o?"ASK_UNSIGNED":"ASK_STALE"}),await this.#M(e)}#t(e,t){let r=pf(e);if(this.#a.set(r.turnId===void 0?r.deliveryId:ir(r.deliveryId,r.turnId),r),this.options.store===void 0)return this.#D(r,t),Promise.resolve();return this.#b().then(()=>{this.#D(r,t)})}#D(e,t){if(!this.#S)return this.cloud.status(e);this.cloud.action($_(e,{...this.#m===""?{}:{clientId:this.#m},...t===void 0?{}:{startedAtMs:t}}))}}var yn=Be([S().min(1),S().min(1),S().min(1)]),U_=k({id:S(),version:H(1),tuple:yn,owner:S().min(1),sessionUri:S().regex(or)}).strict(),$f=(e)=>`session-${zf("sha256").update(e).digest("hex").slice(0,32)}`,Pf=k({id:S(),version:H(1),tuple:yn,sessionUri:S().regex(or),chatUri:S().min(1)}).strict(),Nf=(e)=>`chat-${zf("sha256").update(e).digest("hex").slice(0,32)}`;function Mf(e,t,r,n,o){let s=new Map,i=new Map,a=async(f,m)=>{if(o===void 0||m.chatUri===void 0||i.get(f)===m.chatUri)return;let y=yn.parse(JSON.parse(f)),g=Nf(f);try{await o.put({id:g,version:1,tuple:y,sessionUri:m.sessionUri,chatUri:m.chatUri},{createOnly:!0})}catch(w){if(w?.code!==-32010)throw w;let b=Pf.safeParse(await o.get(g));if(!b.success||b.data.sessionUri!==m.sessionUri||b.data.chatUri!==m.chatUri)throw Error("ahp-host: conflicting durable session chat",{cause:w})}i.set(f,m.chatUri)},c=async()=>{let f=new Map;for(let m of await o?.list()??[]){let y=Pf.safeParse(m);if(!y.success)throw Error("ahp-host: invalid durable session chat");let g=JSON.stringify(y.data.tuple);if(y.data.id!==Nf(g))throw Error("ahp-host: durable session chat has a different key");f.set(g,{sessionUri:y.data.sessionUri,chatUri:y.data.chatUri})}return f},d=(f)=>{let m=U_.safeParse(f);if(!m.success)throw Error("ahp-host: invalid durable session mapping");let y=m.data,g=JSON.stringify(y.tuple);if(y.id!==$f(g)||y.owner!==t)throw Error("ahp-host: durable session mapping has a different key or owner");return[g,{sessionUri:y.sessionUri}]},u=async(f,m)=>{let y=yn.parse(JSON.parse(f));if(JSON.stringify(y)!==f||!or.test(m))throw Error("ahp-host: invalid session mapping to publish");let g=s.get(f);if(g!==void 0)return g.sessionUri;let w=$f(f),b=m;try{await e.put({id:w,version:1,tuple:y,owner:t,sessionUri:m},{createOnly:!0})}catch(v){if(v?.code!==-32010)throw v;let x=await e.get(w);if(x===void 0)throw v;let[I,R]=d(x);if(I!==f)throw Error("ahp-host: conflicting durable session mapping",{cause:v});if(R.sessionUri!==m&&await r(R.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner",{cause:v});b=R.sessionUri}return s.set(f,{sessionUri:b}),b},l=async(f,m)=>{if(await u(f,m.sessionUri)!==m.sessionUri)throw Error("ahp-host: conflicting durable session mapping")},p=(f)=>e.put({id:"state",version:2,state:{dispatched:f.dispatched,lastStatus:f.lastStatus}});return{reserve:u,load:async()=>{let f=await e.get("state"),m={sessions:[],dispatched:[],lastStatus:[]};if(f!==void 0){if(f.id!=="state"||f.version!==1&&f.version!==2||!("state"in f))throw Error("ahp-host: invalid durable state record");let g=f.version===1?f.state:typeof f.state==="object"&&f.state!==null?{sessions:[],...f.state}:f.state,w=ds(g,n);if(f.version===2&&w.sessions.length!==0)throw Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");m=w}let y=new Map;for(let g of await e.list()){if(g.id==="state")continue;let[w,b]=d(g);if(await r(b.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner");y.set(w,b)}s.clear();for(let[g,w]of y)s.set(g,w);for(let[,g]of m.sessions)if(await r(g.sessionUri)!==t)throw Error("ahp-host: legacy session belongs to an unknown or different owner");for(let[g,w]of m.sessions)await l(g,w),y.set(g,w);if(f?.version===1)await p(m);i.clear();for(let[g,w]of await c()){let b=y.get(g);if(b===void 0||b.sessionUri!==w.sessionUri)throw Error("ahp-host: durable session chat names no mapping or a different session");y.set(g,{sessionUri:b.sessionUri,chatUri:w.chatUri}),i.set(g,w.chatUri)}return{sessions:[...y],dispatched:m.dispatched,lastStatus:m.lastStatus}},save:async(f)=>{for(let[m,y]of f.sessions)await l(m,y),await a(m,y);await p(f)}}}import{randomUUID as Z_}from"node:crypto";var j_=15000,F_=(e)=>{if(e===null||typeof e!=="object")return;let t=e.message;return typeof t==="string"&&rr.includes(t)?t:void 0};function Df(e){let{log:t,receive:r}=e,n=!1,o=1000,s,i,a=new Map,c=(g,w=!0)=>{if(w)t.error(`hightea-pipe: ${g}`);for(let b of a.values())clearTimeout(b.timer),b.reject(Error(g));a.clear()},d=(g,w)=>{if(!n&&g!==void 0&&g===i&&g.live&&g.socket?.readyState===1)try{return g.socket.send(JSON.stringify(w)),!0}catch{}return t.error("hightea-pipe: CONTROL_SOCKET_UNAVAILABLE"),!1},u=(g)=>d(i,g),l=(g,w,b)=>{if(g===void 0||g.readyState>=2)return;try{if(w===void 0)g.close();else g.close(w,b)}catch{t.error("hightea-pipe: CONTROL_SOCKET_CLOSE_FAILED")}},p=(g,w)=>{if(n)return;if(n=!0,s!==void 0)clearTimeout(s);if(s=void 0,i!==void 0)i.live=!1;c("CONTROL_SOCKET_CLOSED",!1),l(i?.socket,g,w)},f=(g,w)=>{let b;try{b=JSON.parse(String(g.data))}catch{t.error("hightea-pipe: CONTROL_FRAME_INVALID");return}if(b!==null&&typeof b==="object"&&!Array.isArray(b)){let v=b;if(v.method===void 0&&(("result"in v)||("error"in v))){let x=typeof v.id==="string"?a.get(v.id):void 0;if(x===void 0){t.error("hightea-pipe: CONTROL_RESPONSE_UNKNOWN");return}if(a.delete(v.id),clearTimeout(x.timer),v.jsonrpc==="2.0"&&"result"in v&&!("error"in v))x.resolve(v.result);else{let I="error"in v?F_(v.error):void 0;t.error(`hightea-pipe: CONTROL_REQUEST_REFUSED${I===void 0?"":` ${I}`}`),x.reject(Error(I===void 0?"CONTROL_REQUEST_REFUSED":`CONTROL_REQUEST_REFUSED ${I}`))}return}}r(b,w)},m=()=>{if(n)return;let g={live:!0,opened:!1};i=g;let w=()=>{if(n||s!==void 0)return;let x=o;o=Math.min(o*2,60000),s=setTimeout(()=>{s=void 0,m()},x)},b=(x)=>{if(n||i!==g||!g.live)return;g.live=!1,c(x),l(g.socket),w()},v=(x,I)=>{if(n||i!==g)return;t.error(`${I===void 0||I===""?`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}`:`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}: ${I}`}`),p()};try{let x=e.dial((E)=>{if(E===401||E===403)v(E);else b("CONTROL_SOCKET_ERROR")});g.socket=x;let I={send:(E)=>d(g,E),close:(E,A)=>p(E,A)};x.addEventListener("message",(E)=>{if(!n&&i===g&&g.live)f(E,I)}),x.addEventListener("error",()=>b("CONTROL_SOCKET_ERROR")),x.addEventListener("close",(E)=>{if(E.code===4003||E.code===4004)v(E.code,E.reason);else b("CONTROL_SOCKET_CLOSED")});let R=()=>{if(n||i!==g||!g.live||g.opened)return;g.opened=!0,o=1000,e.opened?.(I)};if(x.addEventListener("open",R),n||!g.live)l(x);else if(x.readyState===1)R()}catch{b("CONTROL_SOCKET_ERROR")}},y=(g,w,b)=>new Promise((v,x)=>{let I=setTimeout(()=>{a.delete(g),t.error("hightea-pipe: CONTROL_REQUEST_TIMEOUT"),x(Error("CONTROL_REQUEST_TIMEOUT"))},j_);if(a.set(g,{resolve:v,reject:x,timer:I}),!u({jsonrpc:"2.0",id:g,method:w,params:b}))a.delete(g),clearTimeout(I),x(Error("CONTROL_SOCKET_UNAVAILABLE"))});return queueMicrotask(m),{send:u,close:p,answer:(g,w)=>u(w.ok?{jsonrpc:"2.0",id:g,result:null}:{jsonrpc:"2.0",id:g,error:{code:-32000,message:w.code}}),reply:(g,w)=>u("result"in w?{jsonrpc:"2.0",id:g,result:w.result}:{jsonrpc:"2.0",id:g,error:w.error}),status:(g)=>u({jsonrpc:"2.0",method:"x-hightea/status",params:g}),sessionChanged:(g)=>void u({jsonrpc:"2.0",method:"root/sessionSummaryChanged",params:g}),action:(g)=>u({jsonrpc:"2.0",method:"action",params:g}),authRequired:(g)=>u({jsonrpc:"2.0",method:"auth/required",params:g}),sourcePush:(g)=>y(`push:${Z_()}`,"x-hightea/source/push",g),hostRequestAnswer:(g,w)=>void u({jsonrpc:"2.0",id:g,...af(w)})}}import{spawn as J_}from"node:child_process";import{createHash as Vf}from"node:crypto";import{createInterface as Y_}from"node:readline";import{randomUUID as Lf}from"node:crypto";var _n=1e4,H_=1024;function B_(e,t,r){let n=0;while(n<e.length&&t+te(e[n])>r)n++;let o=[],s=t;for(let i=n;i<e.length;i++){let a=e[i],c=te(a)+(o.length===0?0:1);if(o.length>0&&s+c>r)break;o.push(a),s+=c}return{dropped:e.slice(0,n),batch:o}}class ar{sourceId;#e="e_"+Lf();#o=0n;#r=[];#s=!1;#n;#d=-1/0;#c=0;#l=-1/0;#u=!0;#f=new AbortController;#a;#g;#h;#y;#w;#v=!1;constructor(e){this.#a=e,this.sourceId=e.sourceId,this.#g=e.coalesceMs??2000;let t=e.soonMs??500;if(!(Number.isFinite(t)&&t>=0))throw Error(`soonMs must be a finite number of milliseconds, 0 or more, not ${String(t)}`);this.#h=t,this.#y=e.now??Date.now,this.#w=e.unackedMax??_n}get epoch(){return this.#e}get ordinal(){return this.#o}get watching(){return this.#u}get unacknowledged(){return this.#r.length}get stopped(){return this.#f.signal.aborted}#S(){return this.#o++,{epoch:this.#e,ordinal:String(this.#o)}}next(){return this.#S()}watch(e){if(this.#u=e,!e){if(this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0;return}this.#m()}enqueue(e,t){if(this.#r.push(...e),this.#r.length>this.#w){this.#a.log.error(`hightea-source: ${this.sourceId} has more than ${this.#w} unacknowledged observations; starting a new epoch`),this.#r.length=0,this.#e="e_"+Lf(),this.#o=0n,this.#a.onOverflow();return}if(t?.soon===!0){if(this.#v=!0,this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}if(this.#m(),this.#r.length===0)this.#v=!1}#m(){if(!this.#u||this.#s||this.#r.length===0||this.#n!==void 0||this.#f.signal.aborted)return;let e=this.#l-this.#y();if(e>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#m()},e);return}let t=this.#v?Math.min(this.#g,this.#h):this.#g,r=this.#d+t-this.#y();if(r>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#m()},r);return}let n=cn-H_,o=te({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:{epoch:this.#e,ordinal:"0"},observations:[]}),{dropped:s,batch:i}=B_(this.#r,o,n);if(s.length>0){this.#r.splice(0,s.length);for(let d of s)this.#a.onOmit?.(d.change.op==="upsert"?d.change.row.address:d.change.address,`${te(d)} bytes cannot fit a ${n}-byte push frame even alone; a later change to that row is what reports it`)}if(i.length===0)return;let a=i[i.length-1],c=this.#e;this.#s=!0,this.#d=this.#y(),this.#v=!1,this.#a.push({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:a.position,observations:i}).then((d)=>{if(this.#c>0)this.#a.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#c} refusal(s)`),this.#c=0,this.#l=-1/0;let u=ql.safeParse(d);if(!u.success){this.#a.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);return}let l=u.data.applied;if(l===null||l.epoch!==c||l.epoch!==this.#e)return;let p=BigInt(l.ordinal),f=0;while(f<this.#r.length&&BigInt(this.#r[f].position.ordinal)<=p)f++;this.#r.splice(0,f)},(d)=>{this.#c++;let u=Math.min(this.#g*2**Math.min(this.#c-1,5),60000);if(this.#l=this.#y()+u,this.#c===1){let l=d instanceof Error?d.message:String(d);this.#a.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${l}; retrying with backoff, next in ${Math.round(u/1000)} s`)}}).finally(()=>{this.#s=!1,this.#m()})}stop(){if(this.#f.abort(),this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}}import{spawn as q_}from"node:child_process";import{createInterface as G_}from"node:readline";var Uf=65536,K_=2000,Zf=16777216,V_=8,W_=5000;class pe extends Error{code;constructor(e,t){super(t);this.code=e}}function wn(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function xt(e){let t=e.stderr.trim().split(`
67
+ `).filter((n)=>n!=="").pop(),r=e.code===null?"on a signal":`exit ${e.code}`;return t===void 0?r:`${r}: ${t.slice(0,400)}`}var jf=(e,t)=>{let[r,...n]=e;if(r===void 0)throw new pe("page-serve-no-command","the page reader has no command to run");let o=q_(r,n,{stdio:["pipe","pipe","pipe"],detached:!0}),s="",i,a,c=[],d=0,u=()=>{return},l=new Promise((v)=>{u=v}),p=(v)=>{let x=a;if(x===void 0)return;if(a=void 0,x.timer!==void 0)clearTimeout(x.timer);x.reject(v)};function f(){if(a!==void 0||c.length===0||i!==void 0)return;let v=c.shift();if(v.timer!==void 0)clearTimeout(v.timer);m(v.request,v.timeoutMs,v.resolve,v.reject)}function m(v,x,I,R){let E={seq:++d,traverse:"traverse"in v&&v.traverse===!0,pages:[],bytes:0,askedAt:Date.now(),deadline:Date.now()+x,resolve:I,reject:R,timer:void 0};a=E,E.timer=setTimeout(()=>{y("page-serve-timeout",`the reader did not answer seq ${E.seq} in ${x} ms`)},x);try{o.stdin.write(JSON.stringify({seq:E.seq,request:v})+`
68
+ `)}catch(A){y("page-serve-write-failed",`the request could not be written: ${A instanceof Error?A.message:String(A)}`)}}let y=(v,x)=>{p(new pe(v,x)),wn(o,"SIGKILL")},g=(v)=>{if(v.trim()==="")return;let x;try{x=JSON.parse(v)}catch{y("page-serve-frame-unparsable",`the reader answered a line that is not JSON: ${v.slice(0,120)}`);return}let I=x,R=typeof I.rss==="number"&&Number.isFinite(I.rss)?I.rss:void 0,E=a;if(E===void 0){y("page-serve-frame-unasked",`the reader answered seq ${String(I.seq)} with no request outstanding`);return}if(I.seq!==E.seq){y("page-serve-frame-out-of-order",`the reader answered seq ${String(I.seq)} while seq ${E.seq} was asked`);return}let A=I.refusal;if(A!==void 0&&A!==null){if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({...R===void 0?{}:{rss:R},refusal:{code:typeof A.code==="string"?A.code:"page-serve-refused",message:typeof A.message==="string"?A.message:"the reader refused without a message",...typeof A.hint==="string"?{hint:A.hint}:{}}}),f();return}if(I.page===void 0&&I.progress!==void 0){if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({...R===void 0?{}:{rss:R},progress:I.progress}),f();return}if(I.page===null||typeof I.page!=="object"||Array.isArray(I.page)){y("page-serve-frame-malformed",`the reader answered seq ${E.seq} outside the page shape`);return}if(E.bytes+=v.length,E.bytes>Zf){y("page-serve-answer-too-large",`the reader's answer to seq ${E.seq} exceeded its byte budget (${Zf} bytes)`);return}let q=I.page.complete;if(E.pages.push(I.page),E.traverse&&q!==!0)return;if(a=void 0,E.timer!==void 0)clearTimeout(E.timer);E.resolve({pages:E.pages,...R===void 0?{}:{rss:R}}),f()};G_({input:o.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",g),o.stderr.setEncoding("utf8").on("data",(v)=>{if(s.length<Uf)s+=v}),o.stdin.on("error",()=>{if(s.length<Uf)s+=`
69
69
  hightea-page-serve: the request pipe failed to write`}),o.on("error",(v)=>{s+=`
70
- hightea-page-serve: ${v.message}`});let w=new Promise((v)=>{o.on("close",(x,I)=>{_n(o,"SIGKILL"),i={code:I===null?x:null,stderr:s},p(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`));for(let C of c.splice(0)){if(C.timer!==void 0)clearTimeout(C.timer);C.reject(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`))}u(i),v()})}),b=async()=>{if(i!==void 0)return;o.stdin.end(),_n(o,"SIGTERM");let v=setTimeout(()=>_n(o,"SIGKILL"),q_);await w,clearTimeout(v)};return t.addEventListener("abort",()=>{b()},{once:!0}),{ask(v,x){if(i!==void 0)return Promise.reject(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`));if(a!==void 0){if(Date.now()>=a.deadline){let re=`the reader did not answer seq ${a.seq} by its ${a.deadline-a.askedAt} ms deadline, and the slot was still held`;return y("page-serve-timeout",re),Promise.reject(new pe("page-serve-timeout",re))}if(c.length>=G_)return Promise.reject(new pe("page-serve-busy",`a page request is already outstanding and ${c.length} more are waiting`));let A=Math.min(x,K_),q={request:v,timeoutMs:x,waitMs:A,resolve:()=>{return},reject:()=>{return},timer:void 0},ke=new Promise((re,Ne)=>{q.resolve=re,q.reject=Ne});return q.timer=setTimeout(()=>{let re=c.indexOf(q);if(re<0)return;c.splice(re,1),q.reject(new pe("page-serve-busy",`a page request waited ${A} ms for the one slot and seq ${a===void 0?"none":a.seq} is still unanswered`))},A),c.push(q),ke}let I=()=>{return},C=()=>{return},E=new Promise((A,q)=>{I=A,C=q});return m(v,x,I,C),E},exited:l,close:b}};var vn=16777216,J_=8,Y_=900000,fs=1000,Zf=3,X_=5000,Q_=536870912,ew=30000,tw=2000,rw=2000,nw=3,ow=300000,sw=20;function jf(e,t){if(!(Number.isFinite(t)&&t>=0))throw Error(`${e} must be a finite number of milliseconds, 0 or more, not ${String(t)}`);return t}class Sn extends Error{item;constructor(e){super(`ITEM_TOO_LARGE: ${e}`);this.item=e}}class cr extends Error{stderr;constructor(e){super(`list refused: ${bt(e)}`);this.stderr=e}}class gs{sourceId;#e;#o=0;#r;#s=new Map;#n;#l=0;#c;#f;#u;#h=!1;#a=0;#m=-1/0;#d;#y=!1;#w=!1;#_=0;#S;#v;#x;#k;#C=!1;#O;#b=0;#j;#M;#D=!1;#F=!1;#T=!1;#R;#$;#g;#A;#P;#L;#U=[];#H=-1/0;#p=new AbortController;#B;#t;#E;#N;#X;#i;#de;#Z;#Q;#le;#z;#ee;#q=!1;#G=-1/0;#te=0;#re=0;#ne=new Map;constructor(e){if(this.#t=e,this.sourceId=e.config.sourceId,this.#E=e.run??ys,this.#N=e.coalesceMs??2000,this.#X=e.hintCoalesceMs??Math.min(this.#N,500),this.#Z=e.readDuty??e.config.readDuty??0.1,!(this.#Z>0&&this.#Z<=1))throw Error(`readDuty must be in (0, 1], not ${this.#Z}`);if(this.#Q=jf("minIncrementalReadGapMs",e.config.minIncrementalReadGapMs),this.#le=jf("minFullReadGapMs",e.config.minFullReadGapMs),this.#z=e.readRetryMs??2000,!(Number.isFinite(this.#z)&&this.#z>=0))throw Error(`readRetryMs must be a finite number of milliseconds, 0 or more, not ${this.#z}`);let t=e.progressCeilingMs??tw;if(!(Number.isFinite(t)&&t>=0))throw Error(`progressCeilingMs must be a finite number of milliseconds, 0 or more, not ${t}`);this.#ee=t;let r=e.watchFloorMs??rw;if(!(Number.isFinite(r)&&r>=0))throw Error(`watchFloorMs must be a finite number of milliseconds, 0 or more, not ${String(r)}`);if(this.#P=r,e.watchRefreshMs!==void 0&&!(Number.isFinite(e.watchRefreshMs)&&e.watchRefreshMs>=0))throw Error(`watchRefreshMs must be a finite number of milliseconds, 0 or more, not ${String(e.watchRefreshMs)}`);this.#L=e.watchRefreshMs,this.#i=e.now??Date.now,this.#de=new Map(Object.entries(e.config.members).map(([n,o])=>[o,n])),this.#e=new ar({sourceId:e.config.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(n)=>e.push(n),log:e.log,coalesceMs:this.#N,now:this.#i,onOmit:(n,o)=>this.#ae(n,o),onOverflow:()=>{this.#s.clear();let n=this.#r;if(n===void 0){e.log.error(`hightea-source: ${e.config.sourceId} overflowed before its first read; reading for the new epoch`),this.#I().catch((s)=>e.log.error(`hightea-source: reading ${e.config.sourceId} after an overflow failed: ${Y(s)}`));return}this.#r=void 0;let o=new Map(n.rows.map((s)=>[s.row.address,{key:s.key,row:s.row}]));this.#W(`${this.#e.epoch}.${++this.#o}`,n.snapshot,o)}})}get epoch(){return this.#e.epoch}start(){this.#K(),this.#I().catch((e)=>this.#t.log.error(`hightea-source: the first read of ${this.sourceId} failed: ${Y(e)}`)),this.#B=this.#He()}async stop(){if(this.#p.abort(),this.#e.stop(),this.#g!==void 0)clearTimeout(this.#g);if(this.#pe(),this.#d!==void 0)clearTimeout(this.#d);await this.#B,await this.#n?.catch(()=>{return}),await this.#u?.close().catch((e)=>this.#t.log.error(`hightea-source: the km reader of ${this.sourceId} did not close: ${Y(e)}`))}hint(e){if(e!==void 0){this.#Ee(e);let i=_w(e);if(i!==void 0&&(this.#R===void 0||i.at<this.#R))this.#R=i.at,this.#$=i.source}if(this.#p.signal.aborted)return;if(this.#n!==void 0||this.#g!==void 0){this.#T=!0;return}let t=this.#c!==void 0&&!this.#q,r=t?this.#Q:this.#le,n=this.#G+Math.max(this.#te*(1/this.#Z-1),r)-this.#i(),o=Math.max(this.#X,n),s=this.#R===void 0?void 0:this.#i()-this.#R;this.#t.log.info?.(`hightea-source: ${this.sourceId} change hint: last read ${Math.round(this.#te)} ms at readDuty ${this.#Z}, ${t?"incremental":"full"} floor ${Math.round(r)} ms, progress ceiling ${Math.round(this.#ee)} ms, hint window ${Math.round(this.#X)} ms, next read in ${Math.round(o)} ms, change age ${s===void 0?"unavailable":`${Math.round(s)} ms${this.#$===void 0?"":` from ${this.#$}`}`}`),this.#g=setTimeout(()=>{this.#g=void 0,this.#I(t).catch((i)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${Y(i)}`))},o)}async handle(e){let t={workspaceId:e.workspaceId,sourceId:e.sourceId,hostId:e.hostId},r=(n,o="refused")=>({...t,op:e.op,outcome:o,code:n});if(e.sourceId!==this.sourceId)return r("SOURCE_UNBOUND");if(!this.#t.config.members[e.caller.memberId])return r("AGENT_NOT_MAPPED");try{switch(e.op){case"watch":if(this.#e.watch(e.args.on),e.args.on)this.#ie();else this.#pe();return{...t,op:"watch",outcome:"applied",body:{on:this.#e.watching}};case"list":return{...t,op:"list",outcome:"applied",...this.#w?{code:"SOURCE_READER_RESTARTING"}:{},body:await this.#Se(e.args,t)};case"read":{let n=await this.#xe();return{...t,op:"read",outcome:"applied",body:{observation:this.#oe(n,e.args.address)}}}case"assign":{let n=this.#ne.get(e.args.intentId);if(n!==void 0)return await n;let o=this.#ve(e,t).finally(()=>this.#ne.delete(e.args.intentId));return this.#ne.set(e.args.intentId,o),await o}}}catch(n){if(n instanceof Sn)return{...t,op:e.op,outcome:"refused",code:"ITEM_TOO_LARGE",item:n.item};return this.#t.log.error(`hightea-source: ${e.op} on ${this.sourceId} failed: ${Y(n)}`),r("SOURCE_UNAVAILABLE","unknown")}}async#Se(e,t){let r=e.page===void 0?void 0:fw(e.page),n=r===void 0?void 0:this.#s.get(r.generation),o=n??await this.#I(!1,!0);if(n===void 0)this.#H=this.#i();let s=n===void 0?0:r.offset,i=this.#ze(),a=[],c=(l,p)=>({generation:o.generation,snapshot:o.snapshot,base:{epoch:o.epoch,ordinal:String(o.base)},rows:p,next:l>=o.rows.length?null:lw(o.generation,l),complete:l>=o.rows.length,...this.#O===void 0?{}:{progressAsOf:new Date(this.#O).toISOString()},...i===void 0?{}:{progressStale:i}}),d=0,u=s;while(u<o.rows.length&&a.length<e.limit){let l=o.rows[u].row,p=te(l);if(te({...t,op:"list",outcome:"applied",body:c(u+1,[])})+d+p+a.length>st){if(a.length===0)throw new Sn(l.address);break}a.push(l),d+=p,u++}return c(u,a)}async#ve(e,t){return this.assign(e.args,t,e.caller.memberId)}async assign(e,t,r){let{address:n,ownerMemberId:o,expectedOwner:s,intentId:i,ifRevision:a}=e,c=this.#t.config.members[o],d=s===void 0||s===null?null:this.#J(s);if(c===void 0||d===void 0)return{...t,op:"assign",outcome:"refused",code:"AGENT_NOT_MAPPED"};let u=this.#Fe(n);if(u===void 0)return{...t,op:"assign",outcome:"refused",code:"INVALID_ADDRESS"};if(a!==void 0){let b=await this.#fe(),v=this.#oe(b,n),x=v.change.op==="upsert"?v.change.row.version:null;if(x!==a){let I=v.change.op==="upsert"?v.change.row.columns.owner??null:null;if((I===null?null:this.#J(I))!==c)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:I},revision:x,observation:v}}}}let l;if(this.#t.config.serviceIdentity)try{let b=this.#t.serviceIdentityEnvironment?.(this.sourceId);if(!b?.HAB_ID_TOKEN_FILE)throw Error("SERVICE_IDENTITY_UNAVAILABLE");l={HAB_ID_TOKEN_FILE:b.HAB_ID_TOKEN_FILE}}catch(b){if(!(b instanceof Error)||!/^SERVICE_IDENTITY_(?:NOT_GRANTED|UNAVAILABLE)(?::|$)/u.test(b.message))throw b;let v=b instanceof Error&&b.message.startsWith("SERVICE_IDENTITY_NOT_GRANTED")?"SERVICE_IDENTITY_NOT_GRANTED":"SERVICE_IDENTITY_UNAVAILABLE";return this.#t.log.error(`hightea-source: assign ${i} on ${this.sourceId}: ${v}`),{...t,op:"assign",outcome:"unknown",code:v}}let p={authority:`hightea:${t.workspaceId}`,subject:r},f=await this.#Y(["issues","assign",u,c,"--id",i,"--expected-owner",JSON.stringify(d),"--requested-by",JSON.stringify(p)],l),m=await this.#fe(),y=this.#oe(m,n),g=y.change.op==="upsert"?y.change.row.columns.owner:null;if(f.code===0)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:g},observation:y}};let w=y.change.op==="upsert"?this.#J(y.change.row.columns.owner??""):null;if(w===c)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:g},observation:y}};if((w??null)!==d)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:g},observation:y}};return this.#t.log.error(`hightea-source: assign ${i} on ${this.sourceId} exited ${f.code??"on a signal"}: ${bt(f.stderr)}`),{...t,op:"assign",outcome:"unknown",code:"SOURCE_UNAVAILABLE"}}#oe(e,t){let r=e.byAddress.get(t);if(r===void 0)return{position:{epoch:e.epoch,ordinal:String(e.base)},change:{op:"delete",address:t}};return{position:{epoch:e.epoch,ordinal:String(r.at)},change:{op:"upsert",row:r.row}}}async#fe(){let e=this.#o;for(;;){let t=this.#n;if(t===void 0)return this.#I();if(this.#l>e)return t;await t.catch(()=>{return})}}async#xe(){return this.#r??await this.#I()}#K(){if(this.#p.signal.aborted||this.#h)return;if(this.#u!==void 0)return this.#u;if(this.#i()<this.#m)return;let e=this.#t.openServe??Uf,t;try{t=e([...this.#t.config.yrd,"issues","list-page-serve","--project-root",this.#t.config.projectRoot],this.#p.signal)}catch(r){this.#se(void 0,{code:null,stderr:Y(r)});return}return this.#u=t,t.exited.then((r)=>this.#se(t,r),(r)=>this.#se(t,{code:null,stderr:Y(r)})),t}#se(e,t){if(e!==void 0&&this.#u!==e)return;if(this.#u===e)this.#u=void 0;if(this.#p.signal.aborted)return;this.#a++;let r=Math.min(this.#z*2**Math.min(this.#a-1,5),60000);if(this.#m=this.#i()+r,mw(t.stderr)){this.#h=!0,this.#t.log.error(`hightea-source: ${this.sourceId} declares no list-page-serve (${xt(t)}); reading with list-page, one process per read`);return}if(this.#w=!0,this.#_++,this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${xt(t)} (restart ${this.#_}, attempt ${this.#a}, in ${Math.round(r/1000)} s)`),this.#d!==void 0)return;this.#d=setTimeout(()=>{if(this.#d=void 0,this.#p.signal.aborted||this.#K()===void 0)return;this.#t.log.info?.(`hightea-source: the km reader of ${this.sourceId} is back; reading it once to catch up`),this.#I().catch((n)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after the km reader returned failed: ${Y(n)}`))},r)}async#be(e){let t=this.#K();if(t!==void 0)try{let{progress:n,...o}=e,s=await t.ask(o,this.#t.childTimeoutMs??120000);if("refusal"in s){let{code:a,message:c,hint:d}=s.refusal;return{ok:!1,stderr:`page-serve: ${a}: ${c}${d===void 0?"":` (${d})`}`}}this.#a=0,this.#y=!1,this.#w=!1;let i=this.#t.pageServeCeilingBytes??Q_;if(s.rss!==void 0&&s.rss>i)this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, rss ${qf(s.rss)} MiB is above its ${qf(i)} MiB ceiling (restart ${this.#_+1})`),t.close();if(!("pages"in s))throw new pe("page-serve-frame-malformed","the reader answered a progress frame where the page was asked for");return{ok:!0,stdout:gw(s.pages),from:"reader"}}catch(n){if(!(n instanceof pe))throw n;this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${Y(n)}; this read uses list-page`)}if(!this.#h&&!this.#y)this.#y=!0,this.#t.log.info?.(`hightea-source: ${this.sourceId} reads with list-page while its km reader restarts; one process per read`);let r=await this.#Y(["issues","list-page",JSON.stringify(e)]);return r.code===0?{ok:!0,stdout:r.stdout,from:"one-shot"}:{ok:!1,stderr:r.stderr}}#Ee(e){try{let t=JSON.parse(e);if(t.source==="item-history")return;if(typeof t.seq==="number"&&Number.isSafeInteger(t.seq))this.#S=Math.max(this.#S??0,t.seq)}catch{if(this.#D)return;this.#D=!0,this.#t.log.error(`hightea-source: ${this.sourceId}: km's change feed wrote a line that is not a journal record, so its changes carry no seq; freshness is checked against each answer's head only`)}}#he(e){let t=this.#S;if(this.#v=void 0,t===void 0)return;if(typeof e==="number"&&e<t)this.#t.log.error(`hightea-source: ${this.sourceId} read whole at head ${String(e)}, below the change notice at ${t}; that notice is not about this vault's journal`);this.#S=void 0}#I(e=!1,t=!1,r=!1){if(this.#n!==void 0){if(this.#T=!0,t)this.#C=!0;return this.#n}if(this.#g!==void 0)clearTimeout(this.#g),this.#g=void 0;this.#T=!1,this.#R=void 0,this.#$=void 0;let n=this.#i(),o=this.#Ce(e,t,r).then((s)=>(this.#re=0,s),(s)=>{throw this.#Ie(),s}).finally(()=>{if(this.#n=void 0,this.#G=this.#i(),this.#te=this.#G-n,this.#ie(),this.#T&&!this.#p.signal.aborted)this.#T=!1,this.hint()});return this.#n=o,this.#l=this.#o,o}#Ie(){if(this.#p.signal.aborted||this.#g!==void 0)return;this.#re++;let e=Math.min(this.#z*2**Math.min(this.#re-1,5),60000);this.#t.log.info?.(`hightea-source: ${this.sourceId} will read again in ${Math.round(e/1000)} s after a failed read`),this.#g=setTimeout(()=>{this.#g=void 0,this.#I().catch((t)=>this.#t.log.error(`hightea-source: retrying ${this.sourceId} after a failed read failed: ${Y(t)}`))},e)}#ke(){if(this.#L!==void 0)return this.#L;let e=[...this.#U].sort((r,n)=>r-n),t=e.length===0?0:e[Math.floor(e.length/2)];return Math.max(this.#P,10*t)}#ie(){if(this.#p.signal.aborted||!this.#e.watching||this.#A!==void 0)return;let e=this.#ke();if(!(e>0))return;let t=Math.max(this.#G,this.#H),r=Math.max(0,e-(this.#i()-t));this.#A=setTimeout(()=>{if(this.#A=void 0,this.#p.signal.aborted||!this.#e.watching)return;if(this.#n!==void 0){this.#ie();return}this.#I(!0,!0,!0).catch((n)=>this.#t.log.error(`hightea-source: the watcher read of ${this.sourceId} failed: ${Y(n)}`))},r)}#pe(){if(this.#A===void 0)return;clearTimeout(this.#A),this.#A=void 0}#Re(){if(this.#p.signal.aborted||this.#g!==void 0)return;this.#g=setTimeout(()=>{if(this.#g=void 0,this.#n!==void 0){this.#T=!0;return}this.#I(!0).catch((e)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a trailing notice failed: ${Y(e)}`))},this.#Q)}async#Ce(e,t,r=!1){for(let n=1;;n++){let o=`${this.#e.epoch}.${++this.#o}`;try{let s=this.#c;if(s!==void 0){let i=await this.#$e(o,s,e,t,r);if(i!==void 0)return i}return await this.#Oe(o)}catch(s){if(n>=Zf||!(s instanceof cr)||!Bf(s.stderr))throw s;this.#t.log.error(`hightea-source: read of ${this.sourceId} restarted after the vault moved (${n}/${Zf}): ${bt(s.stderr)}`),await this.#De()}}}async#Oe(e){let t=await this.#Te(e);if(t!==void 0)return t;return await this.#Ae(e)}async#Te(e){if(this.#f===!1)return;let t={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,traverse:!0,progress:!0},r=await this.#Y(["issues","list-page",JSON.stringify(t)]);if(r.code!==0){if(!pw(r.stderr))throw new cr(r.stderr);this.#f=!1,this.#t.log.error(`hightea-source: ${this.sourceId} has no one-process traversal (${bt(r.stderr)}); checking a single-page native snapshot; larger snapshots require traversal`);return}if(this.#f===void 0)this.#f=!0;let n=uw(r.stdout,e);if(n.activityUnreadRows>0)this.#t.log.error(`hightea-source: ${this.sourceId}: activity read unavailable for ${n.activityUnreadRows} of ${n.rows.length} rows; progress remains unknown; check the declared activity command`);let o=new Map;this.#ce(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#x={value:n.progress,at:s};return this.#V(o,n.progress,s),this.#we(n.head),this.#he(n.head),this.#W(e,ps(o),o)}async#Ae(e){let t={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,progress:!0},r=await this.#Y(["issues","list-page",JSON.stringify(t)]);if(r.code!==0)throw new cr(r.stderr);let n=ms(r.stdout);if(!n.complete){if(this.#f===!1)this.#f=void 0,this.#t.log.info?.(`hightea-source: ${this.sourceId}: a paged whole read cannot serve this multi-page vault; asking the one-process traversal again`);throw Error("progress refresh needs one-process traversal for a multipage native snapshot")}let o=new Map;this.#ce(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#x={value:n.progress,at:s};return this.#V(o,n.progress,s),this.#we(n.head),this.#he(n.head),this.#W(e,ps(o),o)}#ae(e,t){this.#t.log.error(`hightea-source: row ${e} omitted: ${t}`)}#ce(e,t){for(let r of t){let n=this.#je(r),o=St.safeParse(n);if(!o.success){let s=o.error.issues.map((i)=>{let a=(i.path[0]==="columns"?i.path.slice(1):i.path).join("."),c=i.path.reduce((d,u)=>typeof d==="object"&&d!==null?Reflect.get(d,u):void 0,n);return i.code==="too_big"&&typeof c==="string"?`${a} is ${c.length} chars, cap ${i.maximum}`:`${a}: ${i.message}`});this.#ae(r.id,s.join("; "));continue}if(te(n)>st)throw new Sn(n.address);e.set(n.address,{key:r.path,row:n})}}async#$e(e,t,r,n,o){let s=this.#r;if(s===void 0)return;let i={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,changedSince:t,progress:!0},a=this.#i(),c=await this.#be(i),d=this.#i();if(!c.ok){let x=Bf(c.stderr),I=/--page changedSince \d+ needs the vault's journal at [^\n]+, which no daemon has written; do a full read(?:\r?\n|$)/u.test(c.stderr);if(!x&&!hw(c.stderr)&&!I)throw new cr(c.stderr);return this.#t.log.info?.(`hightea-source: ${this.sourceId} could not read after ${t} (${bt(c.stderr)}); reading it whole`),x?this.#ge():this.#me(r)}let u=ms(c.stdout);if(!u.complete)return this.#t.log.info?.(`hightea-source: ${this.sourceId} answered a bounded change list (${u.reason??"no reason named"}); reading it whole`),this.#me(r);if(typeof u.head!=="number"||u.head<t)throw Error(`list-page answered changedSince ${t} at head ${String(u.head)}`);let l=this.#S;if(l!==void 0&&u.head<l){let x=this.#v??(this.#v=this.#i());if(this.#i()-x>=(this.#t.noticePatienceMs??ew))this.#t.log.error(`hightea-source: ${this.sourceId} stayed below the change notice at ${l} for ${Math.round(this.#i()-x)} ms at head ${String(u.head)}; that notice is not about this vault's journal`),this.#S=void 0,this.#v=void 0;else this.#t.log.info?.(`hightea-source: ${this.sourceId}: answer head ${String(u.head)} trails the change notice at ${l}; serving the delta and reading again`),this.#Re()}else if(l!==void 0)this.#S=void 0,this.#v=void 0;let p=new Map(s.byAddress),f=new Set(u.rows.map((x)=>this.#ue(x))),m=new Map([...s.byAddress].map(([x,I])=>[I.key,x]));for(let x of f)p.delete(x);if(this.#ce(p,u.rows),this.#Ze(s,p,f,m,u.rows,u.removed))return this.#t.log.info?.(`hightea-source: ${this.sourceId} saw an ancestor project or path change after ${t}; reading it whole`),this.#ge();for(let x of u.removed){let I=m.get(x);if(I!==void 0&&!f.has(I))p.delete(I)}if(c.from==="reader"){let x=await this.#Ne(o);if(x!==void 0)this.#V(p,x.value,x.at)}else{let x=this.#i();if(u.progress!==void 0)this.#x={value:u.progress,at:x};this.#V(p,u.progress,x)}this.#c=u.head,this.#q=!1;let y=this.#i(),g=ps(p),w=this.#i(),b=this.#W(e,g,p),v=this.#i();if(n||v-a>=500){let x=o?"watch":n?"client":"change";this.#t.log.info?.(`hightea-source: ${this.sourceId} ${x} delta read ${Math.round(v-a)} ms: yrd ${Math.round(d-a)} ms, collect ${Math.round(y-d)} ms, revision ${Math.round(w-y)} ms, diff ${Math.round(v-w)} ms`)}return b}#me(e){this.#q=e;return}#ge(){this.#q=!1;return}async#Pe(){let e=this.#K();if(e===void 0)throw Error("progress unavailable: list-page-serve not running");let t=await e.ask({progress:!0},this.#t.childTimeoutMs??120000);if("refusal"in t)throw Error(`progress unavailable: ${t.refusal.code}: ${t.refusal.message}`);if(!("progress"in t))throw Error("progress unavailable: the reader answered a page where the frame was asked for");let r=t.progress;if(r!==void 0&&Buffer.byteLength(JSON.stringify(r))>vn)throw Error("progress refresh output exceeded its byte budget");return r}async#Ne(e){let t=this.#x;if(!(t===void 0||this.#i()-t.at>=this.#ee))return t;if(t===void 0||e){await this.#ye();let n=this.#x;if(n===void 0)throw Error("progress refresh completed without a projection");return n}return this.#ye().catch((n)=>this.#t.log.error(`hightea-source: ${this.sourceId} activity projection refresh failed: ${Y(n)}`)),t}#ze(){let e=this.#j;if(e===void 0||this.#M===void 0)return;if(this.#b<nw&&this.#i()-e<ow)return;return{since:new Date(e).toISOString(),reason:this.#M}}#ye(){if(this.#k!==void 0)return this.#C=!0,this.#k;let e=(async()=>{do{this.#C=!1;let t=this.#i();try{let r=await this.#Pe();if(this.#U.push(this.#i()-t),this.#U.length>sw)this.#U.shift();this.#_e(r),this.#x={value:r,at:this.#i()},this.#b=0,this.#j=void 0,this.#M=void 0}catch(r){throw this.#b++,this.#j??=this.#i(),this.#M=Y(r),r}}while(this.#C&&!this.#p.signal.aborted)})().finally(()=>{this.#k=void 0});return this.#k=e,e}#_e(e){let t=e;if(typeof t!=="object"||t===null||!Array.isArray(t.qualifying)||t.complete!==!0)throw Error("progress refresh requires a complete terminal qualifying projection, not an ordinary page");let{source:r,default:n}=t;if(!(r==="ok"||r==="undeclared"||r==="unreadable")||n!==(r==="unreadable"?null:!1))throw Error("progress refresh has an invalid progress.source/progress.default pair");let o=new Map,s=new Map;for(let i of t.qualifying){if(typeof i!=="object"||i===null)throw Error("progress refresh carries a malformed qualifying entry");let a=i;if(typeof a.id!=="string"||a.id.length===0||typeof a.reason!=="string"||a.reason.length===0||a.owner!==void 0&&(typeof a.owner!=="string"||a.owner.length===0))throw Error("progress refresh qualifying entry needs identity, reason and an optional nonempty owner");if(a.owner===void 0){if(o.has(a.id))throw Error("progress refresh repeats a hold identity");o.set(a.id,a.reason)}else{let c=s.get(a.id)??new Map;if(c.has(a.owner))throw Error("progress refresh repeats an identity/owner");c.set(a.owner,a.reason),s.set(a.id,c)}}return{source:r,idle:n,holds:o,actors:s}}#V(e,t,r){this.#Me(e,this.#_e(t)),this.#O=r}#Me(e,t){let r=0;for(let[n,o]of e){let s=o.row,i=s.extra,a=wn(o.key),c=a===null?`path:${o.key.endsWith(".md")?o.key.slice(0,-3):o.key}`:`bead:${a}`,d=this.#J(s.columns.owner??"")??"",u=t.holds.get(c)??(d===""?void 0:t.actors.get(c)?.get(d)),l=u===void 0?t.idle:!0;if(l===null)r++;if(i.in_progress===l&&i.in_progress_reason===(u??null))continue;let p={id:i.id,title:s.columns.title,status:s.columns.state,owner:d,project:s.columns.project,in_progress:l,in_progress_reason:u??null,updated_at:s.columns.updatedAt,closed_at:i.closed_at??null},f={...s,version:Hf(p),extra:{...i,in_progress:l,in_progress_reason:u??null}},m=te(f);if(m>st){e.delete(n),this.#ae(i.id,`the row is ${m} bytes with its progress, over the ${st}-byte row cap`);continue}e.set(n,{key:o.key,row:f})}if(t.source==="unreadable")this.#t.log.error(`hightea-source: ${this.sourceId}: activity read unavailable; ${r} of ${e.size} materialized rows have unknown progress`)}#we(e){if(typeof e==="number"){this.#c=e;return}if(this.#c=void 0,this.#F)return;this.#F=!0,this.#t.log.info?.(`hightea-source: ${this.sourceId} names no journal to continue from; every read stays whole`)}async#De(){if(this.#p.signal.aborted)return;await new Promise((e)=>{let t=()=>{clearTimeout(r),this.#p.signal.removeEventListener("abort",t),e()},r=setTimeout(t,this.#z);this.#p.signal.addEventListener("abort",t,{once:!0})})}#W(e,t,r){let n=this.#r,o=new Map,s=[...new Set([...r.keys(),...n?.byAddress.keys()??[]])].sort(),i=[];for(let a of s){let c=r.get(a),d=n?.byAddress.get(a);if(c===void 0){i.push({position:this.#e.next(),change:{op:"delete",address:a}});continue}if(n!==void 0&&(d===void 0||d.row.version!==c.row.version||!dw(d.row,c.row))){let u=this.#e.next();i.push({position:u,change:{op:"upsert",row:c.row}}),o.set(a,{key:c.key,row:c.row,at:BigInt(u.ordinal)})}else o.set(a,{key:c.key,row:c.row,at:d?.at??0n})}if(n===void 0&&o.size>0){let a=o.get(s[0]),c=this.#e.next();i.push({position:c,change:{op:"upsert",row:a.row}}),o.set(a.row.address,{...a,at:BigInt(c.ordinal)})}return this.#Le(e,t,i,o)}#Le(e,t,r,n){let o={generation:e,snapshot:t,base:this.#e.ordinal,epoch:this.#e.epoch,rows:[...n.values()],byAddress:n,at:this.#i()};this.#r=o,this.#s.set(e,o);for(let[s,i]of this.#s)if(this.#s.size>J_||this.#i()-i.at>Y_)this.#s.delete(s);if(this.#e.enqueue(r),r.length>0)this.#t.onRecords?.(r);return o}#ue(e){return`issue:${this.sourceId}/${wn(e.path)??e.id}`}#Ue(e){if(e.container===null||e.containerSource===null||e.containerSource==="beads-root")return null;let t=e.container.endsWith(".md")?e.container:`${e.container}.md`;return`issue:${this.sourceId}/${wn(t)??e.container}`}#Ze(e,t,r,n,o,s){let i=new Set,a=new Set;for(let c of o){let d=this.#ue(c),u=e.byAddress.get(d),l=t.get(d),p=u!==void 0&&l!==void 0&&u.row.columns.project!==l.row.columns.project,f=u!==void 0&&l!==void 0&&u.key!==l.key,m=u===void 0&&l!==void 0&&l.row.columns.project===d;if(!p&&!f&&!m)continue;if(i.add(d),u?.row.columns.project!==void 0&&u.row.columns.project!==null)i.add(u.row.columns.project);if(u!==void 0)for(let y of hs(u.key))a.add(y);if(l!==void 0)for(let y of hs(l.key))a.add(y)}for(let c of s){for(let u of hs(c))a.add(u);let d=n.get(c);if(d!==void 0){let u=e.byAddress.get(d);if(u!==void 0&&u.row.columns.project===d)i.add(d)}}if(i.size===0&&a.size===0)return!1;for(let[c,d]of e.byAddress){if(r.has(c))continue;if(d.row.columns.project!==null&&i.has(d.row.columns.project))return!0;let u=d.key.startsWith("./")?d.key.slice(2):d.key;for(let l of a)if(u.startsWith(l))return!0}return!1}#je(e){let t=this.#ue(e),r=e.owner.trim(),n=e.status.trim()===""?"none":e.status.trim(),o=this.#Ue(e),s=Hf({id:e.id,title:e.title,status:n,owner:r,project:o,in_progress:e.in_progress,in_progress_reason:e.in_progress_reason,updated_at:e.updated_at,closed_at:e.closed_at});return{address:t,version:s,scope:"all",columns:{title:e.title,state:n,owner:r===""?null:this.#de.get(r)??`km:${r}`,parent:null,project:o,labels:[],url:null,updatedAt:e.updated_at},extra:{path:e.path,id:e.id,in_progress:e.in_progress,in_progress_reason:e.in_progress_reason,closed_at:e.closed_at}}}#J(e){if(e.startsWith("km:"))return e.slice(3);return this.#t.config.members[e]}#Fe(e){let t=`issue:${this.sourceId}/`;if(!e.startsWith(t)||e.length<=t.length)return;let r=this.#r?.byAddress.get(e)?.key;if(r!==void 0)return r;let n=e.slice(t.length);return wn(n)===null?n:void 0}async#Y(e,t){let{config:r}=this.#t;try{return await this.#E([...r.yrd,...e,"--project-root",r.projectRoot],{timeoutMs:this.#t.childTimeoutMs??120000,signal:this.#p.signal,...t===void 0?{}:{env:t}})}catch(n){throw Error(`the yrd command ${r.yrd[0]??"(none)"} could not run: ${Y(n)}`)}}async#He(){let e=this.#t.follow??ww,t=this.#p.signal;while(!t.aborted){let r=String(this.#i());try{let n=await e([...this.#t.config.feed,"--since",r],{signal:t,onLine:(o)=>this.hint(o)});if(t.aborted)return;this.#t.log.error(`hightea-source: km's change feed for ${this.sourceId} ended (${n.code??"signal"}): ${bt(n.stderr)}`)}catch(n){if(t.aborted)return;this.#t.log.error(`hightea-source: km's change feed for ${this.sourceId} could not run: ${Y(n)}`)}this.hint(),await new Promise((n)=>{let o=setTimeout(n,X_);t.addEventListener("abort",()=>{clearTimeout(o),n()},{once:!0})})}}}var iw=new Set(["self","ancestor","folder-note","beads-root"]);function hs(e){let t=e.startsWith("./")?e.slice(2):e,r=t.endsWith(".md")?t.slice(0,-3):t;if(r==="")return[];let n=[`${r}/`],o=r.lastIndexOf("/");if(o>0){let s=r.slice(0,o),i=r.slice(o+1),a=i.toLowerCase(),c=s.slice(s.lastIndexOf("/")+1);if(a==="index"||a==="readme"||i===c)n.push(`${s}/`)}return n}var aw=/^(\d{4,})-.+\.md$/u,cw=/^\d{4}-\d{2}-\d{2}/u;function wn(e){let t=e.startsWith("./")?e.slice(2):e;if(!t.startsWith("@"))return null;let r=t.lastIndexOf("/");if(r<0)return null;let n=t.slice(r+1);if(cw.test(n))return null;let o=aw.exec(n),s=o===null?Number.NaN:Number.parseInt(o[1],10);return Number.isInteger(s)&&s>=0?s:null}function Ff(e,t){let r=e[t];if(r===void 0||r===null||r==="")return null;if(typeof r!=="string"||!Number.isFinite(Date.parse(r)))throw Error(`list-page answered ${t} outside an ISO instant`);return new Date(r).toISOString()}function Hf(e){return Gf("sha256").update(`${e.id}\x00${e.title}\x00${e.status}\x00${e.owner}\x00${e.project??""}\x00${String(e.in_progress)}\x00${e.in_progress_reason??""}\x00${e.updated_at??""}\x00${e.closed_at??""}`).digest("hex").slice(0,16)}function ms(e){if(Buffer.byteLength(e)>vn)throw Error("progress refresh output exceeded its byte budget");let t=JSON.parse(e);if(t.verb!=="list-page"||typeof t.result!=="object"||t.result===null)throw Error("list-page answered outside km's page shape");let r=t.result;if(typeof r.snapshot!=="string"||!Array.isArray(r.rows)||typeof r.complete!=="boolean"||!("next"in r)||r.next!==null&&typeof r.next!=="string")throw Error("list-page answered outside km's page shape");let n=(c)=>typeof c==="string",o=r.rows.map((c)=>{let d=c,u=typeof d.row==="object"&&d.row!==null?d.row:d;if(!n(u.id)||!n(u.title)||!n(u.status)||!n(u.owner))throw Error("list-page answered a row outside the declared columns (id, title, status, owner)");if("content"in u||"description"in u)throw Error("list-page answered a row carrying the issue body");let l=u.in_progress;if(l!==void 0&&l!==null&&typeof l!=="boolean")throw Error("list-page answered in_progress outside a boolean or null");let p=u.in_progress_reason;if(p!==void 0&&p!==null&&typeof p!=="string")throw Error("list-page answered in_progress_reason outside a string or null");if(l===!0&&typeof p!=="string")throw Error("list-page answered in_progress true without the environment holding it");let{container:f,containerSource:m}=u,y=null,g=null;if(f!==void 0||m!==void 0){if(typeof f!=="string"||f.trim()===""||typeof m!=="string"||!iw.has(m))throw Error("list-page answered malformed container/containerSource");y=f,g=m}let w={id:u.id,title:u.title,status:u.status,owner:u.owner,container:y,containerSource:g,in_progress:l??null,in_progress_reason:p??null,updated_at:Ff(u,"updated_at"),closed_at:Ff(u,"closed_at")},b=n(d.path)?d.path:w.id;return{...w,path:b}}),s=r.head;if(s!==void 0&&s!==null&&!(typeof s==="number"&&Number.isSafeInteger(s)&&s>=0))throw Error("list-page named a head that is not a journal seq");let i=r.removed;if(i!==void 0&&(!Array.isArray(i)||!i.every((c)=>typeof c==="string")))throw Error("list-page named removed rows outside km's shape");let a=r.reason;if(a!==void 0&&typeof a!=="string")throw Error("list-page named a reason that is not text");return{progress:r.progress,snapshot:r.snapshot,rows:o,next:r.next,complete:r.complete,head:s,removed:i??[],reason:a}}function uw(e,t){if(Buffer.byteLength(e)>vn)throw Error("progress refresh output exceeded its byte budget");let r=e.split(`
71
- `);while(r.length>0&&r[r.length-1].trim()==="")r.pop();if(r.length===0)throw Error("list-page traversal answered no frame");let n,o=[],s,i;if(r.forEach((a)=>{if(s!==void 0)throw Error("list-page traversal answered a frame after its terminal one");let c=JSON.parse(a);if(typeof c!=="object"||c===null||Array.isArray(c))throw Error("list-page traversal answered a frame outside km's page shape");let d=c,u=d.verb==="list-page"&&typeof d.result==="object"&&d.result!==null?d.result:d;if(typeof u.generation!=="string"||u.generation!==t)throw Error("list-page traversal answered a frame for another generation");if(typeof u.population!=="number"||!Number.isSafeInteger(u.population)||u.population<0)throw Error("list-page traversal answered a frame with no population count");if(u.next!==null&&typeof u.next!=="string")throw Error("list-page traversal answered a frame with a malformed next token");let l=ms(JSON.stringify({verb:"list-page",result:u}));if(n===void 0)n={snapshot:l.snapshot,head:l.head,population:u.population};else{if(l.snapshot!==n.snapshot)throw Error("list-page traversal answered frames of two revisions");if(u.population!==n.population)throw Error("list-page traversal answered frames of two populations");if(l.head!==n.head)throw Error("list-page traversal answered frames of two journal heads")}if(o.push(...l.rows),u.complete===!0){if(u.next!==null)throw Error("list-page traversal completed a frame that still names a next page");let p=u.meta,f=typeof p==="object"&&p!==null?p.activityUnreadRows:void 0;if(typeof f!=="number"||!Number.isSafeInteger(f)||f<0||f>u.population)throw Error(`list-page traversal terminal meta.activityUnreadRows must be an integer from 0 through ${u.population}; got ${String(f)}`);s=f,i=u.progress}else if(u.next===null)throw Error("list-page traversal left a frame incomplete with no next page")}),s===void 0)throw Error("list-page traversal never completed");if(n===void 0)throw Error("list-page traversal answered no frame");if(o.length!==n.population)throw Error(`list-page traversal answered ${o.length} rows of ${n.population}`);return{snapshot:n.snapshot,head:n.head,rows:o,activityUnreadRows:s,progress:i}}function ps(e){let t=Gf("sha256");for(let r of[...e.keys()].sort())t.update(`${r}\x00${e.get(r).row.version}
72
- `);return t.digest("hex")}function dw(e,t){return JSON.stringify(e.columns)===JSON.stringify(t.columns)}function lw(e,t){return Buffer.from(JSON.stringify([e,t])).toString("base64url")}function fw(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(Array.isArray(t)&&typeof t[0]==="string"&&Number.isSafeInteger(t[1])&&t[1]>=0)return{generation:t[0],offset:t[1]}}catch{}return}function bt(e){let t=/\b(yrd-[a-z-]+|page-source-[a-z-]+|page-serve-[a-z-]+|[A-Z][A-Z_]{3,})\b/u.exec(e)?.[1];if(t!==void 0)return t;let r=e.split(/\r?\n/u).map((n)=>n.trim()).find((n)=>n.length>0);return r===void 0?"no output":r.slice(0,140)}function hw(e){return/\bpage-source-cursor-unservable\b|cursor[^\n]*(?:do a full read|retention|is older than the journal's retained start|is ahead of this store's watermark|is below watermark)/u.test(e)}function Bf(e){return/\bpage-source-(?:moved|not-reconciled)\b/u.test(e)}function pw(e){return/\byrd-issues-(?:provider-not-json|verb-unsupported)\b/u.test(e)}function mw(e){return/\blist-page-serve is not declared\b/u.test(e)||/\byrd-issues-verb-unsupported\b/u.test(e)}function gw(e){return e.map((t)=>JSON.stringify({verb:"list-page",result:t})).join(`
70
+ hightea-page-serve: ${v.message}`});let w=new Promise((v)=>{o.on("close",(x,I)=>{wn(o,"SIGKILL"),i={code:I===null?x:null,stderr:s},p(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`));for(let R of c.splice(0)){if(R.timer!==void 0)clearTimeout(R.timer);R.reject(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`))}u(i),v()})}),b=async()=>{if(i!==void 0)return;o.stdin.end(),wn(o,"SIGTERM");let v=setTimeout(()=>wn(o,"SIGKILL"),K_);await w,clearTimeout(v)};return t.addEventListener("abort",()=>{b()},{once:!0}),{ask(v,x){if(i!==void 0)return Promise.reject(new pe("page-serve-reader-exited",`the reader is gone (${xt(i)})`));if(a!==void 0){if(Date.now()>=a.deadline){let re=`the reader did not answer seq ${a.seq} by its ${a.deadline-a.askedAt} ms deadline, and the slot was still held`;return y("page-serve-timeout",re),Promise.reject(new pe("page-serve-timeout",re))}if(c.length>=V_)return Promise.reject(new pe("page-serve-busy",`a page request is already outstanding and ${c.length} more are waiting`));let A=Math.min(x,W_),q={request:v,timeoutMs:x,waitMs:A,resolve:()=>{return},reject:()=>{return},timer:void 0},ke=new Promise((re,Ne)=>{q.resolve=re,q.reject=Ne});return q.timer=setTimeout(()=>{let re=c.indexOf(q);if(re<0)return;c.splice(re,1),q.reject(new pe("page-serve-busy",`a page request waited ${A} ms for the one slot and seq ${a===void 0?"none":a.seq} is still unanswered`))},A),c.push(q),ke}let I=()=>{return},R=()=>{return},E=new Promise((A,q)=>{I=A,R=q});return m(v,x,I,R),E},exited:l,close:b}};var xn=16777216,X_=8,Q_=900000,fs=1000,Ff=3,ew=5000,tw=536870912,rw=30000,nw=2000,ow=2000,sw=3,iw=300000,aw=20;function Hf(e,t){if(!(Number.isFinite(t)&&t>=0))throw Error(`${e} must be a finite number of milliseconds, 0 or more, not ${String(t)}`);return t}class vn extends Error{item;constructor(e){super(`ITEM_TOO_LARGE: ${e}`);this.item=e}}class cr extends Error{stderr;constructor(e){super(`list refused: ${bt(e)}`);this.stderr=e}}class gs{sourceId;#e;#o=0;#r;#s=new Map;#n;#d=0;#c;#l;#u;#f=!1;#a=0;#g=-1/0;#h;#y=!1;#w=!1;#v=0;#S;#m;#x;#k;#R=!1;#O;#b=0;#U;#P;#N=!1;#Z=!1;#T=!1;#C;#A;#_;#j=!1;#E;#F;#H;#z=[];#B=-1/0;#p=new AbortController;#M;#t;#D;#X;#Q;#i;#le;#L;#ee;#fe;#$;#te;#q=!1;#G=-1/0;#re=0;#ne=0;#oe=new Map;constructor(e){if(this.#t=e,this.sourceId=e.config.sourceId,this.#D=e.run??ys,this.#X=e.coalesceMs??2000,this.#Q=e.hintCoalesceMs??Math.min(this.#X,100),this.#L=e.readDuty??e.config.readDuty??0.1,!(this.#L>0&&this.#L<=1))throw Error(`readDuty must be in (0, 1], not ${this.#L}`);if(this.#ee=Hf("minIncrementalReadGapMs",e.config.minIncrementalReadGapMs),this.#fe=Hf("minFullReadGapMs",e.config.minFullReadGapMs),this.#$=e.readRetryMs??2000,!(Number.isFinite(this.#$)&&this.#$>=0))throw Error(`readRetryMs must be a finite number of milliseconds, 0 or more, not ${this.#$}`);let t=e.progressCeilingMs??nw;if(!(Number.isFinite(t)&&t>=0))throw Error(`progressCeilingMs must be a finite number of milliseconds, 0 or more, not ${t}`);this.#te=t;let r=e.watchFloorMs??ow;if(!(Number.isFinite(r)&&r>=0))throw Error(`watchFloorMs must be a finite number of milliseconds, 0 or more, not ${String(r)}`);if(this.#F=r,e.watchRefreshMs!==void 0&&!(Number.isFinite(e.watchRefreshMs)&&e.watchRefreshMs>=0))throw Error(`watchRefreshMs must be a finite number of milliseconds, 0 or more, not ${String(e.watchRefreshMs)}`);this.#H=e.watchRefreshMs,this.#i=e.now??Date.now,this.#le=new Map(Object.entries(e.config.members).map(([n,o])=>[o,n])),this.#e=new ar({sourceId:e.config.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(n)=>e.push(n),log:e.log,coalesceMs:this.#X,now:this.#i,onOmit:(n,o)=>this.#ce(n,o),onOverflow:()=>{this.#s.clear();let n=this.#r;if(n===void 0){e.log.error(`hightea-source: ${e.config.sourceId} overflowed before its first read; reading for the new epoch`),this.#I().catch((s)=>e.log.error(`hightea-source: reading ${e.config.sourceId} after an overflow failed: ${J(s)}`));return}this.#r=void 0;let o=new Map(n.rows.map((s)=>[s.row.address,{key:s.key,row:s.row}]));this.#W(`${this.#e.epoch}.${++this.#o}`,n.snapshot,o)}})}get epoch(){return this.#e.epoch}start(){this.#K(),this.#I().catch((e)=>this.#t.log.error(`hightea-source: the first read of ${this.sourceId} failed: ${J(e)}`)),this.#M=this.#Be()}async stop(){if(this.#p.abort(),this.#e.stop(),this.#_!==void 0)clearTimeout(this.#_);if(this.#me(),this.#h!==void 0)clearTimeout(this.#h);await this.#M,await this.#n?.catch(()=>{return}),await this.#u?.close().catch((e)=>this.#t.log.error(`hightea-source: the km reader of ${this.sourceId} did not close: ${J(e)}`))}hint(e){if(e!==void 0){this.#Ie(e);let i=Sw(e);if(i!==void 0&&(this.#C===void 0||i.at<this.#C))this.#C=i.at,this.#A=i.source}if(this.#p.signal.aborted)return;if(this.#n!==void 0||this.#_!==void 0){this.#T=!0;return}let t=this.#c!==void 0&&!this.#q,r=t?this.#ee:this.#fe,n=this.#G+Math.max(this.#re*(1/this.#L-1),r)-this.#i(),o=Math.max(this.#Q,n),s=this.#C===void 0?void 0:this.#i()-this.#C;this.#t.log.info?.(`hightea-source: ${this.sourceId} change hint: last read ${Math.round(this.#re)} ms at readDuty ${this.#L}, ${t?"incremental":"full"} floor ${Math.round(r)} ms, progress ceiling ${Math.round(this.#te)} ms, hint window ${Math.round(this.#Q)} ms, next read in ${Math.round(o)} ms, change age ${s===void 0?"unavailable":`${Math.round(s)} ms${this.#A===void 0?"":` from ${this.#A}`}`}`),this.#_=setTimeout(()=>{this.#_=void 0,this.#j=!0,this.#I(t).catch((i)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${J(i)}`))},o)}async handle(e){let t={workspaceId:e.workspaceId,sourceId:e.sourceId,hostId:e.hostId},r=(n,o="refused")=>({...t,op:e.op,outcome:o,code:n});if(e.sourceId!==this.sourceId)return r("SOURCE_UNBOUND");if(!this.#t.config.members[e.caller.memberId])return r("AGENT_NOT_MAPPED");try{switch(e.op){case"watch":if(this.#e.watch(e.args.on),e.args.on)this.#ae();else this.#me();return{...t,op:"watch",outcome:"applied",body:{on:this.#e.watching}};case"list":return{...t,op:"list",outcome:"applied",...this.#w?{code:"SOURCE_READER_RESTARTING"}:{},body:await this.#ve(e.args,t)};case"read":{let n=await this.#be();return{...t,op:"read",outcome:"applied",body:{observation:this.#se(n,e.args.address)}}}case"assign":{let n=this.#oe.get(e.args.intentId);if(n!==void 0)return await n;let o=this.#xe(e,t).finally(()=>this.#oe.delete(e.args.intentId));return this.#oe.set(e.args.intentId,o),await o}}}catch(n){if(n instanceof vn)return{...t,op:e.op,outcome:"refused",code:"ITEM_TOO_LARGE",item:n.item};return this.#t.log.error(`hightea-source: ${e.op} on ${this.sourceId} failed: ${J(n)}`),r("SOURCE_UNAVAILABLE","unknown")}}async#ve(e,t){let r=e.page===void 0?void 0:pw(e.page),n=r===void 0?void 0:this.#s.get(r.generation),o=n??await this.#I(!1,!0);if(n===void 0)this.#B=this.#i();let s=n===void 0?0:r.offset,i=this.#Me(),a=[],c=(l,p)=>({generation:o.generation,snapshot:o.snapshot,base:{epoch:o.epoch,ordinal:String(o.base)},rows:p,next:l>=o.rows.length?null:hw(o.generation,l),complete:l>=o.rows.length,...this.#O===void 0?{}:{progressAsOf:new Date(this.#O).toISOString()},...i===void 0?{}:{progressStale:i}}),d=0,u=s;while(u<o.rows.length&&a.length<e.limit){let l=o.rows[u].row,p=te(l);if(te({...t,op:"list",outcome:"applied",body:c(u+1,[])})+d+p+a.length>ot){if(a.length===0)throw new vn(l.address);break}a.push(l),d+=p,u++}return c(u,a)}async#xe(e,t){return this.assign(e.args,t,e.caller.memberId)}async assign(e,t,r){let{address:n,ownerMemberId:o,expectedOwner:s,intentId:i,ifRevision:a}=e,c=this.#t.config.members[o],d=s===void 0||s===null?null:this.#J(s);if(c===void 0||d===void 0)return{...t,op:"assign",outcome:"refused",code:"AGENT_NOT_MAPPED"};let u=this.#He(n);if(u===void 0)return{...t,op:"assign",outcome:"refused",code:"INVALID_ADDRESS"};if(a!==void 0){let b=await this.#he(),v=this.#se(b,n),x=v.change.op==="upsert"?v.change.row.version:null;if(x!==a){let I=v.change.op==="upsert"?v.change.row.columns.owner??null:null;if((I===null?null:this.#J(I))!==c)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:I},revision:x,observation:v}}}}let l;if(this.#t.config.serviceIdentity)try{let b=this.#t.serviceIdentityEnvironment?.(this.sourceId);if(!b?.HAB_ID_TOKEN_FILE)throw Error("SERVICE_IDENTITY_UNAVAILABLE");l={HAB_ID_TOKEN_FILE:b.HAB_ID_TOKEN_FILE}}catch(b){if(!(b instanceof Error)||!/^SERVICE_IDENTITY_(?:NOT_GRANTED|UNAVAILABLE)(?::|$)/u.test(b.message))throw b;let v=b instanceof Error&&b.message.startsWith("SERVICE_IDENTITY_NOT_GRANTED")?"SERVICE_IDENTITY_NOT_GRANTED":"SERVICE_IDENTITY_UNAVAILABLE";return this.#t.log.error(`hightea-source: assign ${i} on ${this.sourceId}: ${v}`),{...t,op:"assign",outcome:"unknown",code:v}}let p={authority:`hightea:${t.workspaceId}`,subject:r},f=await this.#Y(["issues","assign",u,c,"--id",i,"--expected-owner",JSON.stringify(d),"--requested-by",JSON.stringify(p)],l),m=await this.#he(),y=this.#se(m,n),g=y.change.op==="upsert"?y.change.row.columns.owner:null;if(f.code===0)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:g},observation:y}};let w=y.change.op==="upsert"?this.#J(y.change.row.columns.owner??""):null;if(w===c)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:g},observation:y}};if((w??null)!==d)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:g},observation:y}};return this.#t.log.error(`hightea-source: assign ${i} on ${this.sourceId} exited ${f.code??"on a signal"}: ${bt(f.stderr)}`),{...t,op:"assign",outcome:"unknown",code:"SOURCE_UNAVAILABLE"}}#se(e,t){let r=e.byAddress.get(t);if(r===void 0)return{position:{epoch:e.epoch,ordinal:String(e.base)},change:{op:"delete",address:t}};return{position:{epoch:e.epoch,ordinal:String(r.at)},change:{op:"upsert",row:r.row}}}async#he(){let e=this.#o;for(;;){let t=this.#n;if(t===void 0)return this.#I();if(this.#d>e)return t;await t.catch(()=>{return})}}async#be(){return this.#r??await this.#I()}#K(){if(this.#p.signal.aborted||this.#f)return;if(this.#u!==void 0)return this.#u;if(this.#i()<this.#g)return;let e=this.#t.openServe??jf,t;try{t=e([...this.#t.config.yrd,"issues","list-page-serve","--project-root",this.#t.config.projectRoot],this.#p.signal)}catch(r){this.#ie(void 0,{code:null,stderr:J(r)});return}return this.#u=t,t.exited.then((r)=>this.#ie(t,r),(r)=>this.#ie(t,{code:null,stderr:J(r)})),t}#ie(e,t){if(e!==void 0&&this.#u!==e)return;if(this.#u===e)this.#u=void 0;if(this.#p.signal.aborted)return;this.#a++;let r=Math.min(this.#$*2**Math.min(this.#a-1,5),60000);if(this.#g=this.#i()+r,yw(t.stderr)){this.#f=!0,this.#t.log.error(`hightea-source: ${this.sourceId} declares no list-page-serve (${xt(t)}); reading with list-page, one process per read`);return}if(this.#w=!0,this.#v++,this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${xt(t)} (restart ${this.#v}, attempt ${this.#a}, in ${Math.round(r/1000)} s)`),this.#h!==void 0)return;this.#h=setTimeout(()=>{if(this.#h=void 0,this.#p.signal.aborted||this.#K()===void 0)return;this.#t.log.info?.(`hightea-source: the km reader of ${this.sourceId} is back; reading it once to catch up`),this.#I().catch((n)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after the km reader returned failed: ${J(n)}`))},r)}async#Ee(e){let t=this.#K();if(t!==void 0)try{let{progress:n,...o}=e,s=await t.ask(o,this.#t.childTimeoutMs??120000);if("refusal"in s){let{code:a,message:c,hint:d}=s.refusal;return{ok:!1,stderr:`page-serve: ${a}: ${c}${d===void 0?"":` (${d})`}`}}this.#a=0,this.#y=!1,this.#w=!1;let i=this.#t.pageServeCeilingBytes??tw;if(s.rss!==void 0&&s.rss>i)this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, rss ${Kf(s.rss)} MiB is above its ${Kf(i)} MiB ceiling (restart ${this.#v+1})`),t.close();if(!("pages"in s))throw new pe("page-serve-frame-malformed","the reader answered a progress frame where the page was asked for");return{ok:!0,stdout:_w(s.pages),from:"reader"}}catch(n){if(!(n instanceof pe))throw n;this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${J(n)}; this read uses list-page`)}if(!this.#f&&!this.#y)this.#y=!0,this.#t.log.info?.(`hightea-source: ${this.sourceId} reads with list-page while its km reader restarts; one process per read`);let r=await this.#Y(["issues","list-page",JSON.stringify(e)]);return r.code===0?{ok:!0,stdout:r.stdout,from:"one-shot"}:{ok:!1,stderr:r.stderr}}#Ie(e){try{let t=JSON.parse(e);if(t.source==="item-history")return;if(typeof t.seq==="number"&&Number.isSafeInteger(t.seq))this.#S=Math.max(this.#S??0,t.seq)}catch{if(this.#N)return;this.#N=!0,this.#t.log.error(`hightea-source: ${this.sourceId}: km's change feed wrote a line that is not a journal record, so its changes carry no seq; freshness is checked against each answer's head only`)}}#pe(e){let t=this.#S;if(this.#m=void 0,t===void 0)return;if(typeof e==="number"&&e<t)this.#t.log.error(`hightea-source: ${this.sourceId} read whole at head ${String(e)}, below the change notice at ${t}; that notice is not about this vault's journal`);this.#S=void 0}#I(e=!1,t=!1,r=!1){if(this.#n!==void 0){if(this.#T=!0,t)this.#R=!0;return this.#n}if(this.#_!==void 0)clearTimeout(this.#_),this.#_=void 0;this.#T=!1,this.#C=void 0,this.#A=void 0;let n=this.#i(),o=this.#Oe(e,t,r).then((s)=>(this.#ne=0,s),(s)=>{throw this.#ke(),s}).finally(()=>{if(this.#n=void 0,this.#G=this.#i(),this.#re=this.#G-n,this.#ae(),this.#T&&!this.#p.signal.aborted)this.#T=!1,this.hint()});return this.#n=o,this.#d=this.#o,o}#ke(){if(this.#p.signal.aborted||this.#_!==void 0)return;this.#ne++;let e=Math.min(this.#$*2**Math.min(this.#ne-1,5),60000);this.#t.log.info?.(`hightea-source: ${this.sourceId} will read again in ${Math.round(e/1000)} s after a failed read`),this.#_=setTimeout(()=>{this.#_=void 0,this.#I().catch((t)=>this.#t.log.error(`hightea-source: retrying ${this.sourceId} after a failed read failed: ${J(t)}`))},e)}#Ce(){if(this.#H!==void 0)return this.#H;let e=[...this.#z].sort((r,n)=>r-n),t=e.length===0?0:e[Math.floor(e.length/2)];return Math.max(this.#F,10*t)}#ae(){if(this.#p.signal.aborted||!this.#e.watching||this.#E!==void 0)return;let e=this.#Ce();if(!(e>0))return;let t=Math.max(this.#G,this.#B),r=Math.max(0,e-(this.#i()-t));this.#E=setTimeout(()=>{if(this.#E=void 0,this.#p.signal.aborted||!this.#e.watching)return;if(this.#n!==void 0){this.#ae();return}this.#I(!0,!0,!0).catch((n)=>this.#t.log.error(`hightea-source: the watcher read of ${this.sourceId} failed: ${J(n)}`))},r)}#me(){if(this.#E===void 0)return;clearTimeout(this.#E),this.#E=void 0}#Re(){if(this.#p.signal.aborted||this.#_!==void 0)return;this.#_=setTimeout(()=>{if(this.#_=void 0,this.#n!==void 0){this.#T=!0;return}this.#I(!0).catch((e)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a trailing notice failed: ${J(e)}`))},this.#ee)}async#Oe(e,t,r=!1){for(let n=1;;n++){let o=`${this.#e.epoch}.${++this.#o}`;try{let s=this.#c;if(s!==void 0){let i=await this.#Pe(o,s,e,t,r);if(i!==void 0)return i}return await this.#Te(o)}catch(s){if(n>=Ff||!(s instanceof cr)||!Gf(s.stderr))throw s;this.#t.log.error(`hightea-source: read of ${this.sourceId} restarted after the vault moved (${n}/${Ff}): ${bt(s.stderr)}`),await this.#Le()}}}async#Te(e){let t=await this.#Ae(e);if(t!==void 0)return t;return await this.#$e(e)}async#Ae(e){if(this.#l===!1)return;let t={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,traverse:!0,progress:!0},r=await this.#Y(["issues","list-page",JSON.stringify(t)]);if(r.code!==0){if(!gw(r.stderr))throw new cr(r.stderr);this.#l=!1,this.#t.log.error(`hightea-source: ${this.sourceId} has no one-process traversal (${bt(r.stderr)}); checking a single-page native snapshot; larger snapshots require traversal`);return}if(this.#l===void 0)this.#l=!0;let n=lw(r.stdout,e);if(n.activityUnreadRows>0)this.#t.log.error(`hightea-source: ${this.sourceId}: activity read unavailable for ${n.activityUnreadRows} of ${n.rows.length} rows; progress remains unknown; check the declared activity command`);let o=new Map;this.#ue(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#x={value:n.progress,at:s};return this.#V(o,n.progress,s),this.#Se(n.head),this.#pe(n.head),this.#W(e,ps(o),o)}async#$e(e){let t={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,progress:!0},r=await this.#Y(["issues","list-page",JSON.stringify(t)]);if(r.code!==0)throw new cr(r.stderr);let n=ms(r.stdout);if(!n.complete){if(this.#l===!1)this.#l=void 0,this.#t.log.info?.(`hightea-source: ${this.sourceId}: a paged whole read cannot serve this multi-page vault; asking the one-process traversal again`);throw Error("progress refresh needs one-process traversal for a multipage native snapshot")}let o=new Map;this.#ue(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#x={value:n.progress,at:s};return this.#V(o,n.progress,s),this.#Se(n.head),this.#pe(n.head),this.#W(e,ps(o),o)}#ce(e,t){this.#t.log.error(`hightea-source: row ${e} omitted: ${t}`)}#ue(e,t){for(let r of t){let n=this.#Fe(r),o=wt.safeParse(n);if(!o.success){let s=o.error.issues.map((i)=>{let a=(i.path[0]==="columns"?i.path.slice(1):i.path).join("."),c=i.path.reduce((d,u)=>typeof d==="object"&&d!==null?Reflect.get(d,u):void 0,n);return i.code==="too_big"&&typeof c==="string"?`${a} is ${c.length} chars, cap ${i.maximum}`:`${a}: ${i.message}`});this.#ce(r.id,s.join("; "));continue}if(te(n)>ot)throw new vn(n.address);e.set(n.address,{key:r.path,row:n})}}async#Pe(e,t,r,n,o){let s=this.#r;if(s===void 0)return;let i={binding:this.sourceId,population:"all-issues",generation:e,limit:fs,changedSince:t,progress:!0},a=this.#i(),c=await this.#Ee(i),d=this.#i();if(!c.ok){let x=Gf(c.stderr),I=/--page changedSince \d+ needs the vault's journal at [^\n]+, which no daemon has written; do a full read(?:\r?\n|$)/u.test(c.stderr);if(!x&&!mw(c.stderr)&&!I)throw new cr(c.stderr);return this.#t.log.info?.(`hightea-source: ${this.sourceId} could not read after ${t} (${bt(c.stderr)}); reading it whole`),x?this.#ye():this.#ge(r)}let u=ms(c.stdout);if(!u.complete)return this.#t.log.info?.(`hightea-source: ${this.sourceId} answered a bounded change list (${u.reason??"no reason named"}); reading it whole`),this.#ge(r);if(typeof u.head!=="number"||u.head<t)throw Error(`list-page answered changedSince ${t} at head ${String(u.head)}`);let l=this.#S;if(l!==void 0&&u.head<l){let x=this.#m??(this.#m=this.#i());if(this.#i()-x>=(this.#t.noticePatienceMs??rw))this.#t.log.error(`hightea-source: ${this.sourceId} stayed below the change notice at ${l} for ${Math.round(this.#i()-x)} ms at head ${String(u.head)}; that notice is not about this vault's journal`),this.#S=void 0,this.#m=void 0;else this.#t.log.info?.(`hightea-source: ${this.sourceId}: answer head ${String(u.head)} trails the change notice at ${l}; serving the delta and reading again`),this.#Re()}else if(l!==void 0)this.#S=void 0,this.#m=void 0;let p=new Map(s.byAddress),f=new Set(u.rows.map((x)=>this.#de(x))),m=new Map([...s.byAddress].map(([x,I])=>[I.key,x]));for(let x of f)p.delete(x);if(this.#ue(p,u.rows),this.#je(s,p,f,m,u.rows,u.removed))return this.#t.log.info?.(`hightea-source: ${this.sourceId} saw an ancestor project or path change after ${t}; reading it whole`),this.#ye();for(let x of u.removed){let I=m.get(x);if(I!==void 0&&!f.has(I))p.delete(I)}if(c.from==="reader"){let x=await this.#ze(o);if(x!==void 0)this.#V(p,x.value,x.at)}else{let x=this.#i();if(u.progress!==void 0)this.#x={value:u.progress,at:x};this.#V(p,u.progress,x)}this.#c=u.head,this.#q=!1;let y=this.#i(),g=ps(p),w=this.#i(),b=this.#W(e,g,p),v=this.#i();if(n||v-a>=500){let x=o?"watch":n?"client":"change";this.#t.log.info?.(`hightea-source: ${this.sourceId} ${x} delta read ${Math.round(v-a)} ms: yrd ${Math.round(d-a)} ms, collect ${Math.round(y-d)} ms, revision ${Math.round(w-y)} ms, diff ${Math.round(v-w)} ms`)}return b}#ge(e){this.#q=e;return}#ye(){this.#q=!1;return}async#Ne(){let e=this.#K();if(e===void 0)throw Error("progress unavailable: list-page-serve not running");let t=await e.ask({progress:!0},this.#t.childTimeoutMs??120000);if("refusal"in t)throw Error(`progress unavailable: ${t.refusal.code}: ${t.refusal.message}`);if(!("progress"in t))throw Error("progress unavailable: the reader answered a page where the frame was asked for");let r=t.progress;if(r!==void 0&&Buffer.byteLength(JSON.stringify(r))>xn)throw Error("progress refresh output exceeded its byte budget");return r}async#ze(e){let t=this.#x;if(!(t===void 0||this.#i()-t.at>=this.#te))return t;if(t===void 0||e){await this.#_e();let n=this.#x;if(n===void 0)throw Error("progress refresh completed without a projection");return n}return this.#_e().catch((n)=>this.#t.log.error(`hightea-source: ${this.sourceId} activity projection refresh failed: ${J(n)}`)),t}#Me(){let e=this.#U;if(e===void 0||this.#P===void 0)return;if(this.#b<sw&&this.#i()-e<iw)return;return{since:new Date(e).toISOString(),reason:this.#P}}#_e(){if(this.#k!==void 0)return this.#R=!0,this.#k;let e=(async()=>{do{this.#R=!1;let t=this.#i();try{let r=await this.#Ne();if(this.#z.push(this.#i()-t),this.#z.length>aw)this.#z.shift();this.#we(r),this.#x={value:r,at:this.#i()},this.#b=0,this.#U=void 0,this.#P=void 0}catch(r){throw this.#b++,this.#U??=this.#i(),this.#P=J(r),r}}while(this.#R&&!this.#p.signal.aborted)})().finally(()=>{this.#k=void 0});return this.#k=e,e}#we(e){let t=e;if(typeof t!=="object"||t===null||!Array.isArray(t.qualifying)||t.complete!==!0)throw Error("progress refresh requires a complete terminal qualifying projection, not an ordinary page");let{source:r,default:n}=t;if(!(r==="ok"||r==="undeclared"||r==="unreadable")||n!==(r==="unreadable"?null:!1))throw Error("progress refresh has an invalid progress.source/progress.default pair");let o=new Map,s=new Map;for(let i of t.qualifying){if(typeof i!=="object"||i===null)throw Error("progress refresh carries a malformed qualifying entry");let a=i;if(typeof a.id!=="string"||a.id.length===0||typeof a.reason!=="string"||a.reason.length===0||a.owner!==void 0&&(typeof a.owner!=="string"||a.owner.length===0))throw Error("progress refresh qualifying entry needs identity, reason and an optional nonempty owner");if(a.owner===void 0){if(o.has(a.id))throw Error("progress refresh repeats a hold identity");o.set(a.id,a.reason)}else{let c=s.get(a.id)??new Map;if(c.has(a.owner))throw Error("progress refresh repeats an identity/owner");c.set(a.owner,a.reason),s.set(a.id,c)}}return{source:r,idle:n,holds:o,actors:s}}#V(e,t,r){this.#De(e,this.#we(t)),this.#O=r}#De(e,t){let r=0;for(let[n,o]of e){let s=o.row,i=s.extra,a=Sn(o.key),c=a===null?`path:${o.key.endsWith(".md")?o.key.slice(0,-3):o.key}`:`bead:${a}`,d=this.#J(s.columns.owner??"")??"",u=t.holds.get(c)??(d===""?void 0:t.actors.get(c)?.get(d)),l=u===void 0?t.idle:!0;if(l===null)r++;if(i.in_progress===l&&i.in_progress_reason===(u??null))continue;let p={id:i.id,title:s.columns.title,status:s.columns.state,owner:d,project:s.columns.project,in_progress:l,in_progress_reason:u??null,updated_at:s.columns.updatedAt,closed_at:i.closed_at??null},f={...s,version:qf(p),extra:{...i,in_progress:l,in_progress_reason:u??null}},m=te(f);if(m>ot){e.delete(n),this.#ce(i.id,`the row is ${m} bytes with its progress, over the ${ot}-byte row cap`);continue}e.set(n,{key:o.key,row:f})}if(t.source==="unreadable")this.#t.log.error(`hightea-source: ${this.sourceId}: activity read unavailable; ${r} of ${e.size} materialized rows have unknown progress`)}#Se(e){if(typeof e==="number"){this.#c=e;return}if(this.#c=void 0,this.#Z)return;this.#Z=!0,this.#t.log.info?.(`hightea-source: ${this.sourceId} names no journal to continue from; every read stays whole`)}async#Le(){if(this.#p.signal.aborted)return;await new Promise((e)=>{let t=()=>{clearTimeout(r),this.#p.signal.removeEventListener("abort",t),e()},r=setTimeout(t,this.#$);this.#p.signal.addEventListener("abort",t,{once:!0})})}#W(e,t,r){let n=this.#r,o=new Map,s=[...new Set([...r.keys(),...n?.byAddress.keys()??[]])].sort(),i=[];for(let a of s){let c=r.get(a),d=n?.byAddress.get(a);if(c===void 0){i.push({position:this.#e.next(),change:{op:"delete",address:a}});continue}if(n!==void 0&&(d===void 0||d.row.version!==c.row.version||!fw(d.row,c.row))){let u=this.#e.next();i.push({position:u,change:{op:"upsert",row:c.row}}),o.set(a,{key:c.key,row:c.row,at:BigInt(u.ordinal)})}else o.set(a,{key:c.key,row:c.row,at:d?.at??0n})}if(n===void 0&&o.size>0){let a=o.get(s[0]),c=this.#e.next();i.push({position:c,change:{op:"upsert",row:a.row}}),o.set(a.row.address,{...a,at:BigInt(c.ordinal)})}return this.#Ue(e,t,i,o)}#Ue(e,t,r,n){let o={generation:e,snapshot:t,base:this.#e.ordinal,epoch:this.#e.epoch,rows:[...n.values()],byAddress:n,at:this.#i()};this.#r=o,this.#s.set(e,o);for(let[i,a]of this.#s)if(this.#s.size>X_||this.#i()-a.at>Q_)this.#s.delete(i);let s=this.#j;if(this.#j=!1,this.#e.enqueue(r,s?{soon:!0}:void 0),r.length>0)this.#t.onRecords?.(r);return o}#de(e){return`issue:${this.sourceId}/${Sn(e.path)??e.id}`}#Ze(e){if(e.container===null||e.containerSource===null||e.containerSource==="beads-root")return null;let t=e.container.endsWith(".md")?e.container:`${e.container}.md`;return`issue:${this.sourceId}/${Sn(t)??e.container}`}#je(e,t,r,n,o,s){let i=new Set,a=new Set;for(let c of o){let d=this.#de(c),u=e.byAddress.get(d),l=t.get(d),p=u!==void 0&&l!==void 0&&u.row.columns.project!==l.row.columns.project,f=u!==void 0&&l!==void 0&&u.key!==l.key,m=u===void 0&&l!==void 0&&l.row.columns.project===d;if(!p&&!f&&!m)continue;if(i.add(d),u?.row.columns.project!==void 0&&u.row.columns.project!==null)i.add(u.row.columns.project);if(u!==void 0)for(let y of hs(u.key))a.add(y);if(l!==void 0)for(let y of hs(l.key))a.add(y)}for(let c of s){for(let u of hs(c))a.add(u);let d=n.get(c);if(d!==void 0){let u=e.byAddress.get(d);if(u!==void 0&&u.row.columns.project===d)i.add(d)}}if(i.size===0&&a.size===0)return!1;for(let[c,d]of e.byAddress){if(r.has(c))continue;if(d.row.columns.project!==null&&i.has(d.row.columns.project))return!0;let u=d.key.startsWith("./")?d.key.slice(2):d.key;for(let l of a)if(u.startsWith(l))return!0}return!1}#Fe(e){let t=this.#de(e),r=e.owner.trim(),n=e.status.trim()===""?"none":e.status.trim(),o=this.#Ze(e),s=qf({id:e.id,title:e.title,status:n,owner:r,project:o,in_progress:e.in_progress,in_progress_reason:e.in_progress_reason,updated_at:e.updated_at,closed_at:e.closed_at});return{address:t,version:s,scope:"all",columns:{title:e.title,state:n,owner:r===""?null:this.#le.get(r)??`km:${r}`,parent:null,project:o,labels:[],url:null,updatedAt:e.updated_at},extra:{path:e.path,id:e.id,in_progress:e.in_progress,in_progress_reason:e.in_progress_reason,closed_at:e.closed_at}}}#J(e){if(e.startsWith("km:"))return e.slice(3);return this.#t.config.members[e]}#He(e){let t=`issue:${this.sourceId}/`;if(!e.startsWith(t)||e.length<=t.length)return;let r=this.#r?.byAddress.get(e)?.key;if(r!==void 0)return r;let n=e.slice(t.length);return Sn(n)===null?n:void 0}async#Y(e,t){let{config:r}=this.#t;try{return await this.#D([...r.yrd,...e,"--project-root",r.projectRoot],{timeoutMs:this.#t.childTimeoutMs??120000,signal:this.#p.signal,...t===void 0?{}:{env:t}})}catch(n){throw Error(`the yrd command ${r.yrd[0]??"(none)"} could not run: ${J(n)}`)}}async#Be(){let e=this.#t.follow??vw,t=this.#p.signal;while(!t.aborted){let r=String(this.#i());try{let n=await e([...this.#t.config.feed,"--since",r],{signal:t,onLine:(o)=>this.hint(o)});if(t.aborted)return;this.#t.log.error(`hightea-source: km's change feed for ${this.sourceId} ended (${n.code??"signal"}): ${bt(n.stderr)}`)}catch(n){if(t.aborted)return;this.#t.log.error(`hightea-source: km's change feed for ${this.sourceId} could not run: ${J(n)}`)}this.hint(),await new Promise((n)=>{let o=setTimeout(n,ew);t.addEventListener("abort",()=>{clearTimeout(o),n()},{once:!0})})}}}var cw=new Set(["self","ancestor","folder-note","beads-root"]);function hs(e){let t=e.startsWith("./")?e.slice(2):e,r=t.endsWith(".md")?t.slice(0,-3):t;if(r==="")return[];let n=[`${r}/`],o=r.lastIndexOf("/");if(o>0){let s=r.slice(0,o),i=r.slice(o+1),a=i.toLowerCase(),c=s.slice(s.lastIndexOf("/")+1);if(a==="index"||a==="readme"||i===c)n.push(`${s}/`)}return n}var uw=/^(\d{4,})-.+\.md$/u,dw=/^\d{4}-\d{2}-\d{2}/u;function Sn(e){let t=e.startsWith("./")?e.slice(2):e;if(!t.startsWith("@"))return null;let r=t.lastIndexOf("/");if(r<0)return null;let n=t.slice(r+1);if(dw.test(n))return null;let o=uw.exec(n),s=o===null?Number.NaN:Number.parseInt(o[1],10);return Number.isInteger(s)&&s>=0?s:null}function Bf(e,t){let r=e[t];if(r===void 0||r===null||r==="")return null;if(typeof r!=="string"||!Number.isFinite(Date.parse(r)))throw Error(`list-page answered ${t} outside an ISO instant`);return new Date(r).toISOString()}function qf(e){return Vf("sha256").update(`${e.id}\x00${e.title}\x00${e.status}\x00${e.owner}\x00${e.project??""}\x00${String(e.in_progress)}\x00${e.in_progress_reason??""}\x00${e.updated_at??""}\x00${e.closed_at??""}`).digest("hex").slice(0,16)}function ms(e){if(Buffer.byteLength(e)>xn)throw Error("progress refresh output exceeded its byte budget");let t=JSON.parse(e);if(t.verb!=="list-page"||typeof t.result!=="object"||t.result===null)throw Error("list-page answered outside km's page shape");let r=t.result;if(typeof r.snapshot!=="string"||!Array.isArray(r.rows)||typeof r.complete!=="boolean"||!("next"in r)||r.next!==null&&typeof r.next!=="string")throw Error("list-page answered outside km's page shape");let n=(c)=>typeof c==="string",o=r.rows.map((c)=>{let d=c,u=typeof d.row==="object"&&d.row!==null?d.row:d;if(!n(u.id)||!n(u.title)||!n(u.status)||!n(u.owner))throw Error("list-page answered a row outside the declared columns (id, title, status, owner)");if("content"in u||"description"in u)throw Error("list-page answered a row carrying the issue body");let l=u.in_progress;if(l!==void 0&&l!==null&&typeof l!=="boolean")throw Error("list-page answered in_progress outside a boolean or null");let p=u.in_progress_reason;if(p!==void 0&&p!==null&&typeof p!=="string")throw Error("list-page answered in_progress_reason outside a string or null");if(l===!0&&typeof p!=="string")throw Error("list-page answered in_progress true without the environment holding it");let{container:f,containerSource:m}=u,y=null,g=null;if(f!==void 0||m!==void 0){if(typeof f!=="string"||f.trim()===""||typeof m!=="string"||!cw.has(m))throw Error("list-page answered malformed container/containerSource");y=f,g=m}let w={id:u.id,title:u.title,status:u.status,owner:u.owner,container:y,containerSource:g,in_progress:l??null,in_progress_reason:p??null,updated_at:Bf(u,"updated_at"),closed_at:Bf(u,"closed_at")},b=n(d.path)?d.path:w.id;return{...w,path:b}}),s=r.head;if(s!==void 0&&s!==null&&!(typeof s==="number"&&Number.isSafeInteger(s)&&s>=0))throw Error("list-page named a head that is not a journal seq");let i=r.removed;if(i!==void 0&&(!Array.isArray(i)||!i.every((c)=>typeof c==="string")))throw Error("list-page named removed rows outside km's shape");let a=r.reason;if(a!==void 0&&typeof a!=="string")throw Error("list-page named a reason that is not text");return{progress:r.progress,snapshot:r.snapshot,rows:o,next:r.next,complete:r.complete,head:s,removed:i??[],reason:a}}function lw(e,t){if(Buffer.byteLength(e)>xn)throw Error("progress refresh output exceeded its byte budget");let r=e.split(`
71
+ `);while(r.length>0&&r[r.length-1].trim()==="")r.pop();if(r.length===0)throw Error("list-page traversal answered no frame");let n,o=[],s,i;if(r.forEach((a)=>{if(s!==void 0)throw Error("list-page traversal answered a frame after its terminal one");let c=JSON.parse(a);if(typeof c!=="object"||c===null||Array.isArray(c))throw Error("list-page traversal answered a frame outside km's page shape");let d=c,u=d.verb==="list-page"&&typeof d.result==="object"&&d.result!==null?d.result:d;if(typeof u.generation!=="string"||u.generation!==t)throw Error("list-page traversal answered a frame for another generation");if(typeof u.population!=="number"||!Number.isSafeInteger(u.population)||u.population<0)throw Error("list-page traversal answered a frame with no population count");if(u.next!==null&&typeof u.next!=="string")throw Error("list-page traversal answered a frame with a malformed next token");let l=ms(JSON.stringify({verb:"list-page",result:u}));if(n===void 0)n={snapshot:l.snapshot,head:l.head,population:u.population};else{if(l.snapshot!==n.snapshot)throw Error("list-page traversal answered frames of two revisions");if(u.population!==n.population)throw Error("list-page traversal answered frames of two populations");if(l.head!==n.head)throw Error("list-page traversal answered frames of two journal heads")}if(o.push(...l.rows),u.complete===!0){if(u.next!==null)throw Error("list-page traversal completed a frame that still names a next page");let p=u.meta,f=typeof p==="object"&&p!==null?p.activityUnreadRows:void 0;if(typeof f!=="number"||!Number.isSafeInteger(f)||f<0||f>u.population)throw Error(`list-page traversal terminal meta.activityUnreadRows must be an integer from 0 through ${u.population}; got ${String(f)}`);s=f,i=u.progress}else if(u.next===null)throw Error("list-page traversal left a frame incomplete with no next page")}),s===void 0)throw Error("list-page traversal never completed");if(n===void 0)throw Error("list-page traversal answered no frame");if(o.length!==n.population)throw Error(`list-page traversal answered ${o.length} rows of ${n.population}`);return{snapshot:n.snapshot,head:n.head,rows:o,activityUnreadRows:s,progress:i}}function ps(e){let t=Vf("sha256");for(let r of[...e.keys()].sort())t.update(`${r}\x00${e.get(r).row.version}
72
+ `);return t.digest("hex")}function fw(e,t){return JSON.stringify(e.columns)===JSON.stringify(t.columns)}function hw(e,t){return Buffer.from(JSON.stringify([e,t])).toString("base64url")}function pw(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(Array.isArray(t)&&typeof t[0]==="string"&&Number.isSafeInteger(t[1])&&t[1]>=0)return{generation:t[0],offset:t[1]}}catch{}return}function bt(e){let t=/\b(yrd-[a-z-]+|page-source-[a-z-]+|page-serve-[a-z-]+|[A-Z][A-Z_]{3,})\b/u.exec(e)?.[1];if(t!==void 0)return t;let r=e.split(/\r?\n/u).map((n)=>n.trim()).find((n)=>n.length>0);return r===void 0?"no output":r.slice(0,140)}function mw(e){return/\bpage-source-cursor-unservable\b|cursor[^\n]*(?:do a full read|retention|is older than the journal's retained start|is ahead of this store's watermark|is below watermark)/u.test(e)}function Gf(e){return/\bpage-source-(?:moved|not-reconciled)\b/u.test(e)}function gw(e){return/\byrd-issues-(?:provider-not-json|verb-unsupported)\b/u.test(e)}function yw(e){return/\blist-page-serve is not declared\b/u.test(e)||/\byrd-issues-verb-unsupported\b/u.test(e)}function _w(e){return e.map((t)=>JSON.stringify({verb:"list-page",result:t})).join(`
73
73
  `)+`
74
- `}var qf=(e)=>Math.round(e/1048576);function Y(e){if(e instanceof Error&&"code"in e&&typeof e.code==="string")return e.code;return e instanceof Error?e.message:String(e)}var yw=['command -v "$1" >/dev/null 2>&1 || { echo "hightea-spawn: ENOENT" >&2; exit 127; }',"exec 3<&0",'"$@" </dev/null 3<&- &',"c=$!","{ cat <&3 >/dev/null 2>&1; kill -KILL 0; } >/dev/null 2>&1 &","w=$!","exec 3<&-",'wait "$c"',"s=$?",'kill -KILL "$w" 2>/dev/null','exit "$s"'].join(`
75
- `);function Kf(e,t){return V_("/bin/sh",["-c",yw,"hightea-spawn",...e],{stdio:["pipe","pipe","pipe"],detached:!0,...t===void 0?{}:{env:{...process.env,HAB_ID_TOKEN_FILE:t.HAB_ID_TOKEN_FILE}}})}function Vf(e,t,r){if(t!==127||!r.includes("hightea-spawn: ENOENT"))return;return Object.assign(Error(`spawn ${e} ENOENT`),{code:"ENOENT"})}function Et(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}var ys=(e,{timeoutMs:t,signal:r,env:n})=>new Promise((o,s)=>{let[i,...a]=e;if(i===void 0){s(Error("no command"));return}let c=Kf([i,...a],n),d="",u="",l=0,p,f=()=>{if(c.exitCode!==null||c.signalCode!==null)return;Et(c,"SIGTERM"),p??=setTimeout(()=>Et(c,"SIGKILL"),2000)},m=setTimeout(f,t);r.addEventListener("abort",f,{once:!0});let y=(w)=>(b)=>{if(l+=b.length,l>vn)return f();if(w==="out")d+=b;else u+=b};c.stdout.setEncoding("utf8").on("data",y("out")),c.stderr.setEncoding("utf8").on("data",y("err"));let g=!0;c.on("error",(w)=>{g=!1,clearTimeout(m),s(w)}),c.on("close",(w,b)=>{if(clearTimeout(m),p!==void 0)clearTimeout(p);if(Et(c,"SIGKILL"),r.removeEventListener("abort",f),!g)return;let v=Vf(i,w,u);if(v!==void 0)s(v);else o({pid:c.pid,code:b===null?w:null,stdout:d,stderr:u})})}),_w=(e)=>{try{let t=JSON.parse(e);if(typeof t.ts!=="number"||!Number.isFinite(t.ts))return;if(t.source==="item-history")return;return{at:t.ts,source:typeof t.source==="string"?t.source:void 0}}catch{return}},ww=(e,{signal:t,onLine:r})=>new Promise((n,o)=>{let[s,...i]=e;if(s===void 0){o(Error("no command"));return}let a=Kf([s,...i]),c="",d,u=()=>{if(a.exitCode!==null||a.signalCode!==null)return;Et(a,"SIGTERM"),d??=setTimeout(()=>Et(a,"SIGKILL"),2000)};t.addEventListener("abort",u,{once:!0}),W_({input:a.stdout}).on("line",(p)=>{if(p.trim()!=="")r(p)}),a.stderr.setEncoding("utf8").on("data",(p)=>{if(c.length<65536)c+=p});let l=!0;a.on("error",(p)=>{l=!1,o(p)}),a.on("close",(p,f)=>{if(d!==void 0)clearTimeout(d);if(Et(a,"SIGKILL"),t.removeEventListener("abort",u),!l)return;let m=Vf(s,p,c);if(m!==void 0)o(m);else n({pid:a.pid,code:f===null?p:null,stdout:"",stderr:c})})});import{createHash as Sw}from"node:crypto";function Jf(e){return e.kind==="command"}var vw="all",xw=60000,Wf=400,It=(e)=>e instanceof Error?e.message:String(e);function _s(e){let t=e.split(`
76
- `).map((r)=>r.trim()).find((r)=>r!=="")??"";return t.length>Wf?`${t.slice(0,Wf)}…`:t}function bw(e,t){if(typeof e.info==="function")e.info(t);else e.error(t)}class ws{sourceId;#e;#o;#r;#s;#n;#l;#c=0;#f;#u;#h=new Map;#a;#m=new AbortController;constructor(e){let{config:t}=e;if(t.command.length===0)throw Error(`the command source ${t.sourceId} declares no command`);if(t.key.trim()==="")throw Error(`the command source ${t.sourceId} declares an empty key field`);let r=t.intervalMs;if(!(Number.isFinite(r)&&r>0))throw Error(`the command source ${t.sourceId} needs a positive intervalMs, not ${String(r)}`);this.#e=e,this.sourceId=t.sourceId,this.#o=e.run??ys,this.#r=e.now??Date.now,this.#n=r,this.#l=e.childTimeoutMs??xw,this.#s=new ar({sourceId:t.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(n)=>e.push(n),log:e.log,now:this.#r,...e.coalesceMs===void 0?{}:{coalesceMs:e.coalesceMs},onOmit:(n,o)=>e.log.error(`hightea-source: ${t.sourceId} row ${n} omitted: ${o}`),onOverflow:()=>this.#x()})}get epoch(){return this.#s.epoch}start(){this.#d()}async stop(){if(this.#m.abort(),this.#s.stop(),this.#a!==void 0)clearTimeout(this.#a),this.#a=void 0;await this.#u?.catch(()=>{return})}#d(){if(this.#m.signal.aborted)return;this.#w().catch((e)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} failed; keeping the last good dataset: ${It(e)}`)).finally(()=>this.#y())}#y(){if(this.#m.signal.aborted||this.#a!==void 0)return;this.#a=setTimeout(()=>{this.#a=void 0,this.#d()},this.#n)}async#w(){let e=this.#u;if(e!==void 0)return await e;let t=this.#_().finally(()=>{this.#u=void 0});return this.#u=t,await t}async#_(){let{config:e}=this.#e,t;try{t=await this.#o(e.command,{timeoutMs:this.#l,signal:this.#m.signal})}catch(n){throw Error(`the command ${e.command[0]??"(none)"} could not run: ${It(n)}`)}if(t.code!==0)throw Error(`the command exited ${t.code===null?"on a signal":t.code}${_s(t.stderr)===""?"":`: ${_s(t.stderr)}`}`);if(t.stderr.trim()!=="")bw(this.#e.log,`hightea-source: ${this.sourceId} read warned: ${_s(t.stderr)}`);let r=this.#S(t.stdout);return this.#v(r)}#S(e){let{key:t}=this.#e.config,r=e.split(`
77
- `),n=new Map;for(let[o,s]of r.entries()){let i=s.trim();if(i==="")continue;let a=`line ${o+1}`,c;try{c=JSON.parse(i)}catch(f){throw Error(`${a} is not JSON: ${It(f)}`)}if(c===null||typeof c!=="object"||Array.isArray(c))throw Error(`${a} is not an object`);let d=c;for(let f of Object.keys(d))if(f!==t&&f!=="columns"&&f!=="extra"&&f!=="version")throw Error(`${a} carries an unknown field "${f}"; a line is {${t}, columns, extra?, version?}`);let u=d[t];if(typeof u!=="string"||u.trim()==="")throw Error(`${a} has no "${t}"; every row needs an address`);let l=d.version??Sw("sha256").update(JSON.stringify([d.columns??null,d.extra??null])).digest("hex");if(typeof l!=="string"||l==="")throw Error(`${a} carries an unusable "version"`);let p=St.safeParse({address:u,version:l,scope:vw,columns:d.columns,extra:d.extra??null});if(!p.success){let f=p.error.issues.slice(0,3).map((m)=>`${m.path.join(".")||"row"}: ${m.message}`).join("; ");throw Error(`${a} is not a row: ${f}`)}if(n.has(u))throw Error(`${a} repeats the address ${u}; one line per row`);n.set(u,{key:u,row:p.data})}return n}#v(e){let t=this.#f,r=new Map,n=[],o=[...new Set([...e.keys(),...t?.byAddress.keys()??[]])].sort();for(let i of o){let a=e.get(i),c=t?.byAddress.get(i);if(a===void 0){n.push({position:this.#s.next(),change:{op:"delete",address:i}});continue}if(c===void 0||c.row.version!==a.row.version){let d=this.#s.next();n.push({position:d,change:{op:"upsert",row:a.row}}),r.set(i,{row:a.row,at:BigInt(d.ordinal)})}else r.set(i,{row:a.row,at:c.at})}this.#h=e;let s={generation:`${this.#s.epoch}.${++this.#c}`,epoch:this.#s.epoch,base:this.#s.ordinal,rows:[...r.values()],byAddress:r,at:this.#r()};return this.#f=s,this.#s.enqueue(n),s}#x(){let e=this.#h.size;if(e>yn){this.#e.log.error(`hightea-source: ${this.sourceId} holds ${e} rows, more than the ${yn} one push may carry; shorten the command's answer`);return}if(this.#f=void 0,e===0){this.#w().catch((t)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} after an overflow failed: ${It(t)}`));return}this.#v(this.#h)}async#k(){return this.#f??await this.#w()}#C(e,t){let r=e.byAddress.get(t);if(r===void 0)return{position:{epoch:e.epoch,ordinal:String(e.base)},change:{op:"delete",address:t}};return{position:{epoch:e.epoch,ordinal:String(r.at)},change:{op:"upsert",row:r.row}}}#O(e,t,r){let n=e.page===void 0?0:Number(e.page);if(!Number.isSafeInteger(n)||n<0||n>r.rows.length)throw Error(`the list token ${String(e.page)} does not name a page of this read`);let o=(c,d)=>({generation:r.generation,snapshot:r.generation,base:{epoch:r.epoch,ordinal:String(r.base)},rows:d,next:c>=r.rows.length?null:String(c),complete:c>=r.rows.length}),s=[],i=0,a=n;while(a<r.rows.length&&s.length<e.limit){let c=r.rows[a].row,d=te(c);if(te({...t,op:"list",outcome:"applied",body:o(a+1,[])})+i+d+s.length>st){if(s.length===0)throw Error(`ITEM_TOO_LARGE: ${c.address}`);break}s.push(c),i+=d,a++}return o(a,s)}async handle(e){let t={workspaceId:e.workspaceId,sourceId:e.sourceId,hostId:e.hostId},r=(n,o="refused")=>({...t,op:e.op,outcome:o,code:n});if(e.sourceId!==this.sourceId)return r("SOURCE_UNBOUND");try{switch(e.op){case"watch":if(this.#s.watch(e.args.on),e.args.on&&this.#f===void 0)this.#w().catch((n)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} on a watcher's first subscribe failed: ${It(n)}`));return{...t,op:"watch",outcome:"applied",body:{on:this.#s.watching}};case"list":return{...t,op:"list",outcome:"applied",body:this.#O(e.args,t,await this.#k())};case"read":return{...t,op:"read",outcome:"applied",body:{observation:this.#C(await this.#k(),e.args.address)}};case"assign":return this.#e.log.error(`hightea-source: ${this.sourceId} cannot assign ${e.args.address}: a command source has no write`),r("SOURCE_UNAVAILABLE")}}catch(n){let o=It(n);if(this.#e.log.error(`hightea-source: ${e.op} on ${this.sourceId} failed: ${o}`),o.startsWith("ITEM_TOO_LARGE: "))return{...t,op:e.op,outcome:"refused",code:"ITEM_TOO_LARGE",item:o.slice(16)};return r("SOURCE_UNAVAILABLE","unknown")}}}function Yf(e,t=0){return e.flatMap((r)=>{if(t>=3||r.errors===void 0||r.errors.length===0)return[r];return r.errors.map((n)=>Yf(n,t+1)).reduce((n,o)=>o.length<n.length?o:n)})}var Ew="x-hightea/source/request";function Xf(e){let{log:t}=e,r=(i,a,c)=>i.send({jsonrpc:"2.0",id:a,error:{code:-32000,message:c}}),n=(i,a,c,d,u)=>o(i,a,c,{workspaceId:c.workspaceId,sourceId:c.sourceId,hostId:c.hostId,op:c.op,outcome:d,code:u}),o=(i,a,c,d)=>{let u={jsonrpc:"2.0",id:a,result:d};if(te(u)>cn)return t.error(`hightea-source: FRAME_TOO_LARGE for ${c.op} on ${c.sourceId}`),n(i,a,c,"unknown","FRAME_TOO_LARGE");return i.send(u)},s=async(i,a,c)=>{let{handler:d}=e;if(d===void 0)return n(i,a,c,"refused","SOURCE_UNAVAILABLE");let u;try{u=await d.handle(c)}catch{return t.error(`hightea-source: ${c.op} on ${c.sourceId} failed in its handler`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}let l=Bl.safeParse(u);if(!l.success){let p=Yf(l.error.issues).slice(0,3).map((f)=>`${f.path.join(".")||"answer"}: ${f.message}`).join("; ").slice(0,400);return t.error(`hightea-source: ${c.op} on ${c.sourceId} returned an answer outside its schema: ${p}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}if(l.data.workspaceId!==c.workspaceId||l.data.sourceId!==c.sourceId||l.data.hostId!==c.hostId||l.data.op!==c.op)return t.error(`hightea-source: ${c.op} on ${c.sourceId} was answered for another binding: ${l.data.op} on ${l.data.sourceId} in ${l.data.workspaceId} for ${l.data.hostId}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE");return o(i,a,c,l.data)};return{receive(i,a){if(i===null||typeof i!=="object"||i.method!==Ew)return!1;let{id:c,params:d}=i;if(typeof c!=="string"||!c.startsWith("source:")||c.length>300)return r(a,c??null,"OPERATION_SHAPE_INVALID"),!0;let u=Hl.safeParse(d);if(!u.success)return r(a,c,"OPERATION_NOT_ALLOWLISTED"),!0;let l=u.data;if(l.workspaceId!==e.workspaceId||l.hostId!==e.hostId||!e.bindings().has(l.sourceId))return n(a,c,l,"refused","SOURCE_UNBOUND"),!0;return s(a,c,l),!0}}}var Qf="x-hh-records";var eh="records",Iw=(e)=>{if(!e.startsWith("x-hh-records://"))return;let t=e.slice(15);if(t===""||t.includes("/")||t.includes("?"))return;return decodeURIComponent(t)};function th(e){let t=new Map,r,n=(a)=>{let c=t.get(a);if(c!==void 0)return c;let d=new Map;return t.set(a,d),d},o=(a)=>[...n(a).values()];return{channel:{grant:"records:read",snapshot:(a)=>{let c=Iw(a);if(c===void 0)return{sources:e.sources().map((p)=>({...p,count:n(p.source).size}))};let d=e.sources().find((l)=>l.source===c);if(d===void 0)return{source:c,epoch:"",records:[],error:`this host offers no source ${c}; x-hh-records:// lists the ones it does`};return{source:c,epoch:d.epoch,records:o(c)}},describe:()=>({title:"Records",description:"Each board source's records, one URI per source: x-hh-records://<sourceId>."}),operations:{operations:()=>[{id:Ie,kind:"records",label:"Assign",description:"Sets one record's owner, against the revision the caller read; a stale revision is refused and nothing is written.",scopes:["records"],grant:dn,status:"idle",input:{type:"object",properties:{address:{type:"string",minLength:1,maxLength:1024},ownerMemberId:{type:"string",minLength:1,maxLength:256},expectedOwner:{type:["string","null"]},ifRevision:{type:"string",minLength:1,maxLength:256},intentId:{type:"string",minLength:1,maxLength:256}},required:["address","ownerMemberId","ifRevision","intentId"],additionalProperties:!1}}],run:async(a,c,d,u,l)=>{if(a.id!==Ie)throw Error(`x-hh-records:// offers no operation ${a.id}; only ${Ie}`);let p=Gl.safeParse(d??{});if(!p.success)throw Error(`${Ie} on x-hh-records://: ${p.error.issues.map((f)=>`${f.path.join(".")} ${f.message}`).join("; ")}`);if(e.assign===void 0)throw Error("x-hh-records:// has no source to assign on this host");return e.assign(p.data,l)}}},bind:(a)=>{r=a},held:o,observe:(a,c)=>{let d=n(a);for(let u of c){if(u.op==="delete"){if(d.get(u.address)===void 0)continue;d.delete(u.address),i(a,{type:"x-hh-records/changed",source:a,deleted:!0,address:u.address,revision:u.revision});continue}let l={address:u.address,revision:u.revision,scope:u.scope??a,columns:u.columns??{},...u.extra===void 0?{}:{extra:u.extra}},p=d.get(u.address);if(p!==void 0&&p.revision===l.revision)continue;d.set(u.address,l),i(a,{type:"x-hh-records/changed",source:a,record:l,revision:l.revision})}}};function i(a,c){if(r===void 0)return;try{r.publish(`x-hh-records://${encodeURIComponent(a)}`,c)}catch(d){e.log.error(`hightea-records: publishing on x-hh-records://${a} failed: ${d instanceof Error?d.message:String(d)}`)}}}import{readFileSync as kw,renameSync as rh,unlinkSync as Rw,writeFileSync as nh}from"node:fs";import{join as Ss}from"node:path";var Cw="pipe-connected.json",oh="pipe-refused.json";function sh(e=new URL("./plugin.json",import.meta.url)){let t;try{t=JSON.parse(kw(e,"utf8"))}catch(r){return{error:`cannot read ${e.pathname}: ${r.message}`}}if(typeof t!=="object"||t===null||!("version"in t)||typeof t.version!=="string"||t.version==="")return{error:`${e.pathname} states no version`};return{version:t.version}}function ih(e,t,r=new Date){let n=Ss(e,Cw),o=`${n}.${process.pid}.tmp`;nh(o,`${JSON.stringify({version:t,at:r.toISOString()},null,2)}
78
- `,{mode:384}),rh(o,n)}function ah(e,t,r,n=new Date){let o=Ss(e,oh),s=`${o}.${process.pid}.tmp`,i={...r===void 0?{}:{version:r},at:n.toISOString(),error:t};nh(s,`${JSON.stringify(i,null,2)}
79
- `,{mode:384}),rh(s,o)}function ch(e){try{Rw(Ss(e,oh))}catch(t){if(t.code!=="ENOENT")throw t}}function kt(e){return{authorization:`Bearer ${e}`,"content-type":"application/json",accept:"application/json, text/event-stream"}}function Ow(e,t,r){if(r===void 0)return Error(`HOUSE_ANSWER_UNREADABLE ${e}: HTTP ${t.status} ${t.statusText===""?"":`${t.statusText} `}— the answer was not JSON`);let n=r.error?.message?.trim()??"",o=r.error?.code===void 0?"":` code ${r.error.code}`,s=/scope="([^"]*)"/u.exec(t.headers.get("www-authenticate")??"")?.[1],i=`HTTP ${t.status}${t.statusText===""?"":` ${t.statusText}`}`;return Error(`HOUSE_REFUSED ${e}: ${i}${o} — ${n===""?"the house gave no message":n}${s===void 0?"":` — the token needs ${s}`}`)}async function xn(e,t,r,n){let o=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:r,arguments:n}});for(let s=0;;s++){let i,a;try{i=await fetch(e,{method:"POST",headers:t,body:o}),a=await i.text()}catch(d){if(s>=1)throw Error(`HOUSE_UNREACHABLE: ${String(d)}`);continue}let c;try{c=JSON.parse(a)}catch{c=void 0}if(!i.ok||c===void 0||c.error!==void 0)throw Ow(r,i,c);return c}}function uh(e){let t=e??{},r=t.pageId;if(typeof r!=="string"||r.trim().length===0)throw Error("page_screenshot requires a non-empty string pageId");let n={pageId:r};for(let o of["version","width","height"]){let s=t[o];if(s===void 0)continue;if(typeof s!=="number"||!Number.isFinite(s))throw Error(`page_screenshot ${o} must be a number`);n[o]=s}if(t.format!==void 0){if(t.format!=="png"&&t.format!=="webp")throw Error("page_screenshot format is png or webp");n.format=t.format}return n}var ur=[{name:"hightea_thread_read",description:"You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",inputSchema:{type:"object",properties:{},additionalProperties:!1},readOnly:!0,toHouse:()=>({tool:"read_thread",args:{}})},{name:"hightea_thread_post",description:"Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",inputSchema:{type:"object",properties:{text:{type:"string"}},required:["text"],additionalProperties:!1},toHouse:(e)=>({tool:"post_message",args:{text:String(e.text??"")}})},{name:"hightea_page_read",description:"Read a Hightea page: its current version and content.",inputSchema:{type:"object",properties:{pageId:{type:"string"}},required:["pageId"],additionalProperties:!1},readOnly:!0,toHouse:(e)=>({tool:"page_read",args:{pageId:String(e.pageId??"")}})},{name:"hightea_page_write",description:"Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",inputSchema:{type:"object",properties:{pageId:{type:"string"},ifVersion:{type:"number"},content:{type:"string"}},required:["pageId","ifVersion","content"],additionalProperties:!1},toHouse:(e)=>{let t=e;return{tool:"page_write",args:{pageId:String(t.pageId??""),ifVersion:Number(t.ifVersion),content:String(t.content??"")}}}},{name:"hightea_page_screenshot",description:"Capture a Hightea page as a stored image at its live version, then mention the page in your reply so a person sees the capture on the page card. A version that is not the live one is refused by name.",inputSchema:{type:"object",properties:{pageId:{type:"string"},version:{type:"number",description:"Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)."},width:{type:"number",description:"Capture width in CSS pixels (16..2400)."},height:{type:"number",description:"Minimum capture height in CSS pixels (16..2400)."},format:{type:"string",enum:["png","webp"]}},required:["pageId"],additionalProperties:!1},toHouse:(e)=>({tool:"page_screenshot",args:uh(e)})}];function vs(e){return ur.find((t)=>t.name===e)}function dh(e){return vs(e)?.readOnly===!0?[ts]:[ts,af]}var lh="hightea";class Ve extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}function Tw(e){let t=e.startsWith("hightea://thread/")?e.slice(17):e,r=t.indexOf("?"),n=r<0?t:t.slice(0,r),[o,s,i]=n.split("/");if(!o||!s||i!==void 0)throw new Ve("THREAD_REF_INVALID",`${JSON.stringify(e)} names no room thread (expected hightea://thread/<roomId>/<rootMessageId>)`);return{roomId:o,rootMessageId:s}}function hh(e){let t=e.split("."),r={};if(t.length===3)try{let o=JSON.parse(Buffer.from(t[1]??"","base64url").toString("utf8"));if(o!==null&&typeof o==="object")r=o}catch{r={}}let n=typeof r.scope==="string"?r.scope.split(" ").filter((o)=>o!==""):void 0;return{token:e,...n===void 0?{}:{scopes:n}}}class xs{#e;#o;#r=new Map;#s;constructor(e){this.#e=e,this.#o=e.house??xn}listTools(){return ur.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.readOnly===!0?{annotations:{readOnlyHint:!0}}:{}}))}async handleRpc(e,t,r){let n=e.id??null;switch(e.method){case"initialize":return{jsonrpc:"2.0",id:n,result:{protocolVersion:String(e.params?.protocolVersion??"2025-06-18"),capabilities:{tools:{}},serverInfo:{name:"hightea",version:"0.1.0"}}};case"ping":return{jsonrpc:"2.0",id:n,result:null};case"tools/list":return{jsonrpc:"2.0",id:n,result:{tools:this.listTools()}};case"tools/call":{let o=e.params?.name;if(typeof o!=="string")return{jsonrpc:"2.0",id:n,error:{code:-32602,message:"tools/call needs a tool name"}};try{if(t===void 0)throw new Ve("TOKEN_EXPIRED_OR_REVOKED","no Hightea token on this request");let s=await this.callTool(o,e.params?.arguments??{},t,r??"");return{jsonrpc:"2.0",id:n,result:s}}catch(s){if(s instanceof Ve||s instanceof Z)return{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:s.message}],isError:!0}};return{jsonrpc:"2.0",id:n,error:{code:-32603,message:s instanceof Error?s.message:String(s)}}}}default:return{jsonrpc:"2.0",id:n,error:{code:-32601,message:`no method ${String(e.method)}`}}}}async callTool(e,t,r,n){let o=vs(e);if(o===void 0)throw new Ve("TOOL_UNKNOWN",`no Hightea tool is named ${JSON.stringify(e)}`);let{tool:s,args:i}=o.toHouse(t),a=kt(r.token);if(s==="read_thread"||s==="post_message"){let d=await this.#n(r.token),u=Tw(d.threadRef),l=`${u.roomId}/${u.rootMessageId}`,p=`${n}|${l}`;if(s==="read_thread"){await this.#c().admit({deliveryId:d.deliveryId,threadRef:l,triggeringMessageIds:d.triggeringMessageIds??[d.deliveryId]},r.token);let g=this.#r.get(p),w=await this.#o(this.#e.mcpUrl,a,"read_thread",{roomId:u.roomId,messageId:u.rootMessageId,...g===void 0?{}:{after:g}}),b=Aw(w),v=b.replies.at(-1)?.id;if(v!==void 0)this.#r.set(p,v);return{content:[{type:"text",text:JSON.stringify(await this.#c().view(l,b))}]}}let f=await this.#e.hostKey;if(f===void 0||f instanceof Error)throw new Ve("HOST_KEY_UNAVAILABLE",`this host cannot sign its agent's post${f instanceof Error?`: ${f.message}`:" (its ahpd names no configDir)"}`);let m=String(i.text??"");a["idempotency-key"]=d.deliveryId;let y=await this.#o(this.#e.mcpUrl,a,"post_message",{text:m,roomId:u.roomId,deliveryId:d.deliveryId,replyId:d.deliveryId,sig:Rf(f,{workspaceId:this.#e.workspaceId,roomId:u.roomId,rootMessageId:u.rootMessageId,authorMemberId:d.member,clientId:d.deliveryId,body:m})});return{content:[{type:"text",text:fh(y)}]}}let c=await this.#o(this.#e.mcpUrl,a,s,i);return{content:[{type:"text",text:fh(c)}]}}async#n(e){return(this.#e.turnFacts??((t)=>this.#l(t)))(e)}async#l(e){let t=await this.#o(this.#e.mcpUrl,kt(e),"read_thread",{limit:1});return $w(t)}#c(){if(this.#e.gate!==void 0)return this.#e.gate;if(this.#s===void 0)this.#s=new sr({configDir:this.#e.configDir,workspaceId:this.#e.workspaceId,ownAgents:this.#e.ownAgents,hostKey:this.#e.hostKey,readThread:async(e,t)=>(await this.#o(this.#e.mcpUrl,kt(e),"read_thread",t)).result?.structuredContent,now:this.#e.now??Date.now});return this.#s}}function Aw(e){let t=e.result?.structuredContent,r=t?.root,n=t?.replies;if(!(t!==void 0&&t!==null&&typeof t==="object"&&r!==void 0&&r!==null&&typeof r==="object"&&typeof r.id==="string"&&r.id!==""&&Array.isArray(n)&&n.every((s)=>s!==null&&typeof s==="object"&&typeof s.id==="string")))throw new Ve("READ_THREAD_INVALID","read_thread returned no valid root/replies paging result");return t}function fh(e){return(e.result?.content??[]).map((t)=>t.text).join(`
80
- `)}function $w(e){let r=e.result?.structuredContent?.turn,n=(d)=>{let u=r?.[d];return typeof u==="string"&&u!==""?u:void 0},o=r?.triggeringMessageIds,s=n("roomId"),i=n("messageId"),a=n("deliveryId"),c=n("memberId");if(s===void 0||i===void 0||a===void 0||c===void 0||!Array.isArray(o)||o.some((d)=>typeof d!=="string"))throw new Ve("TURN_FACTS_UNAVAILABLE","the house's answer for this bearer carries no turn (roomId, messageId, deliveryId, memberId, triggeringMessageIds); nothing room-shaped is served rather than inventing one");return{threadRef:`${s}/${i}`,deliveryId:a,member:c,triggeringMessageIds:o}}var ph=/^[A-Za-z0-9_.:-]{1,200}$/u,Pw=/^[A-Z_]{1,64}$/u;function mh(e){if(typeof e!=="object"||e===null)return null;if(e.method!=="x-hightea/source/declared")return null;let r=e.params;if(typeof r!=="object"||r===null)return{bound:[],refused:[],dropped:0};let n=(i)=>Array.isArray(i)?i.filter((a)=>typeof a==="string"&&ph.test(a)).slice(0,64):[],o=(i)=>{if(!Array.isArray(i))return[];let a=[];for(let c of i){if(typeof c!=="object"||c===null)continue;let{sourceId:d,code:u,message:l}=c;if(typeof d!=="string"||!ph.test(d)||typeof u!=="string"||!Pw.test(u))continue;if(a.push({sourceId:d,code:u,message:typeof l==="string"?l.slice(0,200):""}),a.length===64)break}return a},s=r.dropped;return{bound:n(r.bound),refused:o(r.refused),dropped:typeof s==="number"&&Number.isSafeInteger(s)&&s>=0?s:0}}function gh(e){let t=e.refused.length===0?"none refused":`${String(e.refused.length)} refused: ${e.refused.map((o)=>`${o.sourceId}=${o.code}${o.message===""?"":` (${o.message})`}`).join(", ")}`,r=e.bound.length===0?"none bound":`bound ${e.bound.join(", ")}`,n=e.dropped===0?"":`; ${String(e.dropped)} declared id(s) were not readable`;return`hightea-source: declared sources — ${r}; ${t}${n}`}import{createServer as Nw}from"node:http";function zw(e){let t=e.headers.get("authorization");if(t===null)return;let[r,...n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||n.length===0)return;let o=n.join(" ").trim();return o===""?void 0:o}function Mw(e){return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Hightea token required"}}),{status:401,headers:{"content-type":"application/json","www-authenticate":`Bearer resource_metadata="${e.resourceMetadataUrl}"`}})}function Dw(e,t,r){let n=e.requiredScopes?.(t)??[];if(n.length===0)return;let o=r.scopes??[],s=n.filter((i)=>!o.includes(i));if(s.length===0)return;return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32002,message:`insufficient_scope: ${s.join(" ")}`,error:"insufficient_scope"}}),{status:403,headers:{"content-type":"application/json","www-authenticate":`Bearer error="insufficient_scope", scope="${n.join(" ")}", resource_metadata="${e.resourceMetadataUrl}"`}})}var yh=4194304;function Lw(e,t){return async(r)=>{if(r.method!=="POST")return new Response("Method Not Allowed",{status:405,headers:{allow:"POST"}});let n;try{n=await r.json()}catch{return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"the frame is not JSON"}}),{status:400,headers:{"content-type":"application/json"}})}let o=zw(r),s=o===void 0?void 0:hh(o);if(n.method==="tools/call"){if(s===void 0)return Mw(t);let d=n.params?.name;if(typeof d==="string"){let u=Dw(t,d,s);if(u!==void 0)return u}}let i=r.headers.get("mcp-session-id")??(n.method==="initialize"?crypto.randomUUID():void 0),a=await e.handleRpc(n,s,i),c={"content-type":"application/json"};if(i!==void 0)c["mcp-session-id"]=i;return new Response(JSON.stringify(a),{status:200,headers:c})}}function _h(e,t){let r=t.hostname??"127.0.0.1",n=Lw(e,t),o=t.log??{error:(a)=>console.error(a)},s=Nw((a,c)=>void Uw(a,c,n,o)),i=new Promise((a,c)=>{let d=(u)=>c(u);s.once("error",d),s.listen(t.port,r,()=>{s.off("error",d),a()})});return i.catch(()=>{return}),{get url(){let a=s.address(),c=typeof a==="object"&&a!==null?a.port:t.port;return`http://${r}:${String(c)}/mcp`},ready:i,stop:()=>{s.closeAllConnections(),s.close()}}}async function Uw(e,t,r,n){try{let o=[],s=0;for await(let u of e){if(s+=u.length,s>yh){n.error(`hightea-mcp: a request body over ${String(yh)} bytes was refused (413)`),t.writeHead(413,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32600,message:"this server refuses a request body this large"}})),e.destroy();return}o.push(Buffer.from(u))}let i=new Headers;for(let[u,l]of Object.entries(e.headers)){if(l===void 0)continue;if(Array.isArray(l))for(let p of l)i.append(u,p);else i.set(u,l)}let a=Buffer.concat(o),c=await r(new Request(`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,{method:e.method??"GET",headers:i,...a.length===0?{}:{body:a}})),d=Buffer.from(await c.arrayBuffer());t.writeHead(c.status,Object.fromEntries(c.headers)),t.end(d)}catch(o){n.error(`hightea-mcp: a request could not be answered: ${o instanceof Error?o.name:typeof o}`),t.writeHead(500,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"the Hightea MCP server could not answer this request"}}))}}var Zw=(e)=>e.change.op==="delete"?{op:"delete",address:e.change.address,revision:`${e.position.epoch}#${e.position.ordinal}`}:{op:"upsert",address:e.change.row.address,revision:e.change.row.version,scope:e.change.row.scope,columns:e.change.row.columns,extra:e.change.row.extra},J="hightea-pipe",wh=`plugin:${J}`,jw=ur.map((e)=>e.name);function Fw(e){let t=[];return e.onMessage((r)=>{for(let n of t)n(r)}),{request:(r,n,o)=>e.request(r,n,o),notify:(r,n)=>e.notify(r,n),onMessage:(r)=>void t.push(r),close:()=>e.close()}}function Hw(e){let t=e instanceof Error?e.message:String(e);if(/wants to be signed in|set the authenticate option/u.test(t))return`AGENT_SIGN_IN_REQUIRED: sign in to ${/^([a-z][a-z0-9_-]{0,19}): /u.exec(t)?.[1]??"the agent backend"}`;if(e instanceof vt||/no matching configured ACP process authority/u.test(t))return"AGENT_START_REFUSED: the agent is not mapped on this host";if(/durable state|invalid durable|RECORD_READ_FAILED/u.test(t))return"HOST_STATE_UNREADABLE: the host's saved state could not be read";if(/answered protocol|initialize|local ahpd/u.test(t))return"AHPD_INIT_FAILED: the local daemon did not answer";return"AGENT_START_REFUSED: the agent could not start"}function Bw(e){let t=e.headers;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`${J}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);return t}function qw(e,t,r){let n=t.houseId;if(typeof t.workspaceId!=="string"||t.workspaceId===""){if(typeof n!=="string"||n==="")throw Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");t={...t,workspaceId:n}}let o=Bw(t),s=typeof t.pluginVersion==="string"&&t.pluginVersion!==""?{version:t.pluginVersion}:sh(),i="version"in s?s.version:void 0,a=(E)=>{if(e.configDir===void 0)return;try{ah(e.configDir,String(E),i)}catch(A){e.log.error(`${J}: could not record the refused start in ${e.configDir}: ${String(A)}`)}};if(!("version"in s))e.log.error(`${J}: hello will name no plugin version: ${s.error}`);let c=!1,d,u=!1,l,p,f=new Map,m,y=new Map,g,w=th({sources:()=>[...f.values()].map((E)=>({source:E.sourceId,epoch:E.epoch})),log:e.log,assign:async(E,A)=>{if(g===void 0)throw Error("records:assign: no source is listening on this host yet");return g(E,A)}});w.bind(e.registerChannel(Qf,w.channel)),e.registerGrants(eh,{title:"Board records",description:"Each board source's records as a channel: reading them, and assigning one record's owner against the revision that was read.",operations:[Ie]});let b=async()=>{if(u=!0,l!==void 0)clearTimeout(l);l=void 0,p?.close(),await Promise.all([...y.values()].map((E)=>E.stop?.()))};e.registerClose(b),e.registerClose(()=>m?.stop());let v=e.configDir===void 0?Promise.resolve(void 0):kf(e.configDir).catch((E)=>{let A=E instanceof Error?E:Error(String(E));return e.log.error(`${J}: ${A.message}`),A}),x=new sr({configDir:e.configDir,workspaceId:t.workspaceId,ownAgents:new Set(t.agents.map(([E])=>E)),hostKey:v,readThread:async(E,A)=>{if(t.mcpUrl===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host has no house MCP endpoint to read the ask from");return(await xn(t.mcpUrl,kt(E),"read_thread",A)).result?.structuredContent}}),I=r.askGate??x;if(e.registerSessionMeta===void 0)e.log.error(`${J}: this ahpd cannot publish a session's member (registerSessionMeta is absent), so Hightea page rows for its sessions will name none`);else e.registerSessionMeta("hh/agentMemberId",(E)=>d?.agentMemberOf(E));e.on("listening",()=>{if(u||l!==void 0||p!==void 0)return;l=setTimeout(()=>{l=void 0,C().catch((E)=>{e.log.error(`${J}: the host could not start its connections: ${String(E)}`),a(E)})},100)});async function C(){if(u)return;let E,A=o[hf]??o[pf]??"";f=new Map,y=new Map;for(let O of t.sources??[]){if(Jf(O)){y.set(O.sourceId,new ws({config:O,workspaceId:t.workspaceId,hostId:A,log:e.log,push:(N)=>Ne.sourcePush(N),...r.sourceChildren===void 0?{}:{run:r.sourceChildren.run}}));continue}if(O.kind!==void 0&&O.kind!=="km")throw Error(`${J}: the plugin entry names a source kind it cannot construct (${JSON.stringify(O.kind)}) for ${O.sourceId}, so this start is refused rather than offering it as km`);let z=new gs({config:O,workspaceId:t.workspaceId,hostId:A,log:e.log,...r.sourceChildren,onRecords:(N)=>w.observe(O.sourceId,N.map(Zw)),serviceIdentityEnvironment:(N)=>{if(typeof e.serviceIdentityEnvironment!=="function")throw Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");return e.serviceIdentityEnvironment(N)},push:(N)=>Ne.sourcePush(N)});f.set(O.sourceId,z),y.set(O.sourceId,z)}g=async(O,z)=>{let N=[...f.values()].find((Sh)=>O.address.startsWith(`issue:${Sh.sourceId}/`));if(N===void 0)return{outcome:"refused",code:"INVALID_ADDRESS"};let Rt=z?.owner?.id??`client:${z?.client??"unknown"}`;return N.assign(O,{workspaceId:t.workspaceId,sourceId:N.sourceId,hostId:A},Rt)};let q=new Set(y.keys()),ke=Xf({workspaceId:t.workspaceId,hostId:A,bindings:()=>q,log:e.log,handler:{handle:(O)=>{let z=y.get(O.sourceId);if(z===void 0)return e.log.error(`hightea-source: no handler for ${O.sourceId} although it is bound here`),Promise.resolve({workspaceId:O.workspaceId,sourceId:O.sourceId,hostId:O.hostId,op:O.op,outcome:"refused",code:"SOURCE_UNAVAILABLE"});return z.handle(O)}}}),re;if(t.hostToolsPort!==void 0&&t.mcpUrl!==void 0)try{let O=new xs({mcpUrl:t.mcpUrl,workspaceId:t.workspaceId,configDir:e.configDir,ownAgents:new Set(t.agents.map(([N])=>N)),hostKey:v,gate:I}),z=_h(O,{port:t.hostToolsPort,resourceMetadataUrl:`http://127.0.0.1:${String(t.hostToolsPort)}/.well-known/oauth-protected-resource`,log:e.log,requiredScopes:dh});if(await z.ready,u){z.stop();return}m=z,re={resource:z.url,name:lh}}catch(O){e.log.error(`${J}: the Hightea MCP server could not listen on 127.0.0.1:${String(t.hostToolsPort)} (another process may hold it), so no session is offered Hightea tools: ${String(O)}`)}let Ne=zf({dial:(O)=>{let z=new ki(t.cloudUrl,{headers:o,handshakeTimeout:15000,followRedirects:!1});return z.on("unexpected-response",(N,Rt)=>{O(Rt.statusCode??0),Rt.resume(),z.terminate()}),z},receive:(O,z)=>{let N=mh(O);if(N!==null){(e.log.info??e.log.error).call(e.log,gh(N));return}if(ke.receive(O,z))return;bn.fromCloud(O)},log:e.log,opened:(O)=>{E??=bn.start(J);let z=()=>{if(u)return;if(O.send({jsonrpc:"2.0",method:"x-hightea/hello",params:{channel:"ahp-root://",protocolVersions:[Ke],plugin:{name:J,version:i},ahpd:t.ahpdVersion,capabilities:[es],sources:[...y.keys()]}}),e.configDir!==void 0)try{ch(e.configDir)}catch(N){e.log.error(`${J}: could not clear the refused-start stamp in ${e.configDir}: ${String(N)}`)}if(c||i===void 0||e.configDir===void 0)return;c=!0;try{ih(e.configDir,i)}catch(N){e.log.error(`${J}: could not stamp this bundle's first connection in ${e.configDir}: ${String(N)}`)}};E.then(z,(N)=>{if(u)return;if(N instanceof vt&&f.size>0){e.log.error(`${J}: agent conversations unavailable; declared sources remain connected: ${String(N)}`),z();return}if(e.log.error(`${J}: could not start on the local ahpd: ${String(N)}`),a(N),O.close===void 0)e.log.error(`${J}: this connection cannot be closed by name`);else O.close(4001,Hw(N));b()})}});p=Ne;for(let O of y.values())O.start?.();let dr=Fw(e.connect()),bn=new ls(r.peer===void 0?dr:r.peer(dr),Ne,{workspaceId:t.workspaceId,agents:new Map(t.agents),owner:wh,tools:t.mcpUrl===void 0?[]:jw,...re===void 0?{}:{hostTools:re},startSession:(O,z)=>e.startSession(O,z),log:e.log,store:Nf(e.records("hightea"),wh,(O)=>e.sessionOwner(O),e.log,e.records("hightea/chats")),admitTurn:(O,z)=>I.admit(O,z),...i===void 0?{}:{handshake:{plugin:{name:J,version:i},ahpd:t.ahpdVersion,capabilities:[es],sources:()=>[...y.keys()]}}});d=bn}}function g0(e,t){qw(e,t,{})}export{ls as WakePipe,g0 as apply,qw as applyWith,J as name,uh as pageScreenshotArgs,Nf as recordsPipeStore,Fw as shareListener,Hw as startFailureReason};
74
+ `}var Kf=(e)=>Math.round(e/1048576);function J(e){if(e instanceof Error&&"code"in e&&typeof e.code==="string")return e.code;return e instanceof Error?e.message:String(e)}var ww=['command -v "$1" >/dev/null 2>&1 || { echo "hightea-spawn: ENOENT" >&2; exit 127; }',"exec 3<&0",'"$@" </dev/null 3<&- &',"c=$!","{ cat <&3 >/dev/null 2>&1; kill -KILL 0; } >/dev/null 2>&1 &","w=$!","exec 3<&-",'wait "$c"',"s=$?",'kill -KILL "$w" 2>/dev/null','exit "$s"'].join(`
75
+ `);function Wf(e,t){return J_("/bin/sh",["-c",ww,"hightea-spawn",...e],{stdio:["pipe","pipe","pipe"],detached:!0,...t===void 0?{}:{env:{...process.env,HAB_ID_TOKEN_FILE:t.HAB_ID_TOKEN_FILE}}})}function Jf(e,t,r){if(t!==127||!r.includes("hightea-spawn: ENOENT"))return;return Object.assign(Error(`spawn ${e} ENOENT`),{code:"ENOENT"})}function Et(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}var ys=(e,{timeoutMs:t,signal:r,env:n})=>new Promise((o,s)=>{let[i,...a]=e;if(i===void 0){s(Error("no command"));return}let c=Wf([i,...a],n),d="",u="",l=0,p,f=()=>{if(c.exitCode!==null||c.signalCode!==null)return;Et(c,"SIGTERM"),p??=setTimeout(()=>Et(c,"SIGKILL"),2000)},m=setTimeout(f,t);r.addEventListener("abort",f,{once:!0});let y=(w)=>(b)=>{if(l+=b.length,l>xn)return f();if(w==="out")d+=b;else u+=b};c.stdout.setEncoding("utf8").on("data",y("out")),c.stderr.setEncoding("utf8").on("data",y("err"));let g=!0;c.on("error",(w)=>{g=!1,clearTimeout(m),s(w)}),c.on("close",(w,b)=>{if(clearTimeout(m),p!==void 0)clearTimeout(p);if(Et(c,"SIGKILL"),r.removeEventListener("abort",f),!g)return;let v=Jf(i,w,u);if(v!==void 0)s(v);else o({pid:c.pid,code:b===null?w:null,stdout:d,stderr:u})})}),Sw=(e)=>{try{let t=JSON.parse(e);if(typeof t.ts!=="number"||!Number.isFinite(t.ts))return;if(t.source==="item-history")return;return{at:t.ts,source:typeof t.source==="string"?t.source:void 0}}catch{return}},vw=(e,{signal:t,onLine:r})=>new Promise((n,o)=>{let[s,...i]=e;if(s===void 0){o(Error("no command"));return}let a=Wf([s,...i]),c="",d,u=()=>{if(a.exitCode!==null||a.signalCode!==null)return;Et(a,"SIGTERM"),d??=setTimeout(()=>Et(a,"SIGKILL"),2000)};t.addEventListener("abort",u,{once:!0}),Y_({input:a.stdout}).on("line",(p)=>{if(p.trim()!=="")r(p)}),a.stderr.setEncoding("utf8").on("data",(p)=>{if(c.length<65536)c+=p});let l=!0;a.on("error",(p)=>{l=!1,o(p)}),a.on("close",(p,f)=>{if(d!==void 0)clearTimeout(d);if(Et(a,"SIGKILL"),t.removeEventListener("abort",u),!l)return;let m=Jf(s,p,c);if(m!==void 0)o(m);else n({pid:a.pid,code:f===null?p:null,stdout:"",stderr:c})})});import{createHash as xw}from"node:crypto";function Xf(e){return e.kind==="command"}var bw="all",Ew=60000,Yf=400,It=(e)=>e instanceof Error?e.message:String(e);function _s(e){let t=e.split(`
76
+ `).map((r)=>r.trim()).find((r)=>r!=="")??"";return t.length>Yf?`${t.slice(0,Yf)}…`:t}function Iw(e,t){if(typeof e.info==="function")e.info(t);else e.error(t)}class ws{sourceId;#e;#o;#r;#s;#n;#d;#c=0;#l;#u;#f=new Map;#a;#g=new AbortController;constructor(e){let{config:t}=e;if(t.command.length===0)throw Error(`the command source ${t.sourceId} declares no command`);if(t.key.trim()==="")throw Error(`the command source ${t.sourceId} declares an empty key field`);let r=t.intervalMs;if(!(Number.isFinite(r)&&r>0))throw Error(`the command source ${t.sourceId} needs a positive intervalMs, not ${String(r)}`);this.#e=e,this.sourceId=t.sourceId,this.#o=e.run??ys,this.#r=e.now??Date.now,this.#n=r,this.#d=e.childTimeoutMs??Ew,this.#s=new ar({sourceId:t.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(n)=>e.push(n),log:e.log,now:this.#r,...e.coalesceMs===void 0?{}:{coalesceMs:e.coalesceMs},onOmit:(n,o)=>e.log.error(`hightea-source: ${t.sourceId} row ${n} omitted: ${o}`),onOverflow:()=>this.#x()})}get epoch(){return this.#s.epoch}start(){this.#h()}async stop(){if(this.#g.abort(),this.#s.stop(),this.#a!==void 0)clearTimeout(this.#a),this.#a=void 0;await this.#u?.catch(()=>{return})}#h(){if(this.#g.signal.aborted)return;this.#w().catch((e)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} failed; keeping the last good dataset: ${It(e)}`)).finally(()=>this.#y())}#y(){if(this.#g.signal.aborted||this.#a!==void 0)return;this.#a=setTimeout(()=>{this.#a=void 0,this.#h()},this.#n)}async#w(){let e=this.#u;if(e!==void 0)return await e;let t=this.#v().finally(()=>{this.#u=void 0});return this.#u=t,await t}async#v(){let{config:e}=this.#e,t;try{t=await this.#o(e.command,{timeoutMs:this.#d,signal:this.#g.signal})}catch(n){throw Error(`the command ${e.command[0]??"(none)"} could not run: ${It(n)}`)}if(t.code!==0)throw Error(`the command exited ${t.code===null?"on a signal":t.code}${_s(t.stderr)===""?"":`: ${_s(t.stderr)}`}`);if(t.stderr.trim()!=="")Iw(this.#e.log,`hightea-source: ${this.sourceId} read warned: ${_s(t.stderr)}`);let r=this.#S(t.stdout);return this.#m(r)}#S(e){let{key:t}=this.#e.config,r=e.split(`
77
+ `),n=new Map;for(let[o,s]of r.entries()){let i=s.trim();if(i==="")continue;let a=`line ${o+1}`,c;try{c=JSON.parse(i)}catch(f){throw Error(`${a} is not JSON: ${It(f)}`)}if(c===null||typeof c!=="object"||Array.isArray(c))throw Error(`${a} is not an object`);let d=c;for(let f of Object.keys(d))if(f!==t&&f!=="columns"&&f!=="extra"&&f!=="version")throw Error(`${a} carries an unknown field "${f}"; a line is {${t}, columns, extra?, version?}`);let u=d[t];if(typeof u!=="string"||u.trim()==="")throw Error(`${a} has no "${t}"; every row needs an address`);let l=d.version??xw("sha256").update(JSON.stringify([d.columns??null,d.extra??null])).digest("hex");if(typeof l!=="string"||l==="")throw Error(`${a} carries an unusable "version"`);let p=wt.safeParse({address:u,version:l,scope:bw,columns:d.columns,extra:d.extra??null});if(!p.success){let f=p.error.issues.slice(0,3).map((m)=>`${m.path.join(".")||"row"}: ${m.message}`).join("; ");throw Error(`${a} is not a row: ${f}`)}if(n.has(u))throw Error(`${a} repeats the address ${u}; one line per row`);n.set(u,{key:u,row:p.data})}return n}#m(e){let t=this.#l,r=new Map,n=[],o=[...new Set([...e.keys(),...t?.byAddress.keys()??[]])].sort();for(let i of o){let a=e.get(i),c=t?.byAddress.get(i);if(a===void 0){n.push({position:this.#s.next(),change:{op:"delete",address:i}});continue}if(c===void 0||c.row.version!==a.row.version){let d=this.#s.next();n.push({position:d,change:{op:"upsert",row:a.row}}),r.set(i,{row:a.row,at:BigInt(d.ordinal)})}else r.set(i,{row:a.row,at:c.at})}this.#f=e;let s={generation:`${this.#s.epoch}.${++this.#c}`,epoch:this.#s.epoch,base:this.#s.ordinal,rows:[...r.values()],byAddress:r,at:this.#r()};return this.#l=s,this.#s.enqueue(n),s}#x(){let e=this.#f.size;if(e>_n){this.#e.log.error(`hightea-source: ${this.sourceId} holds ${e} rows, more than the ${_n} one push may carry; shorten the command's answer`);return}if(this.#l=void 0,e===0){this.#w().catch((t)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} after an overflow failed: ${It(t)}`));return}this.#m(this.#f)}async#k(){return this.#l??await this.#w()}#R(e,t){let r=e.byAddress.get(t);if(r===void 0)return{position:{epoch:e.epoch,ordinal:String(e.base)},change:{op:"delete",address:t}};return{position:{epoch:e.epoch,ordinal:String(r.at)},change:{op:"upsert",row:r.row}}}#O(e,t,r){let n=e.page===void 0?0:Number(e.page);if(!Number.isSafeInteger(n)||n<0||n>r.rows.length)throw Error(`the list token ${String(e.page)} does not name a page of this read`);let o=(c,d)=>({generation:r.generation,snapshot:r.generation,base:{epoch:r.epoch,ordinal:String(r.base)},rows:d,next:c>=r.rows.length?null:String(c),complete:c>=r.rows.length}),s=[],i=0,a=n;while(a<r.rows.length&&s.length<e.limit){let c=r.rows[a].row,d=te(c);if(te({...t,op:"list",outcome:"applied",body:o(a+1,[])})+i+d+s.length>ot){if(s.length===0)throw Error(`ITEM_TOO_LARGE: ${c.address}`);break}s.push(c),i+=d,a++}return o(a,s)}async handle(e){let t={workspaceId:e.workspaceId,sourceId:e.sourceId,hostId:e.hostId},r=(n,o="refused")=>({...t,op:e.op,outcome:o,code:n});if(e.sourceId!==this.sourceId)return r("SOURCE_UNBOUND");try{switch(e.op){case"watch":if(this.#s.watch(e.args.on),e.args.on&&this.#l===void 0)this.#w().catch((n)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} on a watcher's first subscribe failed: ${It(n)}`));return{...t,op:"watch",outcome:"applied",body:{on:this.#s.watching}};case"list":return{...t,op:"list",outcome:"applied",body:this.#O(e.args,t,await this.#k())};case"read":return{...t,op:"read",outcome:"applied",body:{observation:this.#R(await this.#k(),e.args.address)}};case"assign":return this.#e.log.error(`hightea-source: ${this.sourceId} cannot assign ${e.args.address}: a command source has no write`),r("SOURCE_UNAVAILABLE")}}catch(n){let o=It(n);if(this.#e.log.error(`hightea-source: ${e.op} on ${this.sourceId} failed: ${o}`),o.startsWith("ITEM_TOO_LARGE: "))return{...t,op:e.op,outcome:"refused",code:"ITEM_TOO_LARGE",item:o.slice(16)};return r("SOURCE_UNAVAILABLE","unknown")}}}function Qf(e,t=0){return e.flatMap((r)=>{if(t>=3||r.errors===void 0||r.errors.length===0)return[r];return r.errors.map((n)=>Qf(n,t+1)).reduce((n,o)=>o.length<n.length?o:n)})}var kw="x-hightea/source/request";function eh(e){let{log:t}=e,r=(i,a,c)=>i.send({jsonrpc:"2.0",id:a,error:{code:-32000,message:c}}),n=(i,a,c,d,u)=>o(i,a,c,{workspaceId:c.workspaceId,sourceId:c.sourceId,hostId:c.hostId,op:c.op,outcome:d,code:u}),o=(i,a,c,d)=>{let u={jsonrpc:"2.0",id:a,result:d};if(te(u)>cn)return t.error(`hightea-source: FRAME_TOO_LARGE for ${c.op} on ${c.sourceId}`),n(i,a,c,"unknown","FRAME_TOO_LARGE");return i.send(u)},s=async(i,a,c)=>{let{handler:d}=e;if(d===void 0)return n(i,a,c,"refused","SOURCE_UNAVAILABLE");let u;try{u=await d.handle(c)}catch{return t.error(`hightea-source: ${c.op} on ${c.sourceId} failed in its handler`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}let l=Bl.safeParse(u);if(!l.success){let p=Qf(l.error.issues).slice(0,3).map((f)=>`${f.path.join(".")||"answer"}: ${f.message}`).join("; ").slice(0,400);return t.error(`hightea-source: ${c.op} on ${c.sourceId} returned an answer outside its schema: ${p}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}if(l.data.workspaceId!==c.workspaceId||l.data.sourceId!==c.sourceId||l.data.hostId!==c.hostId||l.data.op!==c.op)return t.error(`hightea-source: ${c.op} on ${c.sourceId} was answered for another binding: ${l.data.op} on ${l.data.sourceId} in ${l.data.workspaceId} for ${l.data.hostId}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE");return o(i,a,c,l.data)};return{receive(i,a){if(i===null||typeof i!=="object"||i.method!==kw)return!1;let{id:c,params:d}=i;if(typeof c!=="string"||!c.startsWith("source:")||c.length>300)return r(a,c??null,"OPERATION_SHAPE_INVALID"),!0;let u=Hl.safeParse(d);if(!u.success)return r(a,c,"OPERATION_NOT_ALLOWLISTED"),!0;let l=u.data;if(l.workspaceId!==e.workspaceId||l.hostId!==e.hostId||!e.bindings().has(l.sourceId))return n(a,c,l,"refused","SOURCE_UNBOUND"),!0;return s(a,c,l),!0}}}var th="x-hh-records";var rh="records",Cw=(e)=>{if(!e.startsWith("x-hh-records://"))return;let t=e.slice(15);if(t===""||t.includes("/")||t.includes("?"))return;return decodeURIComponent(t)};function nh(e){let t=new Map,r,n=(a)=>{let c=t.get(a);if(c!==void 0)return c;let d=new Map;return t.set(a,d),d},o=(a)=>[...n(a).values()];return{channel:{grant:"records:read",snapshot:(a)=>{let c=Cw(a);if(c===void 0)return{sources:e.sources().map((p)=>({...p,count:n(p.source).size}))};let d=e.sources().find((l)=>l.source===c);if(d===void 0)return{source:c,epoch:"",records:[],error:`this host offers no source ${c}; x-hh-records:// lists the ones it does`};return{source:c,epoch:d.epoch,records:o(c)}},describe:()=>({title:"Records",description:"Each board source's records, one URI per source: x-hh-records://<sourceId>."}),operations:{operations:()=>[{id:Ie,kind:"records",label:"Assign",description:"Sets one record's owner, against the revision the caller read; a stale revision is refused and nothing is written.",scopes:["records"],grant:dn,status:"idle",input:{type:"object",properties:{address:{type:"string",minLength:1,maxLength:1024},ownerMemberId:{type:"string",minLength:1,maxLength:256},expectedOwner:{type:["string","null"]},ifRevision:{type:"string",minLength:1,maxLength:256},intentId:{type:"string",minLength:1,maxLength:256}},required:["address","ownerMemberId","ifRevision","intentId"],additionalProperties:!1}}],run:async(a,c,d,u,l)=>{if(a.id!==Ie)throw Error(`x-hh-records:// offers no operation ${a.id}; only ${Ie}`);let p=Gl.safeParse(d??{});if(!p.success)throw Error(`${Ie} on x-hh-records://: ${p.error.issues.map((f)=>`${f.path.join(".")} ${f.message}`).join("; ")}`);if(e.assign===void 0)throw Error("x-hh-records:// has no source to assign on this host");return e.assign(p.data,l)}}},bind:(a)=>{r=a},held:o,observe:(a,c)=>{let d=n(a);for(let u of c){if(u.op==="delete"){if(d.get(u.address)===void 0)continue;d.delete(u.address),i(a,{type:"x-hh-records/changed",source:a,deleted:!0,address:u.address,revision:u.revision});continue}let l={address:u.address,revision:u.revision,scope:u.scope??a,columns:u.columns??{},...u.extra===void 0?{}:{extra:u.extra}},p=d.get(u.address);if(p!==void 0&&p.revision===l.revision)continue;d.set(u.address,l),i(a,{type:"x-hh-records/changed",source:a,record:l,revision:l.revision})}}};function i(a,c){if(r===void 0)return;try{r.publish(`x-hh-records://${encodeURIComponent(a)}`,c)}catch(d){e.log.error(`hightea-records: publishing on x-hh-records://${a} failed: ${d instanceof Error?d.message:String(d)}`)}}}import{readFileSync as Rw,renameSync as oh,unlinkSync as Ow,writeFileSync as sh}from"node:fs";import{join as Ss}from"node:path";var Tw="pipe-connected.json",ih="pipe-refused.json";function ah(e=new URL("./plugin.json",import.meta.url)){let t;try{t=JSON.parse(Rw(e,"utf8"))}catch(r){return{error:`cannot read ${e.pathname}: ${r.message}`}}if(typeof t!=="object"||t===null||!("version"in t)||typeof t.version!=="string"||t.version==="")return{error:`${e.pathname} states no version`};return{version:t.version}}function ch(e,t,r=new Date){let n=Ss(e,Tw),o=`${n}.${process.pid}.tmp`;sh(o,`${JSON.stringify({version:t,at:r.toISOString()},null,2)}
78
+ `,{mode:384}),oh(o,n)}function uh(e,t,r,n=new Date){let o=Ss(e,ih),s=`${o}.${process.pid}.tmp`,i={...r===void 0?{}:{version:r},at:n.toISOString(),error:t};sh(s,`${JSON.stringify(i,null,2)}
79
+ `,{mode:384}),oh(s,o)}function dh(e){try{Ow(Ss(e,ih))}catch(t){if(t.code!=="ENOENT")throw t}}function kt(e){return{authorization:`Bearer ${e}`,"content-type":"application/json",accept:"application/json, text/event-stream"}}function Aw(e,t,r){if(r===void 0)return Error(`HOUSE_ANSWER_UNREADABLE ${e}: HTTP ${t.status} ${t.statusText===""?"":`${t.statusText} `}— the answer was not JSON`);let n=r.error?.message?.trim()??"",o=r.error?.code===void 0?"":` code ${r.error.code}`,s=/scope="([^"]*)"/u.exec(t.headers.get("www-authenticate")??"")?.[1],i=`HTTP ${t.status}${t.statusText===""?"":` ${t.statusText}`}`;return Error(`HOUSE_REFUSED ${e}: ${i}${o} — ${n===""?"the house gave no message":n}${s===void 0?"":` — the token needs ${s}`}`)}async function bn(e,t,r,n){let o=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:r,arguments:n}});for(let s=0;;s++){let i,a;try{i=await fetch(e,{method:"POST",headers:t,body:o}),a=await i.text()}catch(d){if(s>=1)throw Error(`HOUSE_UNREACHABLE: ${String(d)}`);continue}let c;try{c=JSON.parse(a)}catch{c=void 0}if(!i.ok||c===void 0||c.error!==void 0)throw Aw(r,i,c);return c}}function lh(e){let t=e??{},r=t.pageId;if(typeof r!=="string"||r.trim().length===0)throw Error("page_screenshot requires a non-empty string pageId");let n={pageId:r};for(let o of["version","width","height"]){let s=t[o];if(s===void 0)continue;if(typeof s!=="number"||!Number.isFinite(s))throw Error(`page_screenshot ${o} must be a number`);n[o]=s}if(t.format!==void 0){if(t.format!=="png"&&t.format!=="webp")throw Error("page_screenshot format is png or webp");n.format=t.format}return n}var ur=[{name:"hightea_thread_read",description:"You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",inputSchema:{type:"object",properties:{},additionalProperties:!1},readOnly:!0,toHouse:()=>({tool:"read_thread",args:{}})},{name:"hightea_thread_post",description:"Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",inputSchema:{type:"object",properties:{text:{type:"string"}},required:["text"],additionalProperties:!1},toHouse:(e)=>({tool:"post_message",args:{text:String(e.text??"")}})},{name:"hightea_page_read",description:"Read a Hightea page: its current version and content.",inputSchema:{type:"object",properties:{pageId:{type:"string"}},required:["pageId"],additionalProperties:!1},readOnly:!0,toHouse:(e)=>({tool:"page_read",args:{pageId:String(e.pageId??"")}})},{name:"hightea_page_write",description:"Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",inputSchema:{type:"object",properties:{pageId:{type:"string"},ifVersion:{type:"number"},content:{type:"string"}},required:["pageId","ifVersion","content"],additionalProperties:!1},toHouse:(e)=>{let t=e;return{tool:"page_write",args:{pageId:String(t.pageId??""),ifVersion:Number(t.ifVersion),content:String(t.content??"")}}}},{name:"hightea_page_screenshot",description:"Capture a Hightea page as a stored image at its live version, then mention the page in your reply so a person sees the capture on the page card. A version that is not the live one is refused by name.",inputSchema:{type:"object",properties:{pageId:{type:"string"},version:{type:"number",description:"Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)."},width:{type:"number",description:"Capture width in CSS pixels (16..2400)."},height:{type:"number",description:"Minimum capture height in CSS pixels (16..2400)."},format:{type:"string",enum:["png","webp"]}},required:["pageId"],additionalProperties:!1},toHouse:(e)=>({tool:"page_screenshot",args:lh(e)})}];function vs(e){return ur.find((t)=>t.name===e)}function fh(e){return vs(e)?.readOnly===!0?[ts]:[ts,uf]}var hh="hightea";class Ke extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}function $w(e){let t=e.startsWith("hightea://thread/")?e.slice(17):e,r=t.indexOf("?"),n=r<0?t:t.slice(0,r),[o,s,i]=n.split("/");if(!o||!s||i!==void 0)throw new Ke("THREAD_REF_INVALID",`${JSON.stringify(e)} names no room thread (expected hightea://thread/<roomId>/<rootMessageId>)`);return{roomId:o,rootMessageId:s}}function mh(e){let t=e.split("."),r={};if(t.length===3)try{let o=JSON.parse(Buffer.from(t[1]??"","base64url").toString("utf8"));if(o!==null&&typeof o==="object")r=o}catch{r={}}let n=typeof r.scope==="string"?r.scope.split(" ").filter((o)=>o!==""):void 0;return{token:e,...n===void 0?{}:{scopes:n}}}class xs{#e;#o;#r=new Map;#s;constructor(e){this.#e=e,this.#o=e.house??bn}listTools(){return ur.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.readOnly===!0?{annotations:{readOnlyHint:!0}}:{}}))}async handleRpc(e,t,r){let n=e.id??null;switch(e.method){case"initialize":return{jsonrpc:"2.0",id:n,result:{protocolVersion:String(e.params?.protocolVersion??"2025-06-18"),capabilities:{tools:{}},serverInfo:{name:"hightea",version:"0.1.0"}}};case"ping":return{jsonrpc:"2.0",id:n,result:null};case"tools/list":return{jsonrpc:"2.0",id:n,result:{tools:this.listTools()}};case"tools/call":{let o=e.params?.name;if(typeof o!=="string")return{jsonrpc:"2.0",id:n,error:{code:-32602,message:"tools/call needs a tool name"}};try{if(t===void 0)throw new Ke("TOKEN_EXPIRED_OR_REVOKED","no Hightea token on this request");let s=await this.callTool(o,e.params?.arguments??{},t,r??"");return{jsonrpc:"2.0",id:n,result:s}}catch(s){if(s instanceof Ke||s instanceof Z)return{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:s.message}],isError:!0}};return{jsonrpc:"2.0",id:n,error:{code:-32603,message:s instanceof Error?s.message:String(s)}}}}default:return{jsonrpc:"2.0",id:n,error:{code:-32601,message:`no method ${String(e.method)}`}}}}async callTool(e,t,r,n){let o=vs(e);if(o===void 0)throw new Ke("TOOL_UNKNOWN",`no Hightea tool is named ${JSON.stringify(e)}`);let{tool:s,args:i}=o.toHouse(t),a=kt(r.token);if(s==="read_thread"||s==="post_message"){let d=await this.#n(r.token),u=$w(d.threadRef),l=`${u.roomId}/${u.rootMessageId}`,p=`${n}|${l}`;if(s==="read_thread"){await this.#c().admit({deliveryId:d.deliveryId,threadRef:l,triggeringMessageIds:d.triggeringMessageIds??[d.deliveryId]},r.token);let g=this.#r.get(p),w=await this.#o(this.#e.mcpUrl,a,"read_thread",{roomId:u.roomId,messageId:u.rootMessageId,...g===void 0?{}:{after:g}}),b=Pw(w),v=b.replies.at(-1)?.id;if(v!==void 0)this.#r.set(p,v);return{content:[{type:"text",text:JSON.stringify(await this.#c().view(l,b))}]}}let f=await this.#e.hostKey;if(f===void 0||f instanceof Error)throw new Ke("HOST_KEY_UNAVAILABLE",`this host cannot sign its agent's post${f instanceof Error?`: ${f.message}`:" (its ahpd names no configDir)"}`);let m=String(i.text??"");a["idempotency-key"]=d.deliveryId;let y=await this.#o(this.#e.mcpUrl,a,"post_message",{text:m,roomId:u.roomId,deliveryId:d.deliveryId,replyId:d.deliveryId,sig:Of(f,{workspaceId:this.#e.workspaceId,roomId:u.roomId,rootMessageId:u.rootMessageId,authorMemberId:d.member,clientId:d.deliveryId,body:m})});return{content:[{type:"text",text:ph(y)}]}}let c=await this.#o(this.#e.mcpUrl,a,s,i);return{content:[{type:"text",text:ph(c)}]}}async#n(e){return(this.#e.turnFacts??((t)=>this.#d(t)))(e)}async#d(e){let t=await this.#o(this.#e.mcpUrl,kt(e),"read_thread",{limit:1});return Nw(t)}#c(){if(this.#e.gate!==void 0)return this.#e.gate;if(this.#s===void 0)this.#s=new sr({configDir:this.#e.configDir,workspaceId:this.#e.workspaceId,ownAgents:this.#e.ownAgents,hostKey:this.#e.hostKey,readThread:async(e,t)=>(await this.#o(this.#e.mcpUrl,kt(e),"read_thread",t)).result?.structuredContent,now:this.#e.now??Date.now});return this.#s}}function Pw(e){let t=e.result?.structuredContent,r=t?.root,n=t?.replies;if(!(t!==void 0&&t!==null&&typeof t==="object"&&r!==void 0&&r!==null&&typeof r==="object"&&typeof r.id==="string"&&r.id!==""&&Array.isArray(n)&&n.every((s)=>s!==null&&typeof s==="object"&&typeof s.id==="string")))throw new Ke("READ_THREAD_INVALID","read_thread returned no valid root/replies paging result");return t}function ph(e){return(e.result?.content??[]).map((t)=>t.text).join(`
80
+ `)}function Nw(e){let r=e.result?.structuredContent?.turn,n=(d)=>{let u=r?.[d];return typeof u==="string"&&u!==""?u:void 0},o=r?.triggeringMessageIds,s=n("roomId"),i=n("messageId"),a=n("deliveryId"),c=n("memberId");if(s===void 0||i===void 0||a===void 0||c===void 0||!Array.isArray(o)||o.some((d)=>typeof d!=="string"))throw new Ke("TURN_FACTS_UNAVAILABLE","the house's answer for this bearer carries no turn (roomId, messageId, deliveryId, memberId, triggeringMessageIds); nothing room-shaped is served rather than inventing one");return{threadRef:`${s}/${i}`,deliveryId:a,member:c,triggeringMessageIds:o}}var gh=/^[A-Za-z0-9_.:-]{1,200}$/u,zw=/^[A-Z_]{1,64}$/u;function yh(e){if(typeof e!=="object"||e===null)return null;if(e.method!=="x-hightea/source/declared")return null;let r=e.params;if(typeof r!=="object"||r===null)return{bound:[],refused:[],dropped:0};let n=(i)=>Array.isArray(i)?i.filter((a)=>typeof a==="string"&&gh.test(a)).slice(0,64):[],o=(i)=>{if(!Array.isArray(i))return[];let a=[];for(let c of i){if(typeof c!=="object"||c===null)continue;let{sourceId:d,code:u,message:l}=c;if(typeof d!=="string"||!gh.test(d)||typeof u!=="string"||!zw.test(u))continue;if(a.push({sourceId:d,code:u,message:typeof l==="string"?l.slice(0,200):""}),a.length===64)break}return a},s=r.dropped;return{bound:n(r.bound),refused:o(r.refused),dropped:typeof s==="number"&&Number.isSafeInteger(s)&&s>=0?s:0}}function _h(e){let t=e.refused.length===0?"none refused":`${String(e.refused.length)} refused: ${e.refused.map((o)=>`${o.sourceId}=${o.code}${o.message===""?"":` (${o.message})`}`).join(", ")}`,r=e.bound.length===0?"none bound":`bound ${e.bound.join(", ")}`,n=e.dropped===0?"":`; ${String(e.dropped)} declared id(s) were not readable`;return`hightea-source: declared sources — ${r}; ${t}${n}`}import{createServer as Mw}from"node:http";function Dw(e){let t=e.headers.get("authorization");if(t===null)return;let[r,...n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||n.length===0)return;let o=n.join(" ").trim();return o===""?void 0:o}function Lw(e){return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Hightea token required"}}),{status:401,headers:{"content-type":"application/json","www-authenticate":`Bearer resource_metadata="${e.resourceMetadataUrl}"`}})}function Uw(e,t,r){let n=e.requiredScopes?.(t)??[];if(n.length===0)return;let o=r.scopes??[],s=n.filter((i)=>!o.includes(i));if(s.length===0)return;return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32002,message:`insufficient_scope: ${s.join(" ")}`,error:"insufficient_scope"}}),{status:403,headers:{"content-type":"application/json","www-authenticate":`Bearer error="insufficient_scope", scope="${n.join(" ")}", resource_metadata="${e.resourceMetadataUrl}"`}})}var wh=4194304;function Zw(e,t){return async(r)=>{if(r.method!=="POST")return new Response("Method Not Allowed",{status:405,headers:{allow:"POST"}});let n;try{n=await r.json()}catch{return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"the frame is not JSON"}}),{status:400,headers:{"content-type":"application/json"}})}let o=Dw(r),s=o===void 0?void 0:mh(o);if(n.method==="tools/call"){if(s===void 0)return Lw(t);let d=n.params?.name;if(typeof d==="string"){let u=Uw(t,d,s);if(u!==void 0)return u}}let i=r.headers.get("mcp-session-id")??(n.method==="initialize"?crypto.randomUUID():void 0),a=await e.handleRpc(n,s,i),c={"content-type":"application/json"};if(i!==void 0)c["mcp-session-id"]=i;return new Response(JSON.stringify(a),{status:200,headers:c})}}function Sh(e,t){let r=t.hostname??"127.0.0.1",n=Zw(e,t),o=t.log??{error:(a)=>console.error(a)},s=Mw((a,c)=>void jw(a,c,n,o)),i=new Promise((a,c)=>{let d=(u)=>c(u);s.once("error",d),s.listen(t.port,r,()=>{s.off("error",d),a()})});return i.catch(()=>{return}),{get url(){let a=s.address(),c=typeof a==="object"&&a!==null?a.port:t.port;return`http://${r}:${String(c)}/mcp`},ready:i,stop:()=>{s.closeAllConnections(),s.close()}}}async function jw(e,t,r,n){try{let o=[],s=0;for await(let u of e){if(s+=u.length,s>wh){n.error(`hightea-mcp: a request body over ${String(wh)} bytes was refused (413)`),t.writeHead(413,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32600,message:"this server refuses a request body this large"}})),e.destroy();return}o.push(Buffer.from(u))}let i=new Headers;for(let[u,l]of Object.entries(e.headers)){if(l===void 0)continue;if(Array.isArray(l))for(let p of l)i.append(u,p);else i.set(u,l)}let a=Buffer.concat(o),c=await r(new Request(`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,{method:e.method??"GET",headers:i,...a.length===0?{}:{body:a}})),d=Buffer.from(await c.arrayBuffer());t.writeHead(c.status,Object.fromEntries(c.headers)),t.end(d)}catch(o){n.error(`hightea-mcp: a request could not be answered: ${o instanceof Error?o.name:typeof o}`),t.writeHead(500,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"the Hightea MCP server could not answer this request"}}))}}var Fw=(e)=>e.change.op==="delete"?{op:"delete",address:e.change.address,revision:`${e.position.epoch}#${e.position.ordinal}`}:{op:"upsert",address:e.change.row.address,revision:e.change.row.version,scope:e.change.row.scope,columns:e.change.row.columns,extra:e.change.row.extra},Y="hightea-pipe",vh=`plugin:${Y}`,Hw=ur.map((e)=>e.name);function Bw(e){let t=[];return e.onMessage((r)=>{for(let n of t)n(r)}),{request:(r,n,o)=>e.request(r,n,o),notify:(r,n)=>e.notify(r,n),onMessage:(r)=>void t.push(r),close:()=>e.close()}}function qw(e){let t=e instanceof Error?e.message:String(e);if(/wants to be signed in|set the authenticate option/u.test(t))return`AGENT_SIGN_IN_REQUIRED: sign in to ${/^([a-z][a-z0-9_-]{0,19}): /u.exec(t)?.[1]??"the agent backend"}`;if(e instanceof vt||/no matching configured ACP process authority/u.test(t))return"AGENT_START_REFUSED: the agent is not mapped on this host";if(/durable state|invalid durable|RECORD_READ_FAILED/u.test(t))return"HOST_STATE_UNREADABLE: the host's saved state could not be read";if(/answered protocol|initialize|local ahpd/u.test(t))return"AHPD_INIT_FAILED: the local daemon did not answer";return"AGENT_START_REFUSED: the agent could not start"}function Gw(e){let t=e.headers;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`${Y}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);return t}function Kw(e,t,r){let n=t.houseId;if(typeof t.workspaceId!=="string"||t.workspaceId===""){if(typeof n!=="string"||n==="")throw Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");t={...t,workspaceId:n}}let o=Gw(t),s=typeof t.pluginVersion==="string"&&t.pluginVersion!==""?{version:t.pluginVersion}:ah(),i="version"in s?s.version:void 0,a=(E)=>{if(e.configDir===void 0)return;try{uh(e.configDir,String(E),i)}catch(A){e.log.error(`${Y}: could not record the refused start in ${e.configDir}: ${String(A)}`)}};if(!("version"in s))e.log.error(`${Y}: hello will name no plugin version: ${s.error}`);let c=!1,d,u=!1,l,p,f=new Map,m,y=new Map,g,w=nh({sources:()=>[...f.values()].map((E)=>({source:E.sourceId,epoch:E.epoch})),log:e.log,assign:async(E,A)=>{if(g===void 0)throw Error("records:assign: no source is listening on this host yet");return g(E,A)}});w.bind(e.registerChannel(th,w.channel)),e.registerGrants(rh,{title:"Board records",description:"Each board source's records as a channel: reading them, and assigning one record's owner against the revision that was read.",operations:[Ie]});let b=async()=>{if(u=!0,l!==void 0)clearTimeout(l);l=void 0,p?.close(),await Promise.all([...y.values()].map((E)=>E.stop?.()))};e.registerClose(b),e.registerClose(()=>m?.stop());let v=e.configDir===void 0?Promise.resolve(void 0):Rf(e.configDir).catch((E)=>{let A=E instanceof Error?E:Error(String(E));return e.log.error(`${Y}: ${A.message}`),A}),x=new sr({configDir:e.configDir,workspaceId:t.workspaceId,ownAgents:new Set(t.agents.map(([E])=>E)),hostKey:v,readThread:async(E,A)=>{if(t.mcpUrl===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host has no house MCP endpoint to read the ask from");return(await bn(t.mcpUrl,kt(E),"read_thread",A)).result?.structuredContent}}),I=r.askGate??x;if(e.registerSessionMeta===void 0)e.log.error(`${Y}: this ahpd cannot publish a session's member (registerSessionMeta is absent), so Hightea page rows for its sessions will name none`);else e.registerSessionMeta("hh/agentMemberId",(E)=>d?.agentMemberOf(E));e.on("listening",()=>{if(u||l!==void 0||p!==void 0)return;l=setTimeout(()=>{l=void 0,R().catch((E)=>{e.log.error(`${Y}: the host could not start its connections: ${String(E)}`),a(E)})},100)});async function R(){if(u)return;let E,A=o[mf]??o[gf]??"";f=new Map,y=new Map;for(let T of t.sources??[]){if(Xf(T)){y.set(T.sourceId,new ws({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,push:(N)=>Ne.sourcePush(N),...r.sourceChildren===void 0?{}:{run:r.sourceChildren.run}}));continue}if(T.kind!==void 0&&T.kind!=="km")throw Error(`${Y}: the plugin entry names a source kind it cannot construct (${JSON.stringify(T.kind)}) for ${T.sourceId}, so this start is refused rather than offering it as km`);let L=new gs({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,...r.sourceChildren,onRecords:(N)=>w.observe(T.sourceId,N.map(Fw)),serviceIdentityEnvironment:(N)=>{if(typeof e.serviceIdentityEnvironment!=="function")throw Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");return e.serviceIdentityEnvironment(N)},push:(N)=>Ne.sourcePush(N)});f.set(T.sourceId,L),y.set(T.sourceId,L)}g=async(T,L)=>{let N=[...f.values()].find((xh)=>T.address.startsWith(`issue:${xh.sourceId}/`));if(N===void 0)return{outcome:"refused",code:"INVALID_ADDRESS"};let Ct=L?.owner?.id??`client:${L?.client??"unknown"}`;return N.assign(T,{workspaceId:t.workspaceId,sourceId:N.sourceId,hostId:A},Ct)};let q=new Set(y.keys()),ke=eh({workspaceId:t.workspaceId,hostId:A,bindings:()=>q,log:e.log,handler:{handle:(T)=>{let L=y.get(T.sourceId);if(L===void 0)return e.log.error(`hightea-source: no handler for ${T.sourceId} although it is bound here`),Promise.resolve({workspaceId:T.workspaceId,sourceId:T.sourceId,hostId:T.hostId,op:T.op,outcome:"refused",code:"SOURCE_UNAVAILABLE"});return L.handle(T)}}}),re;if(t.hostToolsPort!==void 0&&t.mcpUrl!==void 0)try{let T=new xs({mcpUrl:t.mcpUrl,workspaceId:t.workspaceId,configDir:e.configDir,ownAgents:new Set(t.agents.map(([N])=>N)),hostKey:v,gate:I}),L=Sh(T,{port:t.hostToolsPort,resourceMetadataUrl:`http://127.0.0.1:${String(t.hostToolsPort)}/.well-known/oauth-protected-resource`,log:e.log,requiredScopes:fh});if(await L.ready,u){L.stop();return}m=L,re={resource:L.url,name:hh}}catch(T){e.log.error(`${Y}: the Hightea MCP server could not listen on 127.0.0.1:${String(t.hostToolsPort)} (another process may hold it), so no session is offered Hightea tools: ${String(T)}`)}let Ne=Df({dial:(T)=>{let L=new ki(t.cloudUrl,{headers:o,handshakeTimeout:15000,followRedirects:!1});return L.on("unexpected-response",(N,Ct)=>{T(Ct.statusCode??0),Ct.resume(),L.terminate()}),L},receive:(T,L)=>{let N=yh(T);if(N!==null){(e.log.info??e.log.error).call(e.log,_h(N));return}if(ke.receive(T,L))return;En.fromCloud(T)},log:e.log,opened:(T)=>{E??=En.start(Y);let L=()=>{if(u)return;if(e.configDir!==void 0)try{dh(e.configDir)}catch(N){e.log.error(`${Y}: could not clear the refused-start stamp in ${e.configDir}: ${String(N)}`)}if(c||i===void 0||e.configDir===void 0)return;c=!0;try{ch(e.configDir,i)}catch(N){e.log.error(`${Y}: could not stamp this bundle's first connection in ${e.configDir}: ${String(N)}`)}};E.then(L,(N)=>{if(u)return;if(N instanceof vt&&f.size>0){e.log.error(`${Y}: agent conversations unavailable; declared sources remain connected: ${String(N)}`),L();return}if(e.log.error(`${Y}: could not start on the local ahpd: ${String(N)}`),a(N),T.close===void 0)e.log.error(`${Y}: this connection cannot be closed by name`);else T.close(4001,qw(N));b()})}});p=Ne;for(let T of y.values())T.start?.();let dr=Bw(e.connect()),En=new ls(r.peer===void 0?dr:r.peer(dr),Ne,{workspaceId:t.workspaceId,agents:new Map(t.agents),owner:vh,tools:t.mcpUrl===void 0?[]:Hw,...re===void 0?{}:{hostTools:re},startSession:(T,L)=>e.startSession(T,L),log:e.log,store:Mf(e.records("hightea"),vh,(T)=>e.sessionOwner(T),e.log,e.records("hightea/chats")),admitTurn:(T)=>I.admit(T),handshake:{...i===void 0?{}:{plugin:{name:Y,version:i}},ahpd:t.ahpdVersion,capabilities:[nf,of,ln],sources:()=>[...y.keys()]}});d=En}}function _0(e,t){Kw(e,t,{})}export{ls as WakePipe,_0 as apply,Kw as applyWith,Y as name,lh as pageScreenshotArgs,Mf as recordsPipeStore,Bw as shareListener,qw as startFailureReason};