@hallohuman/hightea 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +26 -26
- package/dist/{chunk-3w7svm2r.js → chunk-3pxbkmsq.js} +1 -1
- package/dist/{chunk-e9s05rg6.js → chunk-45fsefe1.js} +1 -1
- package/dist/{chunk-q669464j.js → chunk-76e2zy9j.js} +1 -1
- package/dist/{chunk-kq5y08g7.js → chunk-8td27k15.js} +4 -4
- package/dist/{chunk-axj8ef03.js → chunk-fjskavhw.js} +1 -1
- package/dist/chunk-jcgfe3z4.js +13 -0
- package/dist/{chunk-p1142ccr.js → chunk-m472zxhe.js} +1 -1
- package/dist/chunk-nqmxwka8.js +1 -0
- package/dist/plugin/plugin.json +2 -2
- package/dist/plugin/plugin.mjs +44 -44
- package/package.json +1 -1
- package/dist/chunk-88mhcx5q.js +0 -13
- package/dist/chunk-a1vwy98c.js +0 -1
package/dist/plugin/plugin.mjs
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
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
|
|
1
|
+
import{createRequire as Th}from"node:module";var Eh=Object.create;var{getPrototypeOf:Ih,defineProperty:Es,getOwnPropertyNames:kh}=Object;var Is=Object.prototype.hasOwnProperty;function Rh(e){return this[e]}var Ch,Oh,ze=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Ch??=new WeakMap:Oh??=new WeakMap,s=o.get(e);if(s)return s}r=e!=null?Eh(Ih(e)):{};let i=t||!e||!e.__esModule||!Is.call(e,"default")?Es(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of kh(e))if(!Is.call(i,a))Es(i,a,{get:Rh.bind(e,a),enumerable:!0})}if(n)o.set(e,i);return i};var se=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var q=Th(import.meta.url);var Re=se(function(tS,Cs){var ks=["nodebuffer","arraybuffer","fragments"],Rs=typeof Blob<"u";if(Rs)ks.push("blob");Cs.exports={BINARY_TYPES:ks,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Rs,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ct=se(function(rS,lr){var{EMPTY_BUFFER:Ah}=Re(),kn=Buffer[Symbol.species];function $h(e,t){if(e.length===0)return Ah;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 kn(r.buffer,r.byteOffset,n);return r}function Os(e,t,r,n,o){for(let s=0;s<o;s++)r[n+s]=e[s]^t[s&3]}function Ts(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function Ph(e){if(e.length===e.buffer.byteLength)return e.buffer;return e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Rn(e){if(Rn.readOnly=!0,Buffer.isBuffer(e))return e;let t;if(e instanceof ArrayBuffer)t=new kn(e);else if(ArrayBuffer.isView(e))t=new kn(e.buffer,e.byteOffset,e.byteLength);else t=Buffer.from(e),Rn.readOnly=!1;return t}lr.exports={concat:$h,mask:Os,toArrayBuffer:Ph,toBuffer:Rn,unmask:Ts};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)Os(t,r,n,o,s);else e.mask(t,r,n,o,s)},lr.exports.unmask=function(t,r){if(t.length<32)Ts(t,r);else e.unmask(t,r)}}catch(e){}});var Ns=se(function(nS,Ps){var As=Symbol("kDone"),Cn=Symbol("kRun");class $s{constructor(e){this[As]=()=>{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[As])}}}Ps.exports=$s});var ut=se(function(oS,Ls){var we=q("zlib"),hr=Ct(),Nh=Ns(),{kStatusCode:zs}=Re(),zh=Buffer[Symbol.species],Mh=Buffer.from([0,0,255,255]),pr=Symbol("permessage-deflate"),Ce=Symbol("total-length"),at=Symbol("callback"),Me=Symbol("buffers"),ct=Symbol("error"),fr;class Ms{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 Nh(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"?we.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=we.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[pr]=this,this._inflate[Ce]=0,this._inflate[Me]=[],this._inflate.on("error",Lh),this._inflate.on("data",Ds)}if(this._inflate[at]=r,this._inflate.write(e),t)this._inflate.write(Mh);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[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"?we.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=we.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Ce]=0,this._deflate[Me]=[],this._deflate.on("data",Dh)}this._deflate[at]=r,this._deflate.write(e),this._deflate.flush(we.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=hr.concat(this._deflate[Me],this._deflate[Ce]);if(t)o=new zh(o.buffer,o.byteOffset,o.length-4);if(this._deflate[at]=null,this._deflate[Ce]=0,this._deflate[Me]=[],t&&this.params[`${n}_no_context_takeover`])this._deflate.reset();r(null,o)})}}Ls.exports=Ms;function Dh(e){this[Me].push(e),this[Ce]+=e.length}function Ds(e){if(this[Ce]+=e.length,this[pr]._maxPayload<1||this[Ce]<=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][zs]=1009,this.removeListener("data",Ds),this.reset()}function Lh(e){if(this[pr]._inflate=null,this[ct]){this[at](this[ct]);return}e[zs]=1007,this[at](e)}});var dt=se(function(sS,mr){var{isUtf8:Us}=q("buffer"),{hasBlob:Uh}=Re(),Zh=[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 jh(e){return e>=1000&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3000&&e<=4999}function On(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 Fh(e){return Uh&&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:Fh,isValidStatusCode:jh,isValidUTF8:On,tokenChars:Zh};if(Us)mr.exports.isValidUTF8=function(e){return e.length<24?On(e):Us(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?On(t):e(t)}}catch(e){}});var An=se(function(iS,Hs){var{Writable:Hh}=q("stream"),yr=ut(),{BINARY_TYPES:Bh,EMPTY_BUFFER:Zs,kStatusCode:qh,kWebSocket:Gh}=Re(),{concat:Tn,toArrayBuffer:Kh,unmask:Vh}=Ct(),{isValidStatusCode:Wh,isValidUTF8:js}=dt(),gr=Buffer[Symbol.species];class Fs extends Hh{constructor(e={}){super();this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Bh[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[Gh]=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=Zs;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)Vh(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=Tn(r,t);else if(this._binaryType==="arraybuffer")n=Kh(Tn(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=Tn(r,t);if(!this._skipUTF8Validation&&!js(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,Zs),this.end();else{let r=e.readUInt16BE(0);if(!Wh(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&&!js(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[qh]=n,s}}Hs.exports=Fs});var Pn=se(function(cS,qs){var{Duplex:aS}=q("stream"),{randomFillSync:Jh}=q("crypto"),{types:{isUint8Array:Yh}}=q("util"),_r=ut(),{EMPTY_BUFFER:Xh,kWebSocket:Qh,NOOP:ep}=Re(),{isBlob:lt,isValidStatusCode:tp}=dt(),{mask:Bs,toBuffer:Ve}=Ct(),fe=Symbol("kByteLength"),rp=Buffer.alloc(4),We,ft=8192,ge=0,np=1,op=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=ge,this.onerror=ep,this[Qh]=void 0}static frame(e,t){let r,n=!1,o=2,s=!1;if(t.mask){if(r=t.maskBuffer||rp,t.generateMask)t.generateMask(r);else{if(ft===8192){if(We===void 0)We=Buffer.alloc(8192);Jh(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[fe]!==void 0)i=t[fe];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 Bs(e,r,c,o,i),[c];return Bs(e,r,e,0,i),[c,e]}close(e,t,r,n){let o;if(e===void 0)o=Xh;else if(typeof e!=="number"||!tp(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(Yh(t))o.set(t,2);else throw TypeError("Second argument must be a string or a Uint8Array")}let s={[fe]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==ge)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={[fe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};if(lt(e))if(this._state!==ge)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==ge)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={[fe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};if(lt(e))if(this._state!==ge)this.enqueue([this.getBlobData,e,!1,s,r]);else this.getBlobData(e,!1,s,r);else if(this._state!==ge)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={[fe]: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!==ge)this.enqueue([this.getBlobData,e,this._compress,c,r]);else this.getBlobData(e,this._compress,c,r);else if(this._state!==ge)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[fe],this._state=op,e.arrayBuffer().then((o)=>{if(this._socket.destroyed){let i=Error("The socket was closed while the blob was being read");process.nextTick($n,this,i,n);return}this._bufferedBytes-=r[fe];let s=Ve(o);if(!t)this._state=ge,this.sendFrame(De.frame(s,r),n),this.dequeue();else this.dispatch(s,t,r,n)}).catch((o)=>{process.nextTick(sp,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[fe],this._state=np,o.compress(e,r.fin,(s,i)=>{if(this._socket.destroyed){let a=Error("The socket was closed while data was being compressed");$n(this,a,n);return}this._bufferedBytes-=r[fe],this._state=ge,r.readOnly=!1,this.sendFrame(De.frame(i,r),n),this.dequeue()})}dequeue(){while(this._state===ge&&this._queue.length){let e=this._queue.shift();this._bufferedBytes-=e[3][fe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fe],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)}}qs.exports=De;function $n(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 sp(e,t,r){$n(e,t,r),e.onerror(t)}});var ei=se(function(uS,Qs){var{kForOnEventAttribute:Ot,kListener:Nn}=Re(),Gs=Symbol("kCode"),Ks=Symbol("kData"),Vs=Symbol("kError"),Ws=Symbol("kMessage"),Js=Symbol("kReason"),ht=Symbol("kTarget"),Ys=Symbol("kType"),Xs=Symbol("kWasClean");class Le{constructor(e){this[ht]=null,this[Ys]=e}get target(){return this[ht]}get type(){return this[Ys]}}Object.defineProperty(Le.prototype,"target",{enumerable:!0});Object.defineProperty(Le.prototype,"type",{enumerable:!0});class pt extends Le{constructor(e,t={}){super(e);this[Gs]=t.code===void 0?0:t.code,this[Js]=t.reason===void 0?"":t.reason,this[Xs]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Gs]}get reason(){return this[Js]}get wasClean(){return this[Xs]}}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[Vs]=t.error===void 0?null:t.error,this[Ws]=t.message===void 0?"":t.message}get error(){return this[Vs]}get message(){return this[Ws]}}Object.defineProperty(Tt.prototype,"error",{enumerable:!0});Object.defineProperty(Tt.prototype,"message",{enumerable:!0});class Sr extends Le{constructor(e,t={}){super(e);this[Ks]=t.data===void 0?null:t.data}get data(){return this[Ks]}}Object.defineProperty(Sr.prototype,"data",{enumerable:!0});var ip={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[Ot]&&o[Nn]===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[Nn]=t,r.once)this.once(e,n);else this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Nn]===t&&!r[Ot]){this.removeListener(e,r);break}}};Qs.exports={CloseEvent:pt,ErrorEvent:Tt,Event:Le,EventTarget:ip,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=se(function(dS,ti){var{tokenChars:At}=dt();function Se(e,t,r){if(e[t]===void 0)e[t]=[r];else e[t].push(r)}function ap(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)Se(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(Se(r,e.slice(c,u),!0),d===44)Se(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(Se(r,a,f),d===44)Se(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)Se(t,p,r);else{if(a===void 0)Se(r,p,!0);else if(n)Se(r,a,p.replace(/\\/g,""));else Se(r,a,p);Se(t,i,r)}return t}function cp(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(", ")}ti.exports={format:cp,parse:ap}});var kr=se(function(hS,mi){var up=q("events"),oi=q("https"),si=q("http"),Er=q("net"),ii=q("tls"),{randomBytes:dp,createHash:lp}=q("crypto"),{Duplex:lS,Readable:fS}=q("stream"),{URL:zn}=q("url"),ee=ut(),fp=An(),hp=Pn(),{isBlob:pp}=dt(),{BINARY_TYPES:ri,CLOSE_TIMEOUT:mp,EMPTY_BUFFER:xr,GUID:gp,kForOnEventAttribute:Mn,kListener:yp,kStatusCode:_p,kWebSocket:K,NOOP:ai}=Re(),{EventTarget:{addEventListener:wp,removeEventListener:Sp}}=ei(),{format:vp,parse:xp}=vr(),{toBuffer:bp}=Ct(),ci=Symbol("kAborted"),Dn=[8,13],Oe=["CONNECTING","OPEN","CLOSING","CLOSED"],Ep=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class T extends up{constructor(e,t,r){super();if(this._binaryType=ri[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];ui(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(!ri.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 fp({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 hp(e,this._extensions,r.generateMask);if(this._receiver=n,this._sender=o,this._socket=e,n[K]=this,o[K]=this,e[K]=this,n.on("conclude",Rp),n.on("drain",Cp),n.on("error",Op),n.on("message",Tp),n.on("ping",Ap),n.on("pong",$p),o.onerror=Pp,e.setTimeout)e.setTimeout(0);if(e.setNoDelay)e.setNoDelay();if(t.length>0)e.unshift(t);e.on("close",fi),e.on("data",Ir),e.on("end",hi),e.on("error",pi),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[ee.extensionName])this._extensions[ee.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){ie(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()}),li(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){Ln(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){Ln(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){Ln(this,e,r);return}let n={binary:typeof e!=="string",mask:!this._isServer,compress:!0,fin:!0,...t};if(!this._extensions[ee.extensionName])n.compress=!1;this._sender.send(e||xr,n,r)}terminate(){if(this.readyState===T.CLOSED)return;if(this.readyState===T.CONNECTING){ie(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[Mn])return t[yp];return null},set(t){for(let r of this.listeners(e))if(r[Mn]){this.removeListener(e,r);break}if(typeof t!=="function")return;this.addEventListener(e,t,{[Mn]:!0})}})});T.prototype.addEventListener=wp;T.prototype.removeEventListener=Sp;mi.exports=T;function ui(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:mp,protocolVersion:Dn[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,!Dn.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Dn.join(", ")})`);let s;if(t instanceof zn)s=t;else try{s=new zn(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 g=SyntaxError(c);if(e._redirects===0)throw g;else{br(e,g);return}}let d=i?443:80,u=dp(16).toString("base64"),l=i?oi.request:si.request,p=new Set,f;if(o.createConnection=o.createConnection||(i?kp:Ip),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 ee({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=vp({[ee.extensionName]:f.offer()});if(r.length){for(let g of r){if(typeof g!=="string"||!Ep.test(g)||p.has(g))throw SyntaxError("An invalid or duplicated subprotocol was specified");p.add(g)}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 g=o.path.split(":");o.socketPath=g[0],o.path=g[1]}let y;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?o.socketPath:s.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[m,_]of Object.entries(g))n.headers[m.toLowerCase()]=_}else if(e.listenerCount("redirect")===0){let g=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;if(!g||e._originalSecure&&!i){if(delete o.headers.authorization,delete o.headers.cookie,!g)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(y=e._req=l(o),e._redirects)e.emit("redirect",e.url,y)}else y=e._req=l(o);if(o.timeout)y.on("timeout",()=>{ie(e,y,"Opening handshake has timed out")});if(y.on("error",(g)=>{if(y===null||y[ci])return;y=e._req=null,br(e,g)}),y.on("response",(g)=>{let m=g.headers.location,_=g.statusCode;if(m&&o.followRedirects&&_>=300&&_<400){if(++e._redirects>o.maxRedirects){ie(e,y,"Maximum redirects exceeded");return}y.abort();let x;try{x=new zn(m,t)}catch(v){let b=SyntaxError(`Invalid URL: ${m}`);br(e,b);return}ui(e,x,r,n)}else if(!e.emit("unexpected-response",y,g))ie(e,y,`Unexpected server response: ${g.statusCode}`)}),y.on("upgrade",(g,m,_)=>{if(e.emit("upgrade",g),e.readyState!==T.CONNECTING)return;y=e._req=null;let x=g.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ie(e,m,"Invalid Upgrade header");return}let v=lp("sha1").update(u+gp).digest("base64");if(g.headers["sec-websocket-accept"]!==v){ie(e,m,"Invalid Sec-WebSocket-Accept header");return}let b=g.headers["sec-websocket-protocol"],E;if(b!==void 0){if(!p.size)E="Server sent a subprotocol but none was requested";else if(!p.has(b))E="Server sent an invalid subprotocol"}else if(p.size)E="Server sent no subprotocol";if(E){ie(e,m,E);return}if(b)e._protocol=b;let C=g.headers["sec-websocket-extensions"];if(C!==void 0){if(!f){ie(e,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=xp(C)}catch(G){ie(e,m,"Invalid Sec-WebSocket-Extensions header");return}let O=Object.keys(I);if(O.length!==1||O[0]!==ee.extensionName){ie(e,m,"Server indicated an extension that was not requested");return}try{f.accept(I[ee.extensionName])}catch(G){ie(e,m,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ee.extensionName]=f}e.setSocket(m,_,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest)o.finishRequest(y,e);else y.end()}function br(e,t){e._readyState=T.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function Ip(e){return e.path=e.socketPath,Er.connect(e)}function kp(e){if(e.path=void 0,!e.servername&&e.servername!=="")e.servername=Er.isIP(e.host)?"":e.host;return ii.connect(e)}function ie(e,t,r){e._readyState=T.CLOSING;let n=Error(r);if(Error.captureStackTrace(n,ie),t.setHeader){if(t[ci]=!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 Ln(e,t,r){if(t){let n=pp(t)?t.size:bp(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 Rp(e,t){let r=this[K];if(r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[K]===void 0)return;if(r._socket.removeListener("data",Ir),process.nextTick(di,r._socket),e===1005)r.close();else r.close(e,t)}function Cp(){let e=this[K];if(!e.isPaused)e._socket.resume()}function Op(e){let t=this[K];if(t._socket[K]!==void 0)t._socket.removeListener("data",Ir),process.nextTick(di,t._socket),t.close(e[_p]);if(!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function ni(){this[K].emitClose()}function Tp(e,t){this[K].emit("message",e,t)}function Ap(e){let t=this[K];if(t._autoPong)t.pong(e,!this._isServer,ai);t.emit("ping",e)}function $p(e){this[K].emit("pong",e)}function di(e){e.resume()}function Pp(e){let t=this[K];if(t.readyState===T.CLOSED)return;if(t.readyState===T.OPEN)t._readyState=T.CLOSING,li(t);if(this._socket.end(),!t._errorEmitted)t._errorEmitted=!0,t.emit("error",e)}function li(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fi(){let e=this[K];if(this.removeListener("close",fi),this.removeListener("data",Ir),this.removeListener("end",hi),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[K]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted)e.emitClose();else e._receiver.on("error",ni),e._receiver.on("finish",ni)}function Ir(e){if(!this[K]._receiver.write(e))this.pause()}function hi(){let e=this[K];e._readyState=T.CLOSING,e._receiver.end(),this.end()}function pi(){let e=this[K];if(this.removeListener("error",pi),this.on("error",ai),e)e._readyState=T.CLOSING,this.destroy()}});var wi=se(function(mS,_i){var pS=kr(),{Duplex:Np}=q("stream");function gi(e){e.emit("close")}function zp(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function yi(e){if(this.removeListener("error",yi),this.destroy(),this.listenerCount("error")===0)this.emit("error",e)}function Mp(e,t){let r=!0,n=new Np({...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(gi,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(gi,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",zp),n.on("error",yi),n}_i.exports=Mp});var Un=se(function(gS,Si){var{tokenChars:Dp}=dt();function Lp(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&&Dp[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}Si.exports={parse:Lp}});var Ii=se(function(_S,Ei){var Up=q("events"),Ue=q("http"),{Duplex:yS}=q("stream"),{createHash:Zp}=q("crypto"),Rr=vr(),ae=ut(),xi=Un(),jp=kr(),{CLOSE_TIMEOUT:Fp,GUID:Hp,kWebSocket:Bp}=Re(),qp=/^[+/0-9A-Za-z]{22}==$/;class bi extends Up{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:Fp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:jp,...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=Gp(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",vi);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||!qp.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=xi.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 ae({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Rr.parse(d);if(p[ae.extensionName])l.accept(p[ae.extensionName]),u[ae.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,y,g)=>{if(!p)return Pt(t,f||401,y,g);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[Bp])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: ${Zp("sha1").update(t+Hp).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[ae.extensionName]){let u=e[ae.extensionName].params,l=Rr.format({[ae.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",
|
|
3
|
+
`)),o.removeListener("error",vi),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)}}Ei.exports=bi;function Gp(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 vi(){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 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(`
|
|
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 Kp=ze(wi(),1),Vp=ze(vr(),1),Wp=ze(ut(),1),Jp=ze(An(),1),Yp=ze(Pn(),1),Xp=ze(Un(),1),ki=ze(kr(),1),Qp=ze(Ii(),1);var Ri=ki.default;var Ci;(function(e){e.Snapshot="snapshot",e.Replay="replay",e.Live="live"})(Ci||(Ci={}));var Oi;(function(e){e.Enabled="enabled",e.Disabled="disabled",e.Unconfigured="unconfigured"})(Oi||(Oi={}));var Zn;(function(e){e.Creating="creating",e.Ready="ready",e.Failed="failed"})(Zn||(Zn={}));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 Ti;(function(e){e.Automation="automation"})(Ti||(Ti={}));var jn;(function(e){e.ChatInput="chatInput",e.ToolConfirmation="toolConfirmation",e.ToolClientExecution="toolClientExecution",e.ToolAuthentication="toolAuthentication"})(jn||(jn={}));var Fn;(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"})(Fn||(Fn={}));var Ai;(function(e){e.Global="global",e.Workspace="workspace",e.Session="session"})(Ai||(Ai={}));var $i;(function(e){e.Loading="loading",e.Loaded="loaded",e.Degraded="degraded",e.Error="error"})($i||($i={}));var Hn;(function(e){e.Starting="starting",e.Ready="ready",e.AuthRequired="authRequired",e.Error="error",e.Stopped="stopped"})(Hn||(Hn={}));var Pi;(function(e){e.Required="required",e.Expired="expired",e.InsufficientScope="insufficientScope"})(Pi||(Pi={}));var Ni;(function(e){e.Shell="shell",e.Subagent="subagent"})(Ni||(Ni={}));var zi;(function(e){e.User="user",e.Fork="fork",e.SideChat="sideChat",e.Tool="tool"})(zi||(zi={}));var Mi;(function(e){e.Full="full",e.ReadOnly="read-only",e.Hidden="hidden"})(Mi||(Mi={}));var Bn;(function(e){e.Steering="steering",e.Queued="queued"})(Bn||(Bn={}));var Di;(function(e){e.Accept="accept",e.Decline="decline",e.Cancel="cancel"})(Di||(Di={}));var Li;(function(e){e.Text="text",e.Number="number",e.Integer="integer",e.Boolean="boolean",e.SingleSelect="single-select",e.MultiSelect="multi-select"})(Li||(Li={}));var Ui;(function(e){e.Text="text",e.Number="number",e.Boolean="boolean",e.Selected="selected",e.SelectedMany="selected-many"})(Ui||(Ui={}));var Zi;(function(e){e.Draft="draft",e.Submitted="submitted",e.Skipped="skipped"})(Zi||(Zi={}));var qn;(function(e){e.Complete="complete",e.Cancelled="cancelled",e.Error="error"})(qn||(qn={}));var ji;(function(e){e.Simple="simple",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.Annotations="annotations",e.Chat="chat"})(ji||(ji={}));var Fi;(function(e){e.User="user",e.Agent="agent",e.Tool="tool",e.Automation="automation",e.SystemNotification="systemNotification"})(Fi||(Fi={}));var Gn;(function(e){e.Markdown="markdown",e.ContentRef="contentRef",e.ToolCall="toolCall",e.Reasoning="reasoning",e.SystemNotification="systemNotification",e.InputRequest="inputRequest",e.Error="error"})(Gn||(Gn={}));var Kn;(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"})(Kn||(Kn={}));var Vn;(function(e){e.NotNeeded="not-needed",e.UserAction="user-action",e.Setting="setting"})(Vn||(Vn={}));var Hi;(function(e){e.Judge="judge"})(Hi||(Hi={}));var Bi;(function(e){e.Loading="loading",e.Complete="complete"})(Bi||(Bi={}));var Wn;(function(e){e.Denied="denied",e.Skipped="skipped",e.ResultDenied="result-denied"})(Wn||(Wn={}));var qi;(function(e){e.Approve="approve",e.Deny="deny"})(qi||(qi={}));var Jn;(function(e){e.Client="client",e.MCP="mcp"})(Jn||(Jn={}));var Gi;(function(e){e.Text="text",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.FileEdit="fileEdit",e.Terminal="terminal",e.Subagent="subagent"})(Gi||(Gi={}));var Yn;(function(e){e.Running="running",e.Exited="exited"})(Yn||(Yn={}));var Ki;(function(e){e.Client="client",e.Session="session"})(Ki||(Ki={}));var Xn;(function(e){e.Computing="computing",e.Recomputing="recomputing",e.Ready="ready",e.Error="error"})(Xn||(Xn={}));var Vi;(function(e){e[e.Editing=1]="Editing"})(Vi||(Vi={}));var Qn;(function(e){e.Idle="idle",e.Running="running",e.Error="error",e.Disabled="disabled"})(Qn||(Qn={}));var Wi;(function(e){e.Changeset="changeset",e.Resource="resource",e.Range="range"})(Wi||(Wi={}));var Ji;(function(e){e.Added="added",e.Updated="updated",e.Deleted="deleted"})(Ji||(Ji={}));var Yi;(function(e){e.Update="update",e.Remove="remove",e.Run="run"})(Yi||(Yi={}));var Xi;(function(e){e.Skip="skip",e.RunOnce="runOnce"})(Xi||(Xi={}));var Qi;(function(e){e.Schedule="schedule",e.Event="event"})(Qi||(Qi={}));var ea;(function(e){e.AfterRuns="afterRuns",e.AfterDate="afterDate"})(ea||(ea={}));var ta;(function(e){e.Pending="pending",e.Running="running",e.Completed="completed",e.Failed="failed",e.Cancelled="cancelled"})(ta||(ta={}));var ra;(function(e){e.Manual="manual",e.Trigger="trigger"})(ra||(ra={}));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 em={[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 tm=["channel/credit","tcp/reset","unsubscribe"],ov=new Set(tm);var na;(function(e){e.Posix="posix",e.Windows="windows"})(na||(na={}));var oa;(function(e){e.Replay="replay",e.Snapshot="snapshot"})(oa||(oa={}));var sa;(function(e){e.Base64="base64",e.Utf8="utf-8"})(sa||(sa={}));var ia;(function(e){e.Truncate="truncate",e.Append="append",e.Insert="insert"})(ia||(ia={}));var aa;(function(e){e.File="file",e.Directory="directory",e.Symlink="symlink"})(aa||(aa={}));var ca;(function(e){e.McpServer="mcpServer"})(ca||(ca={}));var ua;(function(e){e.UserMessage="userMessage"})(ua||(ua={}));var da;(function(e){e.Fork="fork",e.SideChat="sideChat"})(da||(da={}));var la;(function(e){e.Session="session",e.NewSession="newSession"})(la||(la={}));var fa;(function(e){e.Resource="resource",e.Range="range"})(fa||(fa={}));var ha;(function(e){e.Required="required",e.Expired="expired"})(ha||(ha={}));var Av=Object.freeze(["1.0.0","0.9.0"]);var $v={[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 to(e,t="|"){return e.map((r)=>oo(r)).join(t)}function Mt(e,t){if(typeof t==="bigint")return t.toString();return t}class pa{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 pa(e)}function ma(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 ga(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 he(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 ya(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return he(this,t,n),n},enumerable:!0,configurable:!0})}function _a(e,t,r){if(t in e)he(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)ya(e,s,()=>{let a=t._zod.def.shape[s];return n?n(a,s):a});else _a(e,s,n?n(i.value,s):i.value)}}function pm(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)ya(e,r,()=>t[r]);else _a(e,r,n.value)}}function ce(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function wa(e){return JSON.stringify(e)}function Sa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ro="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function mt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var va=Dt(()=>{if(te.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 no(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 xa=new Set(["string","number","symbol"]);function Fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(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 oo(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function ba(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]}))(),so={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function mm(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)),ve(e,ce(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 gm(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))),ve(e,ce(r,{shape:i,checks:[]}))}function ym(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 ve(e,ce(e._zod.def,{shape:Ea(e,t)}))}function Ea(e,t){let r={};return Ye(r,e,Reflect.ownKeys(Te(e))),pm(r,t),r}function _m(e,t){if(!Xe(t))throw Error("Invalid input to safeExtend: expected a plain object");return ve(e,ce(e._zod.def,{shape:Ea(e,t)}))}function wm(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=ce(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ve(e,n)}function Ia(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}))),ve(t,ce(t._zod.def,{shape:c,checks:[]}))}function Sm(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})),ve(t,ce(t._zod.def,{shape:o}))}function pe(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 ka(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 xe(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 io(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 be(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 vm=/[\uD800-\uDBFF]/;function Pr(e){let t=e.length;if(!vm.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 Ra(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 xm(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 Oa(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 xm(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 bm(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var eo,je=!1,Em={configurable:!0,get(){je=!0;return}};function P(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&eo!==e._zod){eo=void 0;return}eo=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,Em);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 Im(e,t,r,n){let o=bm(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 km="~constantCatch";function Ta(e){let t=()=>e;return t[km]=!0,t}var Aa;var ao={value:void 0,enumerable:!1},$a="captureStackTrace"in Error?Error:null;function Rm(e){let t=$a;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return $a=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function w(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){ao.value=new s(f);try{Object.defineProperty(p,"_zod",ao)}finally{ao.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,f),a){let g=Object.getPrototypeOf(p),m=p._zod.constr.prototype,_=g;while(_&&_!==m)_=Object.getPrototypeOf(_);let x=_??g;if(!a.has(x))a.add(x),Ca(x,i)}let y=l.prototype;for(let g in y){if(!Object.prototype.hasOwnProperty.call(y,g))continue;if(!(g in p))p[g]=y[g].bind(p)}}let d=n?.Parent??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function l(p){let f=n?.Parent?Rm(u):this;c(f,p);let y=f._zod.deferred;if(y){for(let m of y)m();f._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;if(g)g(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 Ee 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"}}(Aa=globalThis).__zod_globalConfig??(Aa.__zod_globalConfig={});var te=globalThis.__zod_globalConfig;function ue(e){if(e)Object.assign(te,e);return te}function Cm(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Mt,2)),e.message}function Om(e){this._zod.message=e}var Tm={get:Cm,set:Om,enumerable:!0,configurable:!0},uo={value:void 0,enumerable:!1},Pa=new WeakSet([Object.prototype,Error.prototype]),Na=(e,t)=>{e.name="$ZodError",uo.value=t,Object.defineProperty(e,"issues",uo),uo.value=void 0,Object.defineProperty(e,"message",Tm);let r=Object.getPrototypeOf(e);if(!Pa.has(r))Pa.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})}})},za=w("$ZodError",Na),Hx=w("$ZodError",Na,void 0,{Parent:Error});function Am(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 Ma(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)Am(r,o.path[0],()=>[]).push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Da(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 Ee;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((d)=>be(d,i,ue())));throw ro(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)=>be(d,i,ue())));throw ro(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 Ee;return s.issues.length?La(e,s.issues,o):{success:!0,data:s.value}};function La(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>be(o,r,ue()))),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?La(e,s.issues,o):{success:!0,data:s.value}};var $m=Symbol.for("zod.compile.invalid"),Pm=Symbol.for("zod.compile.fallback"),lo=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==$m)return!0;if(n.definite===!0&&r===void 0)return!1}return Nm(e,t,r)};function Nm(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)n[Pm]=!0,s=o({value:t,issues:[]},n);else s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)throw new Ee;return s.issues.length===0}var fo=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},Ua=(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 Za=(e)=>{let t=Dr(e),r=(n,o,s,i)=>t(n,o,s,Mr(r,i));return r};var ja=(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 Fa=(e)=>{let t=Lr(e),r=async(n,o,s,i)=>await t(n,o,s,Mr(r,i));return r};var Ha=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ur(e)(t,r,o)};var Ba=(e)=>(t,r,n)=>Ur(e)(t,r,n);var qa=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Zr(e)(t,r,o)};var Ga=(e)=>async(t,r,n)=>Zr(e)(t,r,n);var Ka=/^[cC][0-9a-z]{6,}$/,Va=/^[0-9a-z]+$/,Wa=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Ja=/^[0-9a-vA-V]{20}$/,Ya=/^[A-Za-z0-9]{27}$/,Xa=/^[a-zA-Z0-9_-]{21}$/;function Qa(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var ec=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var tc=/^([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})$/,po=(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 rc=/^(?:[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 zm="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function nc(){return new RegExp(zm,"u")}var oc=/^(?:(?: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])$/,sc=/^(([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 ic=/^((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])$/,ac=/^(([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])$/,cc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,uc=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var dc=/^https?$/,lc=/^\+[1-9]\d{6,14}$/;var fc="(?:(?:\\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 Mm(e){return new RegExp(`^${e}$`)}var hc=Mm(fc);function ho(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 pc(e){return new RegExp(`^${ho(e)}$`)}function mc(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${ho({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${ho({precision:e.precision})}`:r;return new RegExp(`^${fc}T(?:${n})$`)}var gc=/^[\s\S]{0,}$/;var mo=/^-?\d+$/,Zt=/^-?\d+(?:\.\d+)?$/,yc=/^(?:true|false)$/i;var _c=/^[^A-Z]*$/,wc=/^[^a-z]*$/;var J=w("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var go=(e)=>{let t=e.value;return!ma(t)&&t.length!==void 0},jr={number:"number",bigint:"bigint",object:"date"},yo=w("$ZodCheckLessThan",(e,t)=>{J.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})}}),_o=w("$ZodCheckGreaterThan",(e,t)=>{J.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})}}),Sc=w("$ZodCheckMultipleOf",(e,t)=>{J.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):ga(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})}}),vc=w("$ZodCheckNumberFormat",(e,t)=>{J.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 xc=w("$ZodCheckMaxLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=go),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})}}),bc=w("$ZodCheckMinLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=go),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})}}),Ec=w("$ZodCheckLengthEquals",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=go),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=w("$ZodCheckStringFormat",(e,t)=>{var r,n;if(J.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=()=>{})}),Ic=w("$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})}}),kc=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=_c),Ft.init(e,t)}),Rc=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wc),Ft.init(e,t)}),Cc=w("$ZodCheckIncludes",(e,t)=>{J.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})}}),Oc=w("$ZodCheckStartsWith",(e,t)=>{J.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})}}),Tc=w("$ZodCheckEndsWith",(e,t)=>{J.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 Ac=w("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class wo{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 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
|
-
let ${
|
|
13
|
-
for (let i = 0; i < ${
|
|
14
|
-
const iss = ${
|
|
15
|
-
iss.path = iss.path ? [${
|
|
11
|
+
};`)(...Object.values(this.closed))}}var Pc={major:4,minor:6,patch:7};var z=w("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Pc;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=pe(a),l;for(let p of c){if(p._zod.def.when){if(ka(a))continue;if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,y=p._zod.check(a);if(y instanceof Promise&&d?.async===!1)throw new Ee;if(l||y instanceof Promise)l=(l??Promise.resolve()).then(async()=>{if(await y,a.issues.length===f)return;if($r(a.issues,f,e),!u)u=pe(a,f)});else{if(a.issues.length===f)continue;if($r(a.issues,f,e),!u)u=pe(a,f)}}if(l)return l.then(()=>a);return a},i=(a,c,d)=>{if(pe(a))return a.aborted=!0,a;let u=s(c,o,d);if(u instanceof Promise){if(d.async===!1)throw new Ee;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 Ee;return d.then((u)=>s(u,o,c))}return s(d,o,c)}}},{get "~standard"(){return zr(this,"~standard",vo(this))},set "~standard"(e){Ae(this,"~standard",e)}}),Kc=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>be(r,t,ue()))}:{value:e.value};async function Dm(e,t){let r={async:!0};return Kc(await e._zod.run({value:t,issues:[]},r),r)}function vo(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Kc(n,r)}catch(n){}return Dm(e,t)},vendor:"zod",version:1}}var qr=w("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=t.pattern??gc,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=w("$ZodStringFormat",(e,t)=>{Ft.init(e,t),qr.init(e,t)}),Vc=w("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tc),L.init(e,t)}),Wc=w("$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=po(n))}else t.pattern??(t.pattern=po());L.init(e,t)}),Jc=w("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rc),L.init(e,t)}),Yc=1,Hr=2;function Xc(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function Lm(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Xc(e)||Hr;return Um(e,t)}function Um(e,t){if(!t.normalize&&t.protocol?.source===dc.source&&!/^https?:\/\//i.test(e))return Yc;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 Zm=/[\t\n\r]/g;function Nc(e){return e.replace(Zm,"")}function jm(e,t){return t.lastIndex=0,t.test(e.hostname)}function Fm(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Qc=w("$ZodURL",(e,t)=>{L.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=Lm(n,t);if(o===Yc){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=Nc(n);return}if(t.hostname&&!jm(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&&!Fm(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:Nc(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),eu=w("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nc()),L.init(e,t)}),tu=w("$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?Xa:Qa(t.length)),L.init(e,t)}),ru=w("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ka),L.init(e,t)}),nu=w("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Va),L.init(e,t)}),ou=w("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Wa),L.init(e,t)}),su=w("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ja),L.init(e,t)}),iu=w("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ya),L.init(e,t)}),au=w("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mc(t)),L.init(e,t)}),cu=w("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=hc),L.init(e,t)}),uu=w("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=pc(t)),L.init(e,t)}),du=w("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ec),L.init(e,t)}),lu=w("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=oc),L.init(e,t)}),Hm=/^[0-9a-fA-F:.]+$/;function fu(e){if(!Hm.test(e))return!1;return Xc(`http://[${e}]`)}var hu=w("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sc),L.init(e,t),e._zod.check=(r)=>{if(!fu(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var pu=w("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ic),L.init(e,t)});function Bm(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 fu(r)}var mu=w("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ac),L.init(e,t),e._zod.check=(r)=>{if(!Bm(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function gu(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 xo=/^[0-9a-zA-Z+/]*={0,2}$/,yu=w("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xo),L.init(e,t),e._zod.check=(r)=>{if(gu(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 qm(e){if(!Gr.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return gu(r)}var _u=w("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gr),L.init(e,t),e._zod.check=(r)=>{if(qm(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),wu=w("$ZodE164",(e,t)=>{t.pattern??(t.pattern=lc),L.init(e,t)});function Gm(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 Su=w("$ZodJWT",(e,t)=>{L.init(e,t),e._zod.check=(r)=>{if(Gm(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var bo=w("$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}}),vu=w("$ZodNumberFormat",(e,t)=>{vc.init(e,t),bo.init(e,t)}),xu=w("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=yc,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 bu=w("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=(r)=>r}),Eu=w("$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 Km(e,t){let r=io(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 io(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 Vm=(e)=>Array.isArray(e)?e.length:-1;function zc(e,t,r){if(e.issues.length)t.issues.push(...xe(r,e.issues));t.value[r]=e.value}var Iu=w("$ZodArray",(e,t)=>{z.init(e,t);let r=te.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)=>zc(l,n,c)));else if(zc(u,n,c),a&&u.issues.length!==0&&pe(u))break}if(i.length)return Promise.all(i).then(()=>n);return n},Km(e,Vm)});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(...xe(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 Wm=[];function ku(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:Wm,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=ba(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Ru(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 y in t){if(i&&r.issues.length!==f){if(pe(r,f))break;f=r.issues.length}if(c.has(y))continue;if(y==="__proto__"){if(u==="never")a.push(y);continue}if(u==="never"){a.push(y);continue}let g=d.run({value:t[y],issues:[]},n);if(g instanceof Promise)e.push(g.then((m)=>Br(m,r,y,t,l,p)));else Br(g,r,y,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 Jm=w("$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(()=>ku(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))he(l,p,new Set);for(let y of f.values)l[p].add(y);if(f.optin!==void 0)l[p].add(void 0)}}return l});let s=mt,i=t.catchall,a,c=te.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,y=u?.abortEarly,g=d.issues.length;for(let m of a.allKeys){if(y&&d.issues.length!==g){if(pe(d,g))break;g=d.issues.length}if(m==="__proto__")continue;let _=f[m],x=_._zod.optin,v=_._zod.optout,b=_._zod.run({value:l[m],issues:[]},u);if(b instanceof Promise)p.push(b.then((E)=>Br(E,d,m,l,x,v)));else Br(b,d,m,l,x,v)}if(!i)return p.length?Promise.all(p).then(()=>d):d;return Ru(p,l,d,u,o.value,e,y===!0)}}),Cu=w("$ZodObjectJIT",(e,t)=>{Jm.init(e,t);let r=e._zod.parse,n=Dt(()=>ku(t)),o=te.memoizer,s=(f)=>{let y=n.value,g=y.symbolKeys,m=new wo(["payload","ctx"],{shape:f,inst:e,memo:o,syms:g}),_=(E)=>`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`,x=(E,C)=>`
|
|
12
|
+
let ${E}_ab = false;
|
|
13
|
+
for (let i = 0; i < ${E}.issues.length; i++) {
|
|
14
|
+
const iss = ${E}.issues[i];
|
|
15
|
+
iss.path = iss.path ? [${C}, ...iss.path] : [${C}];
|
|
16
16
|
payload.issues.push(iss);
|
|
17
|
-
if (iss.continue !== true) ${
|
|
17
|
+
if (iss.continue !== true) ${E}_ab = true;
|
|
18
18
|
}
|
|
19
|
-
if (${
|
|
19
|
+
if (${E}_ab && ctx && ctx.abortEarly) {
|
|
20
20
|
payload.value = newResult;
|
|
21
21
|
return payload;
|
|
22
|
-
}`;
|
|
23
|
-
const ${
|
|
24
|
-
if (!${
|
|
25
|
-
if (${
|
|
22
|
+
}`;m.write("const input = payload.value;");let v=Object.create(null),b=0;for(let E of y.allKeys)v[E]=`key_${b++}`;m.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let E of y.allKeys){if(E==="__proto__")continue;let C=v[E],I=typeof E==="symbol"?`syms[${g.indexOf(E)}]`:wa(E),O=`${I} in input`,G=f[E],D=G?._zod?.optin,Q=D!==void 0,Ne=G?._zod?.optout==="optional";if(m.write(`const ${C} = ${_(I)};`),Q&&Ne){let dr=D==="optional"?`${C}_present`:`${C}.value !== undefined || ${C}_present`;m.write(`
|
|
23
|
+
const ${C}_present = ${O};
|
|
24
|
+
if (!${C}.issues.length || ${C}_present) {
|
|
25
|
+
if (${C}.issues.length) {${x(C,I)}
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
if (${dr}) {
|
|
29
|
-
newResult[${
|
|
29
|
+
newResult[${I}] = ${C}.value;
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
`)}else if(!
|
|
34
|
-
const ${
|
|
35
|
-
if (${
|
|
33
|
+
`)}else if(!Q)m.write(`
|
|
34
|
+
const ${C}_present = ${O};
|
|
35
|
+
if (${C}.issues.length) {${x(C,I)}
|
|
36
36
|
}
|
|
37
|
-
if (!${
|
|
37
|
+
if (!${C}_present && !${C}.issues.length) {
|
|
38
38
|
payload.issues.push({
|
|
39
39
|
code: "invalid_type",
|
|
40
40
|
expected: "nonoptional",
|
|
41
41
|
input: undefined,
|
|
42
|
-
path: [${
|
|
42
|
+
path: [${I}]
|
|
43
43
|
});
|
|
44
44
|
if (ctx && ctx.abortEarly) {
|
|
45
45
|
payload.value = newResult;
|
|
@@ -47,34 +47,34 @@ ${t.join(`
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
if (${
|
|
51
|
-
newResult[${
|
|
50
|
+
if (${C}_present) {
|
|
51
|
+
newResult[${I}] = ${C}.value;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
`);else if(
|
|
55
|
-
if (${
|
|
54
|
+
`);else if(m.write(`
|
|
55
|
+
if (${C}.issues.length) {${x(C,I)}
|
|
56
56
|
}
|
|
57
|
-
`),
|
|
58
|
-
if (${
|
|
59
|
-
newResult[${
|
|
57
|
+
`),D==="defaulted")m.write(`newResult[${I}] = ${C}.value;`);else m.write(`
|
|
58
|
+
if (${C}.value !== undefined || ${O}) {
|
|
59
|
+
newResult[${I}] = ${C}.value;
|
|
60
60
|
}
|
|
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>
|
|
61
|
+
`)}return m.write("payload.value = newResult;"),m.write("return payload;"),m.compile()},i,a=mt,c=!te.jitless,u=c&&va.value,l=t.catchall,p;e._zod.parse=(f,y)=>{p??(p=n.value);let g=f.value;if(!a(g))return f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f;if(c&&u&&y?.async===!1&&y.jitless!==!0){if(!i)i=s(t.shape);if(f=i(f,y),!l)return f;return Ru([],g,f,y,p,e,y?.abortEarly===!0)}return r(f,y)}});function Mc(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)=>!pe(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)=>be(i,n,ue())))}),t}var Eo=w("$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 Mc(i,n,e,o);return Promise.all(i).then((a)=>Mc(a,n,e,o))}});function Ym(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 Ou=w("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Eo.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))he(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(()=>Ym(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}}),Tu=w("$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])=>Dc(r,c,d));return Dc(r,s,i)}});function So(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=So(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=So(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 Dc(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=So(t.value,r.value);if(!c.valid){if(pe(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Au=w("$ZodTuple",(e,t)=>{z.init(e,t);let r=t.items,n=te.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=Lc(r,"optin"),d=Lc(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 y=r[f]._zod.run({value:i[f],issues:[]},s);if(y instanceof Promise)a.push(y.then((g)=>{u[f]=g}));else if(u[f]=y,l&&!p&&y.issues.length)p=pe(y)}if(t.rest&&!p){let f=r.length-1,y=i.slice(r.length),g=o.issues.length;for(let m of y){if(l&&o.issues.length!==g){if(pe(o,g))break;g=o.issues.length}f++;let _=t.rest._zod.run({value:m,issues:[]},s);if(_ instanceof Promise)a.push(_.then((x)=>Uc(x,o,f)));else Uc(_,o,f)}}if(a.length)return Promise.all(a).then(()=>Zc(u,o,r,i,d));return Zc(u,o,r,i,d)}});function Lc(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 Uc(e,t,r){if(e.issues.length)t.issues.push(...xe(r,e.issues));t.value[r]=e.value}function Zc(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(...xe(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 $u=w("$ZodRecord",(e,t)=>{z.init(e,t);let r=te.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((y)=>be(y,o,ue())),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((y)=>{if(y.issues.length)n.issues.push(...xe(u,y.issues));n.value[p]=y.value}));else{if(f.issues.length)n.issues.push(...xe(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 y=t.keyType._zod.run({value:Number(d),issues:[]},o);if(y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(y.issues.length===0)u=y}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((y)=>be(y,o,ue())),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((y)=>{if(y.issues.length)n.issues.push(...xe(d,y.issues));n.value[p]=y.value}));else{if(f.issues.length)n.issues.push(...xe(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 Pu=w("$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)=>xa.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}}),Nu=w("$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 zu=w("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",te.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 Ee;return r.value=o,r}});function jc(e,t){return e.value=t.issues.length?void 0:t.value,e}var Io=w("$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)=>jc(r,s));return jc(r,o)}return t.innerType._zod.run(r,n)}}),Mu=w("$ZodExactOptional",(e,t)=>{Io.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)}),Du=w("$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)}}),Lu=w("$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)=>Fc(s,t));return Fc(o,t)}});function Fc(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Uu=w("$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)}}),Zu=w("$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)=>Hc(s,e));return Hc(o,e)}});function Hc(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 Bc(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)=>be(o,n,ue()))},input:e.value}),e}var ju=w("$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)=>Bc(r,s,t,n));return Bc(r,o,t,n)}});var Fu=w("$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 Hu=w("$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(qc);return qc(o)}});function qc(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Bu=w("$ZodCustom",(e,t)=>{J.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)=>Gc(s,r,n,e));Gc(o,r,n,e);return}});function Gc(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 Gu extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Ro="~memo",qu=[];function Ku(e){return e!==null&&typeof e==="object"}function ko(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Vu=new WeakMap,Ht=0,Wr=1,Bt=2;function Jr(e,t,r){let n=Vu.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 y=Object.getOwnPropertyDescriptor(u,f);if(l&&!y.enumerable)continue;let g=y.get?Wr:y.value?._zod?Jr(y.value,t,r):Ht;if(g>p)p=g}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),Xm(e,o)}function Xm(e,t){if(t!==Wr)Vu.set(e,t===Bt);return t}function Qm(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var Kr,Vr=[],eg={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"&&tg(s,o.value))throw new Gu;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 _=Jr(e,new Set,!1);if(_===Ht){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,d)}if(_===Bt||n)r=!0;else n=!0}let u=c.value;if(!Ku(u))return i(c,d);let l=d[Ro];if(!l)l={buckets:new WeakMap,backEdges:void 0},d[Ro]=l;let p;if(o===d)p=s;else p=Qm(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(...ko(f.issues))}else c.memo=!0,l.backEdges??(l.backEdges=new WeakSet),l.backEdges.add(f.value);return c}Kr=p;let y=Vr.length,g=i(c,d);Kr=void 0;let m=Vr.length>y?Vr.pop():void 0;if(g instanceof Promise)return g.then((_)=>{if(m)m.issues=_.issues.length?ko(_.issues):qu;return _});if(m)m.issues=g.issues.length?ko(g.issues):qu;return g};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function Wu(){return eg}function tg(e,t){let r=e[Ro]?.backEdges;return r!==void 0&&Ku(t)&&r.has(t)}var rg=()=>{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=Ra(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 ${oo(s.values[0])}`;return`Invalid option: expected one of ${to(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":""}: ${to(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:rg()}}var Ju;class Yu{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 ng(){return new Yu}(Ju=globalThis).__zod_globalRegistry??(Ju.__zod_globalRegistry=ng());var et=globalThis.__zod_globalRegistry;function Xu(e){if(e.checks)e.checks=[...e.checks];return e}function Qu(e,t){return new e(Xu({type:"string",...R(t)}))}function ed(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function td(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function sd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function id(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function ad(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function cd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function ud(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function dd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function ld(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function fd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function hd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function pd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function md(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function gd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function yd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function _d(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function wd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function Sd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function vd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function xd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function bd(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Ed(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Id(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function kd(e,t){return new e(Xu({type:"number",checks:[],...R(t)}))}function Rd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function Cd(e,t){return new e({type:"boolean",...R(t)})}function Od(e){return new e({type:"unknown"})}function Td(e,t){return new e({type:"never",...R(t)})}function Yr(e,t){return new yo({check:"less_than",...R(t),value:e,inclusive:!1})}function qt(e,t){return new yo({check:"less_than",...R(t),value:e,inclusive:!0})}function Xr(e,t){return new _o({check:"greater_than",...R(t),value:e,inclusive:!1})}function Gt(e,t){return new _o({check:"greater_than",...R(t),value:e,inclusive:!0})}function Qr(e,t){return new Sc({check:"multiple_of",...R(t),value:e})}function en(e,t){return new xc({check:"max_length",...R(t),maximum:e})}function gt(e,t){return new bc({check:"min_length",...R(t),minimum:e})}function tn(e,t){return new Ec({check:"length_equals",...R(t),length:e})}function Oo(e,t){return new Ic({check:"string_format",format:"regex",...R(t),pattern:e})}function To(e){return new kc({check:"string_format",format:"lowercase",...R(e)})}function Ao(e){return new Rc({check:"string_format",format:"uppercase",...R(e)})}function $o(e,t){return new Cc({check:"string_format",format:"includes",...R(t),includes:e})}function Po(e,t){return new Oc({check:"string_format",format:"starts_with",...R(t),prefix:e})}function No(e,t){return new Tc({check:"string_format",format:"ends_with",...R(t),suffix:e})}function He(e){return new Ac({check:"overwrite",tx:e})}function zo(e){return He((t)=>t.normalize(e))}function Mo(){return He((e)=>e.trim())}function Do(){return He((e)=>e.toLowerCase())}function Lo(){return He((e)=>e.toUpperCase())}function Uo(){return He((e)=>Sa(e))}function Ad(e,t,r){return new e({type:"array",element:t,...R(r)})}function $d(e,t,r){return new e({type:"custom",check:"custom",fn:t,...R(r)})}function Pd(e,t){let r=og((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 og(e,t){let r=new J({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))he(e,n,r[n]);return e}function jo(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 F(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;F(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"&&re(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 Nd(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Fo(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??((y)=>y);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}/${Nd(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+Nd(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 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
|
|
65
|
-
`).join(""),{mode:384}),await
|
|
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
|
|
68
|
-
`)}catch(
|
|
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 Dd(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;Dd(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 Ld=new Set(["type","properties","required","additionalProperties"]),zd=["oneOf","anyOf"];function Md(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 Zo(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Ld.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]??Md(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]:Zo(a)??{allOf:a};he(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=Md(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 sg(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Ld)if(o in e)return;let r=t.filter((o)=>zd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=Zo(t);else{let o=r[0],s=zd.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)=>Zo([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Kt(e,n)}function Ho(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),y=f.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(y);else Kt(d,y);if(Kt(d,u),a._zod.parent===l)for(let m in d){if(m==="$ref"||m==="allOf")continue;if(!(m in u))delete d[m]}if(y.$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]}}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 y in d){if(y==="$ref"||y==="allOf")continue;if(y in f.def&&JSON.stringify(d[y])===JSON.stringify(f.def[y]))delete d[y]}}}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())Dd(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)??[])sg(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;he(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 re(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 re(n.element,r);if(n.type==="set")return re(n.valueType,r);if(n.type==="lazy")return re(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 re(n.innerType,r);if(n.type==="intersection")return re(n.left,r)||re(n.right,r);if(n.type==="record"||n.type==="map")return re(n.keyType,r)||re(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return re(n.in,r)||re(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(re(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(re(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(re(o,r))return!0;if(n.rest&&re(n.rest,r))return!0;return!1}return!1}var Ud=(e,t={})=>(r)=>{let n=jo({...r,processors:t});return F(e,n),Fo(n,e),Ho(n,e)},Vt=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=jo({...o??{},target:s,io:t,processors:r});return F(e,i),Fo(i,e),Ho(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},Zd=(e,t)=>{yt(e,"minimum",t),_t(e,"maximum",t)},Bd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},qd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Gd=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Kd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},jd=(e,t)=>yt(e,"minimum",t.minimum),Fd=(e,t)=>_t(e,"maximum",t.maximum),Hd=(e)=>(t,r)=>{Kd(t,r.format);let[n,o]=e[r.format];yt(t,"minimum",n),_t(t,"maximum",o)},ig={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)=>Bd(e,t.value),number_format:Hd(Tr),bigint_format:Hd(so),min_length:jd,max_length:Fd,length_equals:(e,t)=>Zd(e,t.length),min_size:jd,max_size:Fd,size_equals:(e,t)=>Zd(e,t.size),string_format:(e,t)=>{if(Kd(e,t.format),t.pattern)qd(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)=>Gd(e,t.mime)};function de(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)ig[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)Bd(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)Gd(t,o.mime);for(let s of o.patterns??[])qd(t,s);return t}var ag={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cg=new Map([[xo,cc],[Gr,uc]]),Vd=(e)=>cg.get(e)??e,Wd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=de(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=ag[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(Vd);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}))]}},Jd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=de(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 y=new Set;for(let _ of a)if(Number.isFinite(_)&&_!==0)y.add(Math.abs(_));else $e(e,t,o,n,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);let[g,...m]=y;if(g!==void 0)o.multipleOf=g;if(m.length)o.allOf=[...o.allOf??[],...m.map((_)=>({multipleOf:_}))]}},Yd=(e,t,r,n)=>{r.type="boolean"};var Xd=(e,t,r,n)=>{r.not={}};var Qd=(e,t,r,n)=>{};var el=(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},tl=(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 rl=(e,t,r,n)=>{$e(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var nl=(e,t,r,n)=>{$e(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var ol=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=de(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=F(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 sl=(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)he(o.properties,d,F(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=F(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},il=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>F(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},al=(e,t,r,n)=>{let o=e._zod.def,s=F(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=F(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)},cl=(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((g,m)=>F(g,t,{...n,path:[...n.path,i,m]})),d=s.rest?F(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 g=s.items[u-1];if(!(t.io==="input"?Wt(g)!==void 0:g._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:y}=de(e);if(typeof f==="number")o.minItems=f;if(typeof y==="number")o.maxItems=y};function Bo(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let y=e.get(t)?.def;if(!y)return t;let g=Bo(e,y,r);return g===y?t:g}for(let y of["anyOf","oneOf"]){let g=t[y];if(!Array.isArray(g))continue;let m=g.map((_)=>Bo(e,_,r));if(m.some((_,x)=>_!==g[x]))t={...t,[y]:m}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((y)=>y==="number"||y==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((y)=>typeof y==="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((y)=>typeof y==="number"?String(y):y);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:mo).source;return f}var qo=new WeakMap;function ug(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 qo.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Bo(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 ul=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=de(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=F(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)he(o.patternProperties,Vd(l).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=F(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=qo.get(t);if(!u)u=[],qo.set(t,u),t.deferred.push(()=>ug(t));u.push(e)}o.additionalProperties=F(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)}},dl=(e,t,r,n)=>{let o=e._zod.def,s=F(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"}]},ll=(e,t,r,n)=>{let o=e._zod.def;F(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Go=Symbol();function fl(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"),Go}var hl=(e,t,r,n)=>{let o=e._zod.def;F(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=fl(o.defaultValue,e,t,r,n);if(i!==Go)r.default=i},pl=(e,t,r,n)=>{let o=e._zod.def;F(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=fl(o.defaultValue,e,t,r,n);if(i!==Go)r._prefault=i},ml=(e,t,r,n)=>{let o=e._zod.def;F(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},gl=(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;F(i,t,n);let a=t.seen.get(e);a.ref=i},yl=(e,t,r,n)=>{let o=e._zod.def;F(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Ko=(e,t,r,n)=>{let o=e._zod.def;F(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var _l=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 yg=(e,t)=>{za.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(_l.has(r))return;_l.add(r),rn(r,"format",(n)=>(o)=>Da(n,o)),rn(r,"flatten",(n)=>(o)=>Ma(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 le=w("ZodError",yg,void 0,{Parent:Error});var wl=Dr(le),Sl=Lr(le),vl=Ur(le),xl=Zr(le),bl=Ua(le),El=Za(le),Il=ja(le),kl=Fa(le),Rl=Ha(le),Cl=Ba(le),Ol=qa(le),Tl=Ga(le);function wg(){if(!te.localeError)ue(Co())}function Jt(){if(!te.memoizer)ue({memoizer:Wu()})}var Z=w("ZodType",(e,t)=>(wg(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ce(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 ve(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(gy(e,t))},superRefine(e,t){return this.check(yy(e,t))},overwrite(e){return this.check(He(e))},optional(){return Pl(this)},exactOptional(){return ny(this)},nullable(){return Nl(this)},nullish(){return Pl(Nl(this))},nonoptional(e){return uy(this,e)},array(){return V(this)},or(e){return on([this,e])},and(e){return Xg(this,e)},transform(e){return zl(this,ry(e))},default(e){return iy(this,e)},prefault(e){return cy(this,e)},catch(e){return ly(this,e)},pipe(e){return zl(this,e)},readonly(){return py(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",{...vo(this),jsonSchema:{input:Vt(this,"input"),output:Vt(this,"output")}})},set "~standard"(e){Ae(this,"~standard",e)},parse:function e(t,r){return wl(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Sl(this,t,r,{callee:e})},safeParse(e,t){return vl(this,e,t)},async safeParseAsync(e,t){return xl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ae(this,"spa",e)},validate(e,t){return lo(this,e,t)},validateAsync(e,t){return fo(this,e,t)},encode:function e(t,r){return bl(this,t,r,{callee:e})},decode:function e(t,r){return El(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await Il(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await kl(this,t,r,{callee:e})},safeEncode(e,t){return Rl(this,e,t)},safeDecode(e,t){return Cl(this,e,t)},async safeEncodeAsync(e,t){return Ol(this,e,t)},async safeDecodeAsync(e,t){return Tl(this,e,t)},toJSONSchema(e){return Ud(this,{})(e)},get description(){return et.get(this)?.description},get _def(){return this._zod.def}}),Ml=w("_ZodString",(e,t)=>{qr.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o)},Oa({format:(e)=>de(e).format??null,minLength:(e)=>de(e).minimum??null,maxLength:(e)=>de(e).maximum??null},{regex(...e){return this.check(Oo(...e))},includes(...e){return this.check($o(...e))},startsWith(...e){return this.check(Po(...e))},endsWith(...e){return this.check(No(...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(To(e))},uppercase(e){return this.check(Ao(e))},trim(){return this.check(Mo())},normalize(...e){return this.check(zo(...e))},toLowerCase(){return this.check(Do())},toUpperCase(){return this.check(Lo())},slugify(){return this.check(Uo())}})),Sg=w("ZodString",(e,t)=>{qr.init(e,t),Ml.init(e,t)},{email(e){return this.check(ed(Ig,e))},url(e){return this.check(id(Rg,e))},jwt(e){return this.check(vd(Fg,e))},emoji(e){return this.check(ad(Cg,e))},guid(e){return this.check(td(kg,e))},uuid(e){return this.check(rd(nn,e))},uuidv4(e){return this.check(nd(nn,e))},uuidv6(e){return this.check(od(nn,e))},uuidv7(e){return this.check(sd(nn,e))},nanoid(e){return this.check(cd(Og,e))},cuid(e){return this.check(ud(Tg,e))},cuid2(e){return this.check(dd(Ag,e))},ulid(e){return this.check(ld($g,e))},base64(e){return this.check(_d(Ug,e))},base64url(e){return this.check(wd(Zg,e))},xid(e){return this.check(fd(Pg,e))},ksuid(e){return this.check(hd(Ng,e))},ipv4(e){return this.check(pd(zg,e))},ipv6(e){return this.check(md(Mg,e))},cidrv4(e){return this.check(gd(Dg,e))},cidrv6(e){return this.check(yd(Lg,e))},e164(e){return this.check(Sd(jg,e))},datetime(e){return this.check(xd(vg,e))},date(e){return this.check(bd(xg,e))},time(e){return this.check(Ed(bg,e))},duration(e){return this.check(Id(Eg,e))}});function S(e){return Qu(Sg,e)}var H=w("ZodStringFormat",(e,t)=>{L.init(e,t),Ml.init(e,t)}),vg=w("ZodISODateTime",(e,t)=>{au.init(e,t),H.init(e,t)}),xg=w("ZodISODate",(e,t)=>{cu.init(e,t),H.init(e,t)}),bg=w("ZodISOTime",(e,t)=>{uu.init(e,t),H.init(e,t)}),Eg=w("ZodISODuration",(e,t)=>{du.init(e,t),H.init(e,t)}),Ig=w("ZodEmail",(e,t)=>{Jc.init(e,t),H.init(e,t)});var kg=w("ZodGUID",(e,t)=>{Vc.init(e,t),H.init(e,t)});var nn=w("ZodUUID",(e,t)=>{Wc.init(e,t),H.init(e,t)});var Rg=w("ZodURL",(e,t)=>{Qc.init(e,t),H.init(e,t)});var Cg=w("ZodEmoji",(e,t)=>{eu.init(e,t),H.init(e,t)});var Og=w("ZodNanoID",(e,t)=>{tu.init(e,t),H.init(e,t)});var Tg=w("ZodCUID",(e,t)=>{ru.init(e,t),H.init(e,t)});var Ag=w("ZodCUID2",(e,t)=>{nu.init(e,t),H.init(e,t)});var $g=w("ZodULID",(e,t)=>{ou.init(e,t),H.init(e,t)});var Pg=w("ZodXID",(e,t)=>{su.init(e,t),H.init(e,t)});var Ng=w("ZodKSUID",(e,t)=>{iu.init(e,t),H.init(e,t)});var zg=w("ZodIPv4",(e,t)=>{lu.init(e,t),H.init(e,t)});var Mg=w("ZodIPv6",(e,t)=>{hu.init(e,t),H.init(e,t)});var Dg=w("ZodCIDRv4",(e,t)=>{pu.init(e,t),H.init(e,t)});var Lg=w("ZodCIDRv6",(e,t)=>{mu.init(e,t),H.init(e,t)});var Ug=w("ZodBase64",(e,t)=>{yu.init(e,t),H.init(e,t)});var Zg=w("ZodBase64URL",(e,t)=>{_u.init(e,t),H.init(e,t)});var jg=w("ZodE164",(e,t)=>{wu.init(e,t),H.init(e,t)});var Fg=w("ZodJWT",(e,t)=>{Su.init(e,t),H.init(e,t)});var Dl=w("ZodNumber",(e,t)=>{bo.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jd(e,r,n,o),e.isFinite=!0},Oa({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=de(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=de(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=de(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>de(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(Al(e))},safe(e){return this.check(Al(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 kd(Dl,e)}var Hg=w("ZodNumberFormat",(e,t)=>{vu.init(e,t),Dl.init(e,t)});function Al(e){return Rd(Hg,e)}var Bg=w("ZodBoolean",(e,t)=>{xu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o)});function Yt(e){return Cd(Bg,e)}var qg=w("ZodUnknown",(e,t)=>{bu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qd(e,r,n,o)});function Ie(){return Od(qg)}var Gg=w("ZodNever",(e,t)=>{Eu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o)});function Kg(e){return Td(Gg,e)}var Vg=w("ZodArray",(e,t)=>{Jt(),Iu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ol(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 V(e,t){return Ad(Vg,e,t)}var Wg=w("ZodObject",(e,t)=>{Jt(),Cu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sl(e,r,n,o),Im(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return oe(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ce(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ce(this._zod.def,{catchall:Ie()}))},loose(){return this.clone(ce(this._zod.def,{catchall:Ie()}))},strict(){return this.clone(ce(this._zod.def,{catchall:Kg()}))},strip(){return this.clone(ce(this._zod.def,{catchall:void 0}))},extend(e){return ym(this,e)},safeExtend(e){return _m(this,e)},merge(e){return wm(this,e)},pick(e){return mm(this,e)},omit(e){return gm(this,e)},partial(...e){return Ia(Jo,this,e[0])},exactPartial(...e){return Ia(jl,this,e[0],"exactPartial")},required(...e){return Sm(Fl,this,e[0])}});function k(e,t){let r={type:"object",shape:e??{},...R(t)};return new Wg(r)}var Ll=w("ZodUnion",(e,t)=>{Eo.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>il(e,r,n,o),e.options=t.options});function on(e,t){return new Ll({type:"union",options:e,...R(t)})}var Jg=w("ZodDiscriminatedUnion",(e,t)=>{Ll.init(e,t),Ou.init(e,t)});function Ul(e,t,r){return new Jg({type:"union",options:t,discriminator:e,...R(r)})}var Yg=w("ZodIntersection",(e,t)=>{Tu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>al(e,r,n,o)});function Xg(e,t){return new Yg({type:"intersection",left:e,right:t})}var Qg=w("ZodTuple",(e,t)=>{Jt(),Au.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cl(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 Jo({type:"optional",innerType:t}))})}});function Be(e,t,r){let n=t instanceof z,o=n?r:t;return new Qg({type:"tuple",items:e,rest:n?t:null,...R(o)})}var $l=w("ZodRecord",(e,t)=>{Jt(),$u.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ul(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Zl(e,t,r){if(!t||!t._zod)return new $l({type:"record",keyType:S(),valueType:e,...R(t)});return new $l({type:"record",keyType:e,valueType:t,...R(r)})}var Wo=w("ZodEnum",(e,t)=>{Pu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,o,s)=>el(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 Wo({...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 Wo({...t,checks:[],...R(o),entries:s})}});function oe(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Wo({type:"enum",entries:r,...R(t)})}var ey=w("ZodLiteral",(e,t)=>{Nu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tl(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 B(e,t){return new ey({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var ty=w("ZodTransform",(e,t)=>{Jt(),zu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nl(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 ry(e){return new ty({type:"transform",transform:e})}var Jo=w("ZodOptional",(e,t)=>{Io.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ko(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new Jo({type:"optional",innerType:e})}var jl=w("ZodExactOptional",(e,t)=>{Mu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ko(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ny(e){return new jl({type:"optional",innerType:e})}var oy=w("ZodNullable",(e,t)=>{Du.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Nl(e){return new oy({type:"nullable",innerType:e})}var sy=w("ZodDefault",(e,t)=>{Lu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iy(e,t){return new sy({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():no(t)}})}var ay=w("ZodPrefault",(e,t)=>{Uu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cy(e,t){return new ay({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():no(t)}})}var Fl=w("ZodNonOptional",(e,t)=>{Zu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ll(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function uy(e,t){return new Fl({type:"nonoptional",innerType:e,...R(t)})}var dy=w("ZodCatch",(e,t)=>{ju.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ml(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ly(e,t){return new dy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Ta(t)})}var fy=w("ZodPipe",(e,t)=>{Fu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gl(e,r,n,o),e.in=t.in,e.out=t.out});function zl(e,t){return new fy({type:"pipe",in:e,out:t})}var hy=w("ZodReadonly",(e,t)=>{Hu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function py(e){return new hy({type:"readonly",innerType:e})}var my=w("ZodCustom",(e,t)=>{Bu.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rl(e,r,n,o)});function gy(e,t={}){return $d(my,e,t)}function yy(e,t){return Pd(e,t)}var Xo=["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,_y=1000;function ne(e){return new TextEncoder().encode(JSON.stringify(e)).length}var Y=S().min(1).max(256),nt=S().min(1).max(1024),wy=S().regex(/^(0|[1-9][0-9]{0,17})$/u),un=k({epoch:Y,ordinal:wy}).strict(),rt={workspaceId:Y,sourceId:Y,hostId:Y},wt=k({address:nt,version:Y,scope:Y,columns:k({title:S().max(4096),state:Y,owner:Y.nullable(),parent:nt.nullable(),project:nt.nullable(),labels:V(Y).max(256),url:S().max(2048).nullable(),updatedAt:S().max(64).nullable()}).strict(),extra:Ie()}).strict(),Qo=k({position:un,change:Ul("op",[k({op:B("upsert"),row:wt}).strict(),k({op:B("delete"),address:nt}).strict()])}).strict(),Sy=k({address:nt}).strict(),vy=k({page:S().min(1).max(4096).optional(),limit:Pe().int().min(1).max(_y)}).strict(),xy=k({address:nt,ownerMemberId:Y,expectedOwner:Y.nullable(),intentId:Y,ifRevision:S().min(1).max(256).optional()}).strict(),by=k({on:Yt()}).strict(),Ey=k({memberId:Y}).strict(),sn=(e,t)=>k({...rt,caller:Ey,op:B(e),args:t}).strict(),Bl=Ul("op",[sn("read",Sy),sn("list",vy),sn("assign",xy),sn("watch",by)]),Iy=k({generation:Y,snapshot:Y,base:un,rows:V(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"}),ky=k({intentId:Y,result:Ie(),observation:Qo,revision:Y.nullable().optional()}).strict(),Yo={read:k({observation:Qo}).strict(),list:Iy,assign:ky,watch:k({on:Yt()}).strict()},Hl=oe(Xo),Ry=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],an=(e)=>on([k({...rt,op:B(e),outcome:oe(["applied","noop"]),body:Yo[e]}).strict(),k({...rt,op:B(e),outcome:oe(["applied","noop"]),code:B("SOURCE_READER_RESTARTING"),body:Yo[e]}).strict(),k({...rt,op:B(e),outcome:B("rejected"),code:Hl,body:Yo[e]}).strict(),k({...rt,op:B(e),outcome:oe(["unknown","refused"]),code:on([Hl.exclude(["ITEM_TOO_LARGE"]),oe(Ry)])}).strict(),k({...rt,op:B(e),outcome:B("refused"),code:B("ITEM_TOO_LARGE"),item:nt}).strict()]),ql=on([an("read"),an("list"),an("assign"),an("watch")]),lI=k({...rt,position:un,observations:V(Qo).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"}),Gl=k({applied:un.nullable(),seq:Pe().int().min(0),relist:Yt()}).strict();var qe="x-hh-records";var Cy=`${qe}/changed`,ke="assign",dn="records:assign",Kl=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(),Vl=S().min(1).max(256),Wl=S().min(1).max(1024),Jl=k({address:Wl,revision:S().min(1).max(256),scope:S().min(1).max(256),columns:Zl(S(),Ie()),extra:Ie().optional()}).strict(),pI=k({source:Vl,epoch:S().min(1).max(256),records:V(Jl)}).strict(),Oy=k({type:B(Cy),source:Vl,revision:S().min(1).max(256),address:Wl,deleted:B(!0).optional(),record:Jl.optional()}).strict(),mI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),action:Oy}),Ty=new RegExp(`^${qe}://[^/?#]+$`,"u"),Yl=(e)=>e===`${qe}://`||Ty.test(e);var Ay=k({id:S().min(1),revision:Pe().int().min(0),state:S(),operations:V(S())}).passthrough();var es=Pe().int().min(0),_I=k({id:S().min(1),engine:S().min(1),owner:S().min(1),name:S().min(1),description:S().optional(),tags:V(S()).optional(),model:Ie().optional(),config:Zl(S(),Ie()),ifRevision:es}).passthrough(),wI=k({id:S().min(1),ifRevision:es}).strict(),SI=k({id:S().min(1),ifRevision:es}).strict(),Xl=-32602,vI=k({code:B(Xl),message:S(),data:k({staleRevision:Pe().int().min(1),row:Ay})}),xI=k({code:B(Xl),message:S(),data:k({staleRevision:B(0)})});var ts=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],Ge="x-hh-services://",$y=`${Ge} and ${qe}://<sourceId>`,Ql=["put","remove","start","stop","restart","accept"];var Py="hh-services://backup",Ny="hh-services://changes",zy=/^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;function ef(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||Yl(n)))return;return`subscribe to ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ${$y}`}case"x-ahpd/invokeOperation":{if(t.channel===Ge){if(typeof t.operationId==="string"&&Ql.includes(t.operationId))return;return`x-ahpd/invokeOperation ${r("operationId")} on ${Ge} is not one Hightea sends; only ${Ql.join(", ")}`}if(t.channel===`${qe}://`){if(t.operationId===ke)return;return`x-ahpd/invokeOperation ${r("operationId")} on ${qe}:// is not one Hightea sends; only ${ke} (${dn})`}return`x-ahpd/invokeOperation on ${r("channel")} is not one Hightea sends; only ${Ge} and ${qe}://`}case"resourceRead":if(typeof t.uri==="string"&&zy.test(t.uri))return;return`resourceRead of ${r("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${Py} and ${Ny}`;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 ${ts.join(", ")}`}}var tf=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...ts];function Xt(e){return ts.includes(e)}var My=1e4,Qt=My-1000,rf="host-request:",nf="1.1.0";var of="signed-envelopes",sf="meta-routing-ids@1",ln="host-frames-slim@1";var af=k({workspaceId:S().min(1).optional(),hostId:S().min(1).optional(),agentMemberId:S().min(1).optional(),caller:S().min(1).max(256).optional()}).strict(),Dy=["unmapped","timedOut","outside"],kI=k({reason:oe(Dy)}).strict();function cf(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 Ly=k({resource:S().min(1),customizationId:S().min(1)}).strict(),er=k({available:Yt(),reason:S().min(1).max(200).optional(),server:Ly.optional()}).strict(),st="ahpd/hostTools",RI=k({resource:S().min(1),_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er.optional()}).strict()}).strict(),CI=k({channel:B("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=_e(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 uf(e,t,r){if(!_e(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 OI=k({channel:S().min(1),resource:S().min(1),reason:B("expired")}).strict();function _e(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var rs="event:all",df="tool:all";var Uy=["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",...Xo],lf=16,ff=49152,hf=262144,Zy=k({id:S().min(1),from:k({memberId:S().min(1)}).strict(),text:S(),replyTo:S().min(1).optional(),deleted:B(!0).optional(),signed:k({keyId:S().min(1),createdAt:S().min(1),signature:S().min(1),clientId:S().min(1),attachmentIds:V(S().min(1))}).strict().optional()}).strict(),jy=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,Fy=V(Zy).min(1).superRefine((e,t)=>{if(e.length>lf){t.addIssue({code:"custom",message:`a wake carries at most ${lf} 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=jy(n);if(o>ff){t.addIssue({code:"custom",message:`triggering envelope ${n.id} is ${o} bytes, over the ${ff}-byte limit`});return}r+=o}if(r>hf)t.addIssue({code:"custom",message:`the triggering envelopes take ${r} bytes, over the ${hf}-byte limit`})}),pf=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:V(S().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:Fy.optional()}).strict(),fn=k({event:oe(Uy),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:oe(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:oe(rr).optional(),errorDetail:S().max(256).optional()}).strict();function mf(e){return fn.parse(e)}var Hy=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],NI=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:oe(Hy),turnId:S().min(1).optional(),part:k({error:k({errorType:S().min(1)})}).optional()})});var gf="Hightea-Host",yf="x-hightea-host";import{createHash as Mf}from"node:crypto";var By=(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,qy=/^[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 Gy(e){let t=pf.safeParse(e._meta);return t.success?t.data:void 0}function _f(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=Gy(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=By(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(Ky(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"||!qy.test(f.turnId))return M("OPERATION_SHAPE_INVALID");if(f.startedAt!==void 0&&typeof f.startedAt!=="number")return M("OPERATION_SHAPE_INVALID");let y=f.message;if(!nr(y)||!it(y,["text","origin"])||typeof y.text!=="string")return M("OPERATION_SHAPE_INVALID");if(!nr(y.origin)||!it(y.origin,["kind"])||y.origin.kind!=="user")return M("OPERATION_SHAPE_INVALID");if(y.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:y.text,origin:{kind:"user"}}}}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i,turnId:f.turnId}}function Ky(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 Vy="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}},Wy=(e)=>e.ifRevision===0,pn=(e)=>e instanceof Error&&/timed? ?out|timeout/iu.test(e.message),wf="x-ahpd-agents://";async function Jy(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-host: 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-host: ${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-host: dropping the services subscription failed: ${n instanceof Error?n.name:typeof n}`)}}return{ok:!0,result:t}}function Yy(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-host: the agents snapshot holds no records");return n.map((o)=>{if(typeof o!=="object"||o===null)throw Error("hightea-host: 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-host: an agents snapshot entry names no id");return{id:s.id,...s.record}}if(typeof s.id!=="string")throw Error("hightea-host: an agents snapshot entry names no id");return s})}async function Xy(e){let t=new Set([...e.agents.values()].map((s)=>s.provider)),r,n;try{r=await e.peer.request("subscribe",{channel:wf},Qt),n=Yy(r)}catch(s){let i=hn(s);if(i!==void 0)return{ok:!1,reason:"refused",...i};if(e.log.error(`hightea-host: ${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:wf})}catch(s){e.log.error(`hightea-host: dropping the agents subscription failed: ${s instanceof Error?s.name:typeof s}`)}return{ok:!0,result:{rows:o}}}async function Qy(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-host: 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=ns(t)&&Array.isArray(t.items)?t.items:void 0;if(r===void 0)return e.log.error("hightea-host: 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=ns(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=uf(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-host: skipped ${o.length} unreadable session row(s): ${o.join("; ").slice(0,500)}`);return{ok:!0,result:{items:n}}}async function Sf(e,t){let r=t_(e.meta);if(r===void 0)return{ok:!1,reason:"outside"};let n=e.method;if(!r_(n)&&!Xt(n))return{ok:!1,reason:"outside"};let o=e.params;if(!ns(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=ef(n,o);if(u!==void 0)return t.log.error(`hightea-host: refused a host request: ${u}`),{ok:!1,reason:"outside"};if(n==="subscribe")return Jy(t);if(n==="listSessions")return Qy(t);if(n==="authenticate")return n_(t,o);return os(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 Xy(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?e_(o):o,d=n==="x-ahpd/agents/put"&&Wy(c)?{...c,owner:Vy}:c;return os(t,n,d)}function e_(e){let{agentMemberId:t,...r}=e;return r}function t_(e){let t=af.safeParse(e);return t.success?t.data:void 0}function ns(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function r_(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 n_(e,t){let r=t.target;if(typeof r.session!=="string"||e.memberOf(r.session)===void 0)return e.log.error("hightea-host: 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-host: 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-host: 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-host: refused an authenticate for a resource that is not this host's server"),{ok:!1,reason:"outside"};return os(e,"authenticate",t)}async function os(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-host: 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 g_,createPublicKey as y_,generateKeyPairSync as __,sign as w_}from"node:crypto";import{appendFile as S_,chmod as v_,readFile as kf,rename as Rf,writeFile as Cf}from"node:fs/promises";import{join as as}from"node:path";function o_(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(o_(e))}import{createPublicKey as s_,verify as i_}from"node:crypto";var a_=Buffer.from("302a300506032b6570032100","hex");function ss(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=s_({key:Buffer.concat([a_,Buffer.from(n.publicKey,"base64url")]),format:"der",type:"spki"});if(s.length!==64||!i_(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 vf(e,t){let r=(a)=>a.deleted===!0?{id:a.id,deleted:!0}:a,n=(a)=>a.deleted===!0||ss(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 c_}from"node:crypto";import{existsSync as u_,readFileSync as d_}from"node:fs";import{join as l_}from"node:path";var f_="trusted-keys.json",h_=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,p_=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,m_=(e)=>Buffer.from(e).toString("base64url");function is(e){if(!p_.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:m_(c_("sha256").update(Buffer.from(e,"base64url")).digest())}}function xf(e){let t=l_(e,f_);if(!u_(t))return{state:"missing",file:t};let r;try{r=JSON.parse(d_(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"?is(s.publicKey):void 0;if(typeof s.name!=="string"||!h_.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 j extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var x_="host-signing-key",bf="hightea-acted-asks.jsonl",gn=600000,b_=2592000000,E_=20;async function Of(e,t=()=>Date.now()){let r=as(e,x_),n;try{n=await kf(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=__("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),c=`${r}.${String(process.pid)}.tmp`;await Cf(c,a,{mode:384,flag:"wx"}),await v_(c,384),await Rf(c,r),n=a}let o;try{if(o=g_({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=y_(o).export({format:"jwk"}).x,i=s===void 0?{error:"no public key"}:is(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 Tf(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:w_(null,o,e.privateKey).toString("base64url")}}async function Ef(e,t){if(e.configDir===void 0)throw new j("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 j("ROOM_ASKS_UNTRUSTED",r.message);let n;try{let s=await xf(e.configDir);n=s.state==="read"?s.keys:[]}catch(s){throw new j("ROOM_ASKS_UNTRUSTED",String(s instanceof Error?s.message:s))}if(n.length===0)throw new j("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 If(e){let[t,r,n]=e.split("/");if(!t||!r||n!==void 0)throw new j("ASK_UNSIGNED",`the wake's thread ref ${e} names no room thread`);return{roomId:t,rootMessageId:r}}function I_(e,t,r){if(t===void 0||t==="")throw new j("ASK_UNSIGNED",`wake ${r.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);return t}function k_(e,t,r,n){let o=new Map;for(let i of e){let a=i.replyTo??i.id;if(a!==r)throw new j("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 j("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}=If(e.threadRef),o=await Ef(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 j("ASK_UNSIGNED",`wake ${e.deliveryId} names no triggering message to check`);let a=s===void 0?await this.#s(I_(this.#e,t,e),r,n,e.afterMessageId,new Set(i)):k_(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 j("ASK_UNSIGNED",`triggering message ${l} is not in thread ${e.threadRef}`);let f=ss(p,o);if(!f.ok)throw new j(f.code,f.why);let y=d.filter((m)=>m.clientId===f.clientId);if(y.some((m)=>m.deliveryId!==e.deliveryId))throw new j("ASK_REPLAYED",`the ask signed as ${f.clientId} (message ${l}) was already acted on under another wake`);if(y.length>0){let m=Math.min(...y.map((_)=>_.at));if(c-m>gn)throw new j("ASK_REPLAYED",`wake ${e.deliveryId} was first admitted at ${new Date(m).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);continue}let g=Date.parse(f.createdAt);if(!Number.isFinite(g)||Math.abs(c-g)>gn)throw new j("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 vf(t,await Ef(this.#e,If(e).roomId))}async#s(e,t,r,n,o){let s=new Map,i=n??r;for(let a=0;a<E_;a++){let c=await this.#e.readThread(e,{roomId:t,messageId:r,after:i});if(!R_(c))throw new j("ASK_UNSIGNED",`thread_read 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=as(this.#e.configDir,bf),n="";try{n=await kf(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw new j("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 j("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<b_);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 Cf(r,t.map((n)=>`${JSON.stringify(n)}
|
|
65
|
+
`).join(""),{mode:384}),await Rf(r,e)}async#c(e,t){e.push(...t);let r=as(this.#e.configDir,bf),n=this.#r.then(()=>S_(r,t.map((o)=>`${JSON.stringify(o)}
|
|
66
|
+
`).join(""),{mode:384}));this.#r=n.catch(()=>{return}),await n}}function R_(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 ds extends Error{}function O_(e,t){if(!tf.includes(e))return!1;return!Xt(e)||typeof t==="string"&&t.startsWith(rf)}function T_(e){let t=e.params.clientSeq;if(typeof t!=="number"||!Number.isInteger(t)||t<1)throw new ds("ahp-host: a dispatch names no clientSeq");return t}var A_=[/No agent provider registered for: /u,/: this conversation has no matching configured ACP process authority/u];function Af(e){if(e instanceof j)return e.code;if(e instanceof ds)return"OPERATION_SHAPE_INVALID";if(e instanceof vt)return"AGENT_NOT_MAPPED";let t=e instanceof Error?e.message:String(e);if(A_.some((r)=>r.test(t)))return"AGENT_NOT_MAPPED";return"WAKE_NOT_SENT"}var St=nf,cs=15000,$_="x-hh/actions";function P_(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 N_(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 fk=k({sessions:V(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:V(Be([S().min(1),V(S().min(1))])),lastStatus:V(Be([S().min(1),fn]))}).strict(),z_=k({event:oe(["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:oe(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:oe(rr).optional(),errorDetail:S().max(256).optional()}).strict(),M_={"session.created":"session/ready","turn.started":"chat/turnStarted","turn.finished":"chat/turnComplete","turn.error":"x-hh/turnFailed"};function D_(e){return{event:M_[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 L_=k({sessions:V(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:V(Be([S().min(1),V(S().min(1))])),lastStatus:V(Ie())}).strict(),U_=(e)=>e.turnId===void 0?e.deliveryId:ir(e.deliveryId,e.turnId);function us(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 $f(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 ls(e,t){let r=L_.safeParse(e);if(!r.success)throw Error(`ahp-host: invalid durable state: ${us(r.error)}`);let n=[],o=0,s=0;if(r.data.lastStatus.forEach((a,c)=>{let d=Be([S().min(1),Ie()]).safeParse(a),u=d.success?d.data[0]:"",l=d.success?fn.safeParse(d.data[1]):void 0,p=d.success&&l?.success===!1?z_.safeParse(d.data[1]):void 0,f=l?.success===!0?l.data:p?.success===!0?D_(p.data):void 0;if(f===void 0){s+=1;let y=d.success&&typeof d.data[1]==="object"&&d.data[1]!==null&&"houseId"in d.data[1],g=p?.success===!1&&y?`pre-0.1.11 shape: ${us(p.error)}`:l?.success===!1?us(l.error):"not a [key, frame] entry";t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (${$f(a)}): ${g}`);return}if(U_(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}] (${$f(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 fs{#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;#g=Promise.resolve();#p;#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.#V(n).catch((o)=>{if(o!==this.#p)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:[St],clientId:e},cs);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.#b();return}let n=ls(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.#U(c.sessionUri)}catch(u){if(Af(u)==="AGENT_NOT_MAPPED"){this.#R(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 y=s.get(a);if(y?.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:y.chatUri,session:y.sessionUri,chat:y.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.#x(a);await this.#E(),this.#b()}#b(){this.#y=!0;for(let e of this.#s.splice(0))this.#T(e)}#R(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-host: 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}`)}#O(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[$_]===!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.#T(e)}#T(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:[]}})}#E(){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.#p===void 0){this.#p=Error("ahp-host: durable state write failed",{cause:t});for(let r of this.#r.values())r.cancelled=!0;this.options.log.error(`${this.#p.message}: ${String(t)}`)}throw this.#p}),this.#g}async#B(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.#x({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-host: an initialize frame carries no id; nothing to answer");return}this.#O(t,e.params);return}if(!this.#y||this.#p!==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&&O_(r,t)){let o=String(t??""),s=await Sf({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.#I(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.#B(t,e.params).catch(()=>{if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"OPERATION_SHAPE_INVALID"})});let n=_f(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-host: 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.#E();return}this.#e.set(n.sessionKey,{sessionUri:d}),await this.#E()})}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.#U(a):await this.#A(a);this.#e.set(n.sessionKey,{sessionUri:a,chatUri:c}),this.#c.set(a,Promise.resolve()),await this.#E(),await this.#x({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.#Z(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=Af(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#L(e,t){let r=this.#c.get(e);if(r===void 0)r=this.#U(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#U(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.#A(e)}async#A(e){let t=await this.peer.request("subscribe",{channel:e},cs);this.#l.add(e),this.#N(e,t?.snapshot?.state?.customizations),this.#_(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#Z(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.#F(c);return}if(this.options.admitTurn!==void 0)await this.options.admitTurn(r);await this.#L(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.#E();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.#j(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:T_(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.#E(),s.cancelled){this.#r.delete(e),await this.#x({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.#z(s);return}if(!this.#l.has(o.chatUri))this.#l.add(o.chatUri),this.peer.request("subscribe",{channel:o.chatUri},cs);this.peer.notify("dispatchAction",{...t.params,clientSeq:++this.#w})}#j(e,t){return[...this.#r.values()].filter((r)=>r.sessionUri===e&&r.chatUri===t)}#K(e){this.#P(e)}#$(e,t){let r=this.#I(e);if(r===void 0||t.id!==r.customizationId)return;if(e===""||this.agentMemberOf(e)===void 0)return;let n=_e(t.state)?t.state:void 0;if(n?.kind!=="authRequired"||n.reason!=="expired")return;this.cloud.authRequired({channel:e,resource:r.resource,reason:"expired"})}#I(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}}#N(e,t){let r=this.options.hostTools;if(r===void 0||!Array.isArray(t))return;let n=t.find((s)=>_e(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})}#_(e,t){if(this.options.hostTools===void 0)return;let r=_e(t)?_e(t._meta)?t._meta:t:void 0,n=er.safeParse(r?.[st]);if(n.success)this.#h.set(e,n.data)}#q(e){let t=this.agentMemberOf(e),r=this.#h.get(e);if(t===void 0||r===void 0)return;let n=this.#I(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(!_e(e)){this.options.log.error("hightea-host: a root/sessionSummaryChanged carries no params object");return}let t=e.session;if(typeof t!=="string"||t===""){this.options.log.error("hightea-host: a root/sessionSummaryChanged names no session");return}let r=this.agentMemberOf(t);if(r===void 0)return;let n=_e(e.changes)?e.changes:void 0,o=n!==void 0&&_e(n._meta)?n._meta:void 0,s=tr(o,r,this.#I(t));if(s===void 0){this.options.log.error(`hightea-host: ${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-host: ${t} changed ${st} 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#V(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.#N(t.channel,t.action.customizations),this.#u.get(t.channel)!==i)this.#q(t.channel)}return}if(t?.action?.type==="session/mcpServerStateChanged"){this.#$(typeof t.channel==="string"?t.channel:"",t.action);return}if(_e(e)&&e.method==="root/sessionSummaryChanged")return this.#K(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.#j(l,u),f=a&&typeof i.turnId==="string"?i.turnId:"",y=p.filter((_)=>!_.cancelled&&!_.finishing&&_.stopReason===void 0),g=a&&f==="",m=f!==""?p.find((_)=>_.turnId===f):y.length===1?y[0]:void 0;if(m===void 0||g){this.#v++;let _=f!==""?"INPUT_REQUEST_UNMATCHED_TURN":"INPUT_REQUEST_UNATTRIBUTED";this.options.log.error(`hightea-host: ${_} ${JSON.stringify({sessionId:l,chatId:u,kind:i.kind,requestId:d,droppedCount:this.#v,...f===""?{liveWakeCount:y.length}:{turnId:f}})}`)}if(m===void 0||m.cancelled||m.finishing||m.stopReason!==void 0)return;if(m.stopReason=g?"OPERATION_SHAPE_INVALID":c?"INPUT_REQUIRED":"APPROVAL_REQUIRED",a&&!g){let _=typeof i?.toolCall?.toolName==="string"?i.toolCall.toolName:"",x=/^[A-Za-z0-9_.:-]{1,64}$/u.test(_)?`tool ${_}`:_===""?"a tool it did not name":`tool name withheld (${_.length} chars)`;(this.options.log.warn??this.options.log.error)(`hightea-host: turn ${m.turnId} needs approval for ${x}`)}if(m.stopStatusCode=g?"INPUT_REQUEST_UNATTRIBUTED":m.stopReason,g)m.stopDetail=`INPUT_REQUEST_UNATTRIBUTED:${d}`.slice(0,256);this.peer.notify("dispatchAction",{channel:m.chatUri,clientSeq:++this.#w,action:{type:"chat/turnCancelled",turnId:m.turnId,duration:Math.max(0,Date.now()-m.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.#x({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.#x(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.#z(o)}}async#z(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=N_(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.#p!==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.#x({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.#z(e)}#x(e,t){let r=mf(e);if(this.#a.set(r.turnId===void 0?r.deliveryId:ir(r.deliveryId,r.turnId),r),this.options.store===void 0)return this.#F(r,t),Promise.resolve();return this.#E().then(()=>{this.#F(r,t)})}#F(e,t){if(!this.#S)return this.cloud.status(e);this.cloud.action(P_(e,{...this.#m===""?{}:{clientId:this.#m},...t===void 0?{}:{startedAtMs:t}}))}}var yn=Be([S().min(1),S().min(1),S().min(1)]),Z_=k({id:S(),version:B(1),tuple:yn,owner:S().min(1),sessionUri:S().regex(or)}).strict(),Pf=(e)=>`session-${Mf("sha256").update(e).digest("hex").slice(0,32)}`,Nf=k({id:S(),version:B(1),tuple:yn,sessionUri:S().regex(or),chatUri:S().min(1)}).strict(),zf=(e)=>`chat-${Mf("sha256").update(e).digest("hex").slice(0,32)}`;function Df(e,t,r,n,o){let s=t[0];if(s===void 0)throw Error("ahp-host: no plugin owner to record a session under");let i=(g)=>g!==void 0&&g!==null&&t.includes(g),a=new Map,c=new Map,d=async(g,m)=>{if(o===void 0||m.chatUri===void 0||c.get(g)===m.chatUri)return;let _=yn.parse(JSON.parse(g)),x=zf(g);try{await o.put({id:x,version:1,tuple:_,sessionUri:m.sessionUri,chatUri:m.chatUri},{createOnly:!0})}catch(v){if(v?.code!==-32010)throw v;let b=Nf.safeParse(await o.get(x));if(!b.success||b.data.sessionUri!==m.sessionUri||b.data.chatUri!==m.chatUri)throw Error("ahp-host: conflicting durable session chat",{cause:v})}c.set(g,m.chatUri)},u=async()=>{let g=new Map;for(let m of await o?.list()??[]){let _=Nf.safeParse(m);if(!_.success)throw Error("ahp-host: invalid durable session chat");let x=JSON.stringify(_.data.tuple);if(_.data.id!==zf(x))throw Error("ahp-host: durable session chat has a different key");g.set(x,{sessionUri:_.data.sessionUri,chatUri:_.data.chatUri})}return g},l=(g)=>{let m=Z_.safeParse(g);if(!m.success)throw Error("ahp-host: invalid durable session mapping");let _=m.data,x=JSON.stringify(_.tuple);if(_.id!==Pf(x)||!i(_.owner))throw Error("ahp-host: durable session mapping has a different key or owner");return[x,{sessionUri:_.sessionUri}]},p=async(g,m)=>{let _=yn.parse(JSON.parse(g));if(JSON.stringify(_)!==g||!or.test(m))throw Error("ahp-host: invalid session mapping to publish");let x=a.get(g);if(x!==void 0)return x.sessionUri;let v=Pf(g),b=m;try{await e.put({id:v,version:1,tuple:_,owner:s,sessionUri:m},{createOnly:!0})}catch(E){if(E?.code!==-32010)throw E;let C=await e.get(v);if(C===void 0)throw E;let[I,O]=l(C);if(I!==g)throw Error("ahp-host: conflicting durable session mapping",{cause:E});if(O.sessionUri!==m&&!i(await r(O.sessionUri)))throw Error("ahp-host: durable session belongs to an unknown or different owner",{cause:E});b=O.sessionUri}return a.set(g,{sessionUri:b}),b},f=async(g,m)=>{if(await p(g,m.sessionUri)!==m.sessionUri)throw Error("ahp-host: conflicting durable session mapping")},y=(g)=>e.put({id:"state",version:2,state:{dispatched:g.dispatched,lastStatus:g.lastStatus}});return{reserve:p,load:async()=>{let g=await e.get("state"),m={sessions:[],dispatched:[],lastStatus:[]};if(g!==void 0){if(g.id!=="state"||g.version!==1&&g.version!==2||!("state"in g))throw Error("ahp-host: invalid durable state record");let x=g.version===1?g.state:typeof g.state==="object"&&g.state!==null?{sessions:[],...g.state}:g.state,v=ls(x,n);if(g.version===2&&v.sessions.length!==0)throw Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");m=v}let _=new Map;for(let x of await e.list()){if(x.id==="state")continue;let[v,b]=l(x);if(!i(await r(b.sessionUri)))throw Error("ahp-host: durable session belongs to an unknown or different owner");_.set(v,b)}a.clear();for(let[x,v]of _)a.set(x,v);for(let[,x]of m.sessions)if(!i(await r(x.sessionUri)))throw Error("ahp-host: legacy session belongs to an unknown or different owner");for(let[x,v]of m.sessions)await f(x,v),_.set(x,v);if(g?.version===1)await y(m);c.clear();for(let[x,v]of await u()){let b=_.get(x);if(b===void 0||b.sessionUri!==v.sessionUri)throw Error("ahp-host: durable session chat names no mapping or a different session");_.set(x,{sessionUri:b.sessionUri,chatUri:v.chatUri}),c.set(x,v.chatUri)}return{sessions:[..._],dispatched:m.dispatched,lastStatus:m.lastStatus}},save:async(g)=>{for(let[m,_]of g.sessions)await f(m,_),await d(m,_);await y(g)}}}import{randomUUID as j_}from"node:crypto";var F_=15000,H_=(e)=>{if(e===null||typeof e!=="object")return;let t=e.message;return typeof t==="string"&&rr.includes(t)?t:void 0};function Lf(e){let{log:t,receive:r}=e,n=!1,o=1000,s,i,a=new Map,c=(m,_=!0)=>{if(_)t.error(`hightea-host: ${m}`);for(let x of a.values())clearTimeout(x.timer),x.reject(Error(m));a.clear()},d=(m,_)=>{if(!n&&m!==void 0&&m===i&&m.live&&m.socket?.readyState===1)try{return m.socket.send(JSON.stringify(_)),!0}catch{}return t.error("hightea-host: CONTROL_SOCKET_UNAVAILABLE"),!1},u=(m)=>d(i,m),l=(m,_,x)=>{if(m===void 0||m.readyState>=2)return;try{if(_===void 0)m.close();else m.close(_,x)}catch{t.error("hightea-host: CONTROL_SOCKET_CLOSE_FAILED")}},p=(m,_)=>{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,m,_)},f=(m,_)=>{let x;try{x=JSON.parse(String(m.data))}catch{t.error("hightea-host: CONTROL_FRAME_INVALID");return}if(x!==null&&typeof x==="object"&&!Array.isArray(x)){let v=x;if(v.method===void 0&&(("result"in v)||("error"in v))){let b=typeof v.id==="string"?a.get(v.id):void 0;if(b===void 0){t.error("hightea-host: CONTROL_RESPONSE_UNKNOWN");return}if(a.delete(v.id),clearTimeout(b.timer),v.jsonrpc==="2.0"&&"result"in v&&!("error"in v))b.resolve(v.result);else{let E="error"in v?H_(v.error):void 0;t.error(`hightea-host: CONTROL_REQUEST_REFUSED${E===void 0?"":` ${E}`}`),b.reject(Error(E===void 0?"CONTROL_REQUEST_REFUSED":`CONTROL_REQUEST_REFUSED ${E}`))}return}}r(x,_)},y=()=>{if(n)return;let m={live:!0,opened:!1};i=m;let _=()=>{if(n||s!==void 0)return;let b=o;o=Math.min(o*2,60000),s=setTimeout(()=>{s=void 0,y()},b)},x=(b)=>{if(n||i!==m||!m.live)return;m.live=!1,c(b),l(m.socket),_()},v=(b,E)=>{if(n||i!==m)return;t.error(`${E===void 0||E===""?`hightea-host: CONTROL_SOCKET_REFUSED:${b}`:`hightea-host: CONTROL_SOCKET_REFUSED:${b}: ${E}`}`),p()};try{let b=e.dial((I)=>{if(I===401||I===403)v(I);else x("CONTROL_SOCKET_ERROR")});m.socket=b;let E={send:(I)=>d(m,I),close:(I,O)=>p(I,O)};b.addEventListener("message",(I)=>{if(!n&&i===m&&m.live)f(I,E)}),b.addEventListener("error",()=>x("CONTROL_SOCKET_ERROR")),b.addEventListener("close",(I)=>{if(I.code===4003||I.code===4004)v(I.code,I.reason);else x("CONTROL_SOCKET_CLOSED")});let C=()=>{if(n||i!==m||!m.live||m.opened)return;m.opened=!0,o=1000,e.opened?.(E)};if(b.addEventListener("open",C),n||!m.live)l(b);else if(b.readyState===1)C()}catch{x("CONTROL_SOCKET_ERROR")}},g=(m,_,x)=>new Promise((v,b)=>{let E=setTimeout(()=>{a.delete(m),t.error("hightea-host: CONTROL_REQUEST_TIMEOUT"),b(Error("CONTROL_REQUEST_TIMEOUT"))},F_);if(a.set(m,{resolve:v,reject:b,timer:E}),!u({jsonrpc:"2.0",id:m,method:_,params:x}))a.delete(m),clearTimeout(E),b(Error("CONTROL_SOCKET_UNAVAILABLE"))});return queueMicrotask(y),{send:u,close:p,answer:(m,_)=>u(_.ok?{jsonrpc:"2.0",id:m,result:null}:{jsonrpc:"2.0",id:m,error:{code:-32000,message:_.code}}),reply:(m,_)=>u("result"in _?{jsonrpc:"2.0",id:m,result:_.result}:{jsonrpc:"2.0",id:m,error:_.error}),status:(m)=>u({jsonrpc:"2.0",method:"x-hightea/status",params:m}),sessionChanged:(m)=>void u({jsonrpc:"2.0",method:"root/sessionSummaryChanged",params:m}),action:(m)=>u({jsonrpc:"2.0",method:"action",params:m}),authRequired:(m)=>u({jsonrpc:"2.0",method:"auth/required",params:m}),sourcePush:(m)=>g(`push:${j_()}`,"x-hightea/source/push",m),hostRequestAnswer:(m,_)=>void u({jsonrpc:"2.0",id:m,...cf(_)})}}import{spawn as Y_}from"node:child_process";import{createHash as Wf}from"node:crypto";import{createInterface as X_}from"node:readline";import{randomUUID as Uf}from"node:crypto";var _n=1e4,B_=1024;function q_(e,t,r){let n=0;while(n<e.length&&t+ne(e[n])>r)n++;let o=[],s=t;for(let i=n;i<e.length;i++){let a=e[i],c=ne(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_"+Uf();#o=0n;#r=[];#s=!1;#n;#l=-1/0;#c=0;#f=-1/0;#u=!0;#h=new AbortController;#a;#g;#p;#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.#p=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.#h.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_"+Uf(),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.#h.signal.aborted)return;let e=this.#f-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.#p):this.#g,r=this.#l+t-this.#y();if(r>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#m()},r);return}let n=cn-B_,o=ne({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:{epoch:this.#e,ordinal:"0"},observations:[]}),{dropped:s,batch:i}=q_(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,`${ne(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.#l=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.#f=-1/0;let u=Gl.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.#f=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.#h.abort(),this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}}import{spawn as G_}from"node:child_process";import{createInterface as K_}from"node:readline";var Zf=65536,V_=2000,jf=16777216,W_=8,J_=5000;class me 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 Ff=(e,t)=>{let[r,...n]=e;if(r===void 0)throw new me("page-serve-no-command","the page reader has no command to run");let o=G_(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 b=a;if(b===void 0)return;if(a=void 0,b.timer!==void 0)clearTimeout(b.timer);b.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);y(v.request,v.timeoutMs,v.resolve,v.reject)}function y(v,b,E,C){let I={seq:++d,traverse:"traverse"in v&&v.traverse===!0,pages:[],bytes:0,askedAt:Date.now(),deadline:Date.now()+b,resolve:E,reject:C,timer:void 0};a=I,I.timer=setTimeout(()=>{g("page-serve-timeout",`the reader did not answer seq ${I.seq} in ${b} ms`)},b);try{o.stdin.write(JSON.stringify({seq:I.seq,request:v})+`
|
|
68
|
+
`)}catch(O){g("page-serve-write-failed",`the request could not be written: ${O instanceof Error?O.message:String(O)}`)}}let g=(v,b)=>{p(new me(v,b)),wn(o,"SIGKILL")},m=(v)=>{if(v.trim()==="")return;let b;try{b=JSON.parse(v)}catch{g("page-serve-frame-unparsable",`the reader answered a line that is not JSON: ${v.slice(0,120)}`);return}let E=b,C=typeof E.rss==="number"&&Number.isFinite(E.rss)?E.rss:void 0,I=a;if(I===void 0){g("page-serve-frame-unasked",`the reader answered seq ${String(E.seq)} with no request outstanding`);return}if(E.seq!==I.seq){g("page-serve-frame-out-of-order",`the reader answered seq ${String(E.seq)} while seq ${I.seq} was asked`);return}let O=E.refusal;if(O!==void 0&&O!==null){if(a=void 0,I.timer!==void 0)clearTimeout(I.timer);I.resolve({...C===void 0?{}:{rss:C},refusal:{code:typeof O.code==="string"?O.code:"page-serve-refused",message:typeof O.message==="string"?O.message:"the reader refused without a message",...typeof O.hint==="string"?{hint:O.hint}:{}}}),f();return}if(E.page===void 0&&E.journal!==void 0){let D=E.journal;if(!(D!==null&&typeof D==="object"&&!Array.isArray(D)&&typeof D.generation==="string"&&typeof D.head==="number"&&Number.isFinite(D.head)&&typeof D.asOf==="number"&&Number.isFinite(D.asOf)&&Array.isArray(D.lines)&&typeof D.more==="boolean")){g("page-serve-journal-malformed",`the reader answered seq ${I.seq} outside the journal shape`);return}if(a=void 0,I.timer!==void 0)clearTimeout(I.timer);I.resolve({...C===void 0?{}:{rss:C},journal:{generation:D.generation,head:D.head,asOf:D.asOf,lines:D.lines,more:D.more}}),f();return}if(E.page===void 0&&E.progress!==void 0){if(a=void 0,I.timer!==void 0)clearTimeout(I.timer);I.resolve({...C===void 0?{}:{rss:C},progress:E.progress}),f();return}if(E.page===null||typeof E.page!=="object"||Array.isArray(E.page)){g("page-serve-frame-malformed",`the reader answered seq ${I.seq} outside the page shape`);return}if(I.bytes+=v.length,I.bytes>jf){g("page-serve-answer-too-large",`the reader's answer to seq ${I.seq} exceeded its byte budget (${jf} bytes)`);return}let G=E.page.complete;if(I.pages.push(E.page),I.traverse&&G!==!0)return;if(a=void 0,I.timer!==void 0)clearTimeout(I.timer);I.resolve({pages:I.pages,...C===void 0?{}:{rss:C}}),f()};K_({input:o.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",m),o.stderr.setEncoding("utf8").on("data",(v)=>{if(s.length<Zf)s+=v}),o.stdin.on("error",()=>{if(s.length<Zf)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)=>{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=
|
|
72
|
-
`);return t.digest("hex")}function
|
|
70
|
+
hightea-page-serve: ${v.message}`});let _=new Promise((v)=>{o.on("close",(b,E)=>{wn(o,"SIGKILL"),i={code:E===null?b:null,stderr:s},p(new me("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 me("page-serve-reader-exited",`the reader is gone (${xt(i)})`))}u(i),v()})}),x=async()=>{if(i!==void 0)return;o.stdin.end(),wn(o,"SIGTERM");let v=setTimeout(()=>wn(o,"SIGKILL"),V_);await _,clearTimeout(v)};return t.addEventListener("abort",()=>{x()},{once:!0}),{ask(v,b){if(i!==void 0)return Promise.reject(new me("page-serve-reader-exited",`the reader is gone (${xt(i)})`));if(a!==void 0){if(Date.now()>=a.deadline){let Q=`the reader did not answer seq ${a.seq} by its ${a.deadline-a.askedAt} ms deadline, and the slot was still held`;return g("page-serve-timeout",Q),Promise.reject(new me("page-serve-timeout",Q))}if(c.length>=W_)return Promise.reject(new me("page-serve-busy",`a page request is already outstanding and ${c.length} more are waiting`));let O=Math.min(b,J_),G={request:v,timeoutMs:b,waitMs:O,resolve:()=>{return},reject:()=>{return},timer:void 0},D=new Promise((Q,Ne)=>{G.resolve=Q,G.reject=Ne});return G.timer=setTimeout(()=>{let Q=c.indexOf(G);if(Q<0)return;c.splice(Q,1),G.reject(new me("page-serve-busy",`a page request waited ${O} ms for the one slot and seq ${a===void 0?"none":a.seq} is still unanswered`))},O),c.push(G),D}let E=()=>{return},C=()=>{return},I=new Promise((O,G)=>{E=O,C=G});return y(v,b,E,C),I},exited:l,close:x}};var bn=16777216,Q_=8,ew=900000,hs=1000,Hf=3,tw=5000,rw=536870912,nw=30000,ow=2000,sw=250,iw=200,Sn=5000,aw=2000,cw=3,uw=300000,dw=20;function Bf(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 xn 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 ys{sourceId;#e;#o=0;#r;#s=new Map;#n;#l=0;#c;#f;#u;#h=!1;#a=0;#g=-1/0;#p;#y=!1;#w=!1;#v=0;#S;#m;#b;#R;#O=!1;#T;#E=0;#B;#L;#U=!1;#A;#Z;#C;#j=!1;#K=!1;#$=!1;#I;#N;#_;#q=!1;#P;#V;#z;#x=[];#F=-1/0;#d=new AbortController;#ge;#t;#ye;#re;#ne;#M;#i;#_e;#H;#oe;#we;#D;#se;#W=!1;#J=-1/0;#ie=0;#ae=0;#ce=new Map;constructor(e){this.#t=e,this.sourceId=e.config.sourceId,this.#ye=e.run??_s,this.#re=e.coalesceMs??2000,this.#ne=e.hintCoalesceMs??Math.min(this.#re,100);let t=e.journalPollMs??sw;if(!(Number.isFinite(t)&&t>=0))throw Error(`journalPollMs must be a finite number of milliseconds, 0 or more, not ${t}`);if(this.#M=t,this.#H=e.readDuty??e.config.readDuty??0.1,!(this.#H>0&&this.#H<=1))throw Error(`readDuty must be in (0, 1], not ${this.#H}`);if(this.#oe=Bf("minIncrementalReadGapMs",e.config.minIncrementalReadGapMs),this.#we=Bf("minFullReadGapMs",e.config.minFullReadGapMs),this.#D=e.readRetryMs??2000,!(Number.isFinite(this.#D)&&this.#D>=0))throw Error(`readRetryMs must be a finite number of milliseconds, 0 or more, not ${this.#D}`);let r=e.progressCeilingMs??ow;if(!(Number.isFinite(r)&&r>=0))throw Error(`progressCeilingMs must be a finite number of milliseconds, 0 or more, not ${r}`);this.#se=r;let n=e.watchFloorMs??aw;if(!(Number.isFinite(n)&&n>=0))throw Error(`watchFloorMs must be a finite number of milliseconds, 0 or more, not ${String(n)}`);if(this.#V=n,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.#z=e.watchRefreshMs,this.#i=e.now??Date.now,this.#_e=new Map(Object.entries(e.config.members).map(([o,s])=>[s,o])),this.#e=new ar({sourceId:e.config.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(o)=>e.push(o),log:e.log,coalesceMs:this.#re,now:this.#i,onOmit:(o,s)=>this.#he(o,s),onOverflow:()=>{this.#s.clear();let o=this.#r;if(o===void 0){e.log.error(`hightea-source: ${e.config.sourceId} overflowed before its first read; reading for the new epoch`),this.#k().catch((i)=>e.log.error(`hightea-source: reading ${e.config.sourceId} after an overflow failed: ${W(i)}`));return}this.#r=void 0;let s=new Map(o.rows.map((i)=>[i.row.address,{key:i.key,row:i.row}]));this.#Q(`${this.#e.epoch}.${++this.#o}`,o.snapshot,s)}})}get epoch(){return this.#e.epoch}start(){this.#G(),this.#k().catch((e)=>this.#t.log.error(`hightea-source: the first read of ${this.sourceId} failed: ${W(e)}`)),this.#ge=this.#Xe(),this.#le()}async stop(){if(this.#d.abort(),this.#e.stop(),this.#_!==void 0)clearTimeout(this.#_);if(this.#C!==void 0)clearTimeout(this.#C);if(this.#xe(),this.#p!==void 0)clearTimeout(this.#p);await this.#ge,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: ${W(e)}`))}hint(e){if(e!==void 0){this.#Pe(e);let i=bw(e);if(i!==void 0&&(this.#I===void 0||i.at<this.#I))this.#I=i.at,this.#N=i.source}if(this.#d.signal.aborted)return;if(this.#n!==void 0||this.#_!==void 0){this.#$=!0;return}let t=this.#c!==void 0&&!this.#W,r=t?this.#oe:this.#we,n=this.#J+Math.max(this.#ie*(1/this.#H-1),r)-this.#i(),o=Math.max(this.#ne,n),s=this.#I===void 0?void 0:this.#i()-this.#I;this.#t.log.info?.(`hightea-source: ${this.sourceId} change hint: last read ${Math.round(this.#ie)} ms at readDuty ${this.#H}, ${t?"incremental":"full"} floor ${Math.round(r)} ms, progress ceiling ${Math.round(this.#se)} ms, hint window ${Math.round(this.#ne)} ms, next read in ${Math.round(o)} ms, change age ${s===void 0?"unavailable":`${Math.round(s)} ms${this.#N===void 0?"":` from ${this.#N}`}`}`),this.#_=setTimeout(()=>{this.#_=void 0,this.#q=!0,this.#k(t).catch((i)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${W(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.#fe();else this.#xe();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.#Ce(e.args,t)};case"read":{let n=await this.#Te();return{...t,op:"read",outcome:"applied",body:{observation:this.#ue(n,e.args.address)}}}case"assign":{let n=this.#ce.get(e.args.intentId);if(n!==void 0)return await n;let o=this.#Oe(e,t).finally(()=>this.#ce.delete(e.args.intentId));return this.#ce.set(e.args.intentId,o),await o}}}catch(n){if(n instanceof xn)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: ${W(n)}`),r("SOURCE_UNAVAILABLE","unknown")}}async#Ce(e,t){let r=e.page===void 0?void 0:yw(e.page),n=r===void 0?void 0:this.#s.get(r.generation),o=n??await this.#k(!1,!0);if(n===void 0)this.#F=this.#i();let s=n===void 0?0:r.offset,i=this.#Be(),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:gw(o.generation,l),complete:l>=o.rows.length,...this.#T===void 0?{}:{progressAsOf:new Date(this.#T).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=ne(l);if(ne({...t,op:"list",outcome:"applied",body:c(u+1,[])})+d+p+a.length>ot){if(a.length===0)throw new xn(l.address);break}a.push(l),d+=p,u++}return c(u,a)}async#Oe(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.#ee(s);if(c===void 0||d===void 0)return{...t,op:"assign",outcome:"refused",code:"AGENT_NOT_MAPPED"};let u=this.#Ye(n);if(u===void 0)return{...t,op:"assign",outcome:"refused",code:"INVALID_ADDRESS"};if(a!==void 0){let x=await this.#Se(),v=this.#ue(x,n),b=v.change.op==="upsert"?v.change.row.version:null;if(b!==a){let E=v.change.op==="upsert"?v.change.row.columns.owner??null:null;if((E===null?null:this.#ee(E))!==c)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:E},revision:b,observation:v}}}}let l;if(this.#t.config.serviceIdentity)try{let x=this.#t.serviceIdentityEnvironment?.(this.sourceId);if(!x?.HAB_ID_TOKEN_FILE)throw Error("SERVICE_IDENTITY_UNAVAILABLE");l={HAB_ID_TOKEN_FILE:x.HAB_ID_TOKEN_FILE}}catch(x){if(!(x instanceof Error)||!/^SERVICE_IDENTITY_(?:NOT_GRANTED|UNAVAILABLE)(?::|$)/u.test(x.message))throw x;let v=x instanceof Error&&x.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.#te(["issues","assign",u,c,"--id",i,"--expected-owner",JSON.stringify(d),"--requested-by",JSON.stringify(p)],l),y=await this.#Se(),g=this.#ue(y,n),m=g.change.op==="upsert"?g.change.row.columns.owner:null;if(f.code===0)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:m},observation:g}};let _=g.change.op==="upsert"?this.#ee(g.change.row.columns.owner??""):null;if(_===c)return{...t,op:"assign",outcome:"applied",body:{intentId:i,result:{owner:m},observation:g}};if((_??null)!==d)return{...t,op:"assign",outcome:"rejected",code:"STALE_EXPECTATION",body:{intentId:i,result:{owner:m},observation:g}};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"}}#ue(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#Se(){let e=this.#o;for(;;){let t=this.#n;if(t===void 0)return this.#k();if(this.#l>e)return t;await t.catch(()=>{return})}}async#Te(){return this.#r??await this.#k()}#G(){if(this.#d.signal.aborted||this.#h)return;if(this.#u!==void 0)return this.#u;if(this.#i()<this.#g)return;let e=this.#t.openServe??Ff,t;try{t=e([...this.#t.config.yrd,"issues","list-page-serve","--project-root",this.#t.config.projectRoot],this.#d.signal)}catch(r){this.#de(void 0,{code:null,stderr:W(r)});return}return this.#u=t,t.exited.then((r)=>this.#de(t,r),(r)=>this.#de(t,{code:null,stderr:W(r)})),t}#de(e,t){if(e!==void 0&&this.#u!==e)return;if(this.#u===e)this.#u=void 0;if(this.#d.signal.aborted)return;this.#a++;let r=Math.min(this.#D*2**Math.min(this.#a-1,5),60000);if(this.#g=this.#i()+r,Sw(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.#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.#p!==void 0)return;this.#p=setTimeout(()=>{if(this.#p=void 0,this.#d.signal.aborted||this.#G()===void 0)return;this.#t.log.info?.(`hightea-source: the km reader of ${this.sourceId} is back; reading it once to catch up`),this.#k().catch((n)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after the km reader returned failed: ${W(n)}`))},r)}#le(){if(this.#d.signal.aborted||this.#M===0)return;this.#Ae().then((e)=>{if(this.#d.signal.aborted)return;this.#C=setTimeout(()=>{this.#C=void 0,this.#le()},e)},(e)=>{if(this.#d.signal.aborted)return;this.#Y(`the journal poll failed: ${W(e)}`),this.#C=setTimeout(()=>{this.#C=void 0,this.#le()},Sn)})}async#Ae(){if(this.#n!==void 0)return this.#M;let e=this.#G();if(e===void 0)return this.#M;let t;try{t=await e.ask({journal:{after:this.#A??0,limit:iw}},this.#t.childTimeoutMs??120000)}catch(s){return this.#Y(`the journal poll could not talk to the km reader: ${W(s)}; the change feed is the wake`),Sn}if("refusal"in t)return this.#Y(`the km reader refused the journal frame (${t.refusal.code}: ${t.refusal.message}); the change feed is the wake`),Sn;if(!("journal"in t))return this.#Y("the km reader answered neither a journal frame nor a refusal; the change feed is the wake"),Sn;this.#j=!1;let r=t.journal;if(this.#Z===void 0)return this.#Z=r.generation,this.#A=r.head,this.#M;if(r.generation!==this.#Z)return this.#Z=r.generation,this.#A=r.head,this.#t.log.info?.(`hightea-source: ${this.sourceId}: km's vault store was replaced (generation ${r.generation}); reading whole once`),this.hint(),this.#M;let n=this.#A??0,o=r.lines.filter((s)=>{let i=s?.seq;return typeof i==="number"&&Number.isSafeInteger(i)&&i>n});if(o.length>0){let s=o[o.length-1];this.#A=s.seq,this.hint(JSON.stringify({seq:s.seq,ts:s.ts,source:s.source}))}return r.more?0:this.#M}#Y(e){if(this.#j)return;this.#j=!0,this.#t.log.error(`hightea-source: ${this.sourceId}: ${e}`)}async#$e(e){let t=this.#G();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??rw;if(s.rss!==void 0&&s.rss>i)this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, rss ${Vf(s.rss)} MiB is above its ${Vf(i)} MiB ceiling (restart ${this.#v+1})`),t.close();if(!("pages"in s))throw new me("page-serve-frame-malformed","the reader answered a progress frame where the page was asked for");return{ok:!0,stdout:vw(s.pages),from:"reader"}}catch(n){if(!(n instanceof me))throw n;this.#t.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${W(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.#te(["issues","list-page",JSON.stringify(e)]);return r.code===0?{ok:!0,stdout:r.stdout,from:"one-shot"}:{ok:!1,stderr:r.stderr}}#Pe(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.#U)return;this.#U=!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`)}}#ve(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}#k(e=!1,t=!1,r=!1){if(this.#n!==void 0){if(this.#$=!0,t)this.#O=!0;return this.#n}if(this.#_!==void 0)clearTimeout(this.#_),this.#_=void 0;this.#$=!1,this.#I=void 0,this.#N=void 0;let n=this.#i(),o=this.#De(e,t,r).then((s)=>(this.#ae=0,s),(s)=>{throw this.#Ne(),s}).finally(()=>{if(this.#n=void 0,this.#J=this.#i(),this.#ie=this.#J-n,this.#fe(),this.#$&&!this.#d.signal.aborted)this.#$=!1,this.hint()});return this.#n=o,this.#l=this.#o,o}#Ne(){if(this.#d.signal.aborted||this.#_!==void 0)return;this.#ae++;let e=Math.min(this.#D*2**Math.min(this.#ae-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.#k().catch((t)=>this.#t.log.error(`hightea-source: retrying ${this.sourceId} after a failed read failed: ${W(t)}`))},e)}#ze(){if(this.#z!==void 0)return this.#z;let e=[...this.#x].sort((r,n)=>r-n),t=e.length===0?0:e[Math.floor(e.length/2)];return Math.max(this.#V,10*t)}#fe(){if(this.#d.signal.aborted||!this.#e.watching||this.#P!==void 0)return;let e=this.#ze();if(!(e>0))return;let t=Math.max(this.#J,this.#F),r=Math.max(0,e-(this.#i()-t));this.#P=setTimeout(()=>{if(this.#P=void 0,this.#d.signal.aborted||!this.#e.watching)return;if(this.#n!==void 0){this.#fe();return}this.#k(!0,!0,!0).catch((n)=>this.#t.log.error(`hightea-source: the watcher read of ${this.sourceId} failed: ${W(n)}`))},r)}#xe(){if(this.#P===void 0)return;clearTimeout(this.#P),this.#P=void 0}#Me(){if(this.#d.signal.aborted||this.#_!==void 0)return;this.#_=setTimeout(()=>{if(this.#_=void 0,this.#n!==void 0){this.#$=!0;return}this.#k(!0).catch((e)=>this.#t.log.error(`hightea-source: reading ${this.sourceId} after a trailing notice failed: ${W(e)}`))},this.#oe)}async#De(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.#je(o,s,e,t,r);if(i!==void 0)return i}return await this.#Le(o)}catch(s){if(n>=Hf||!(s instanceof cr)||!Kf(s.stderr))throw s;this.#t.log.error(`hightea-source: read of ${this.sourceId} restarted after the vault moved (${n}/${Hf}): ${bt(s.stderr)}`),await this.#Ge()}}}async#Le(e){let t=await this.#Ue(e);if(t!==void 0)return t;return await this.#Ze(e)}async#Ue(e){if(this.#f===!1)return;let t={binding:this.sourceId,population:"all-issues",generation:e,limit:hs,traverse:!0,progress:!0},r=await this.#te(["issues","list-page",JSON.stringify(t)]);if(r.code!==0){if(!ww(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=pw(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.#pe(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#b={value:n.progress,at:s};return this.#X(o,n.progress,s),this.#Re(n.head),this.#ve(n.head),this.#Q(e,ms(o),o)}async#Ze(e){let t={binding:this.sourceId,population:"all-issues",generation:e,limit:hs,progress:!0},r=await this.#te(["issues","list-page",JSON.stringify(t)]);if(r.code!==0)throw new cr(r.stderr);let n=gs(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.#pe(o,n.rows);let s=this.#i();if(n.progress!==void 0)this.#b={value:n.progress,at:s};return this.#X(o,n.progress,s),this.#Re(n.head),this.#ve(n.head),this.#Q(e,ms(o),o)}#he(e,t){this.#t.log.error(`hightea-source: row ${e} omitted: ${t}`)}#pe(e,t){for(let r of t){let n=this.#Je(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.#he(r.id,s.join("; "));continue}if(ne(n)>ot)throw new xn(n.address);e.set(n.address,{key:r.path,row:n})}}async#je(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:hs,changedSince:t,progress:!0},a=this.#i(),c=await this.#$e(i),d=this.#i();if(!c.ok){let b=Kf(c.stderr),E=/--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(!b&&!_w(c.stderr)&&!E)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`),b?this.#Ee():this.#be(r)}let u=gs(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.#be(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 b=this.#m??(this.#m=this.#i());if(this.#i()-b>=(this.#t.noticePatienceMs??nw))this.#t.log.error(`hightea-source: ${this.sourceId} stayed below the change notice at ${l} for ${Math.round(this.#i()-b)} 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.#Me()}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((b)=>this.#me(b))),y=new Map([...s.byAddress].map(([b,E])=>[E.key,b]));for(let b of f)p.delete(b);if(this.#pe(p,u.rows),this.#We(s,p,f,y,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.#Ee();for(let b of u.removed){let E=y.get(b);if(E!==void 0&&!f.has(E))p.delete(E)}if(c.from==="reader"){let b=await this.#He(o);if(b!==void 0)this.#X(p,b.value,b.at)}else{let b=this.#i();if(u.progress!==void 0)this.#b={value:u.progress,at:b};this.#X(p,u.progress,b)}this.#c=u.head,this.#W=!1;let g=this.#i(),m=ms(p),_=this.#i(),x=this.#Q(e,m,p),v=this.#i();if(n||v-a>=500){let b=o?"watch":n?"client":"change";this.#t.log.info?.(`hightea-source: ${this.sourceId} ${b} delta read ${Math.round(v-a)} ms: yrd ${Math.round(d-a)} ms, collect ${Math.round(g-d)} ms, revision ${Math.round(_-g)} ms, diff ${Math.round(v-_)} ms`)}return x}#be(e){this.#W=e;return}#Ee(){this.#W=!1;return}async#Fe(){let e=this.#G();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))>bn)throw Error("progress refresh output exceeded its byte budget");return r}async#He(e){let t=this.#b;if(!(t===void 0||this.#i()-t.at>=this.#se))return t;if(t===void 0||e){await this.#Ie();let n=this.#b;if(n===void 0)throw Error("progress refresh completed without a projection");return n}return this.#Ie().catch((n)=>this.#t.log.error(`hightea-source: ${this.sourceId} activity projection refresh failed: ${W(n)}`)),t}#Be(){let e=this.#B;if(e===void 0||this.#L===void 0)return;if(this.#E<cw&&this.#i()-e<uw)return;return{since:new Date(e).toISOString(),reason:this.#L}}#Ie(){if(this.#R!==void 0)return this.#O=!0,this.#R;let e=(async()=>{do{this.#O=!1;let t=this.#i();try{let r=await this.#Fe();if(this.#x.push(this.#i()-t),this.#x.length>dw)this.#x.shift();this.#ke(r),this.#b={value:r,at:this.#i()},this.#E=0,this.#B=void 0,this.#L=void 0}catch(r){throw this.#E++,this.#B??=this.#i(),this.#L=W(r),r}}while(this.#O&&!this.#d.signal.aborted)})().finally(()=>{this.#R=void 0});return this.#R=e,e}#ke(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}}#X(e,t,r){this.#qe(e,this.#ke(t)),this.#T=r}#qe(e,t){let r=0;for(let[n,o]of e){let s=o.row,i=s.extra,a=vn(o.key),c=a===null?`path:${o.key.endsWith(".md")?o.key.slice(0,-3):o.key}`:`bead:${a}`,d=this.#ee(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:Gf(p),extra:{...i,in_progress:l,in_progress_reason:u??null}},y=ne(f);if(y>ot){e.delete(n),this.#he(i.id,`the row is ${y} 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`)}#Re(e){if(typeof e==="number"){this.#c=e;return}if(this.#c=void 0,this.#K)return;this.#K=!0,this.#t.log.info?.(`hightea-source: ${this.sourceId} names no journal to continue from; every read stays whole`)}async#Ge(){if(this.#d.signal.aborted)return;await new Promise((e)=>{let t=()=>{clearTimeout(r),this.#d.signal.removeEventListener("abort",t),e()},r=setTimeout(t,this.#D);this.#d.signal.addEventListener("abort",t,{once:!0})})}#Q(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||!mw(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.#Ke(e,t,i,o)}#Ke(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>Q_||this.#i()-a.at>ew)this.#s.delete(i);let s=this.#q;if(this.#q=!1,this.#e.enqueue(r,s?{soon:!0}:void 0),r.length>0)this.#t.onRecords?.(r);return o}#me(e){return`issue:${this.sourceId}/${vn(e.path)??e.id}`}#Ve(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}/${vn(t)??e.container}`}#We(e,t,r,n,o,s){let i=new Set,a=new Set;for(let c of o){let d=this.#me(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,y=u===void 0&&l!==void 0&&l.row.columns.project===d;if(!p&&!f&&!y)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 g of ps(u.key))a.add(g);if(l!==void 0)for(let g of ps(l.key))a.add(g)}for(let c of s){for(let u of ps(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.#me(e),r=e.owner.trim(),n=e.status.trim()===""?"none":e.status.trim(),o=this.#Ve(e),s=Gf({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.#_e.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}}}#ee(e){if(e.startsWith("km:"))return e.slice(3);return this.#t.config.members[e]}#Ye(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 vn(n)===null?n:void 0}async#te(e,t){let{config:r}=this.#t;try{return await this.#ye([...r.yrd,...e,"--project-root",r.projectRoot],{timeoutMs:this.#t.childTimeoutMs??120000,signal:this.#d.signal,...t===void 0?{}:{env:t}})}catch(n){throw Error(`the yrd command ${r.yrd[0]??"(none)"} could not run: ${W(n)}`)}}async#Xe(){let e=this.#t.follow??Ew,t=this.#d.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: ${W(n)}`)}this.hint(),await new Promise((n)=>{let o=setTimeout(n,tw);t.addEventListener("abort",()=>{clearTimeout(o),n()},{once:!0})})}}}var lw=new Set(["self","ancestor","folder-note","beads-root"]);function ps(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 fw=/^(\d{4,})-.+\.md$/u,hw=/^\d{4}-\d{2}-\d{2}/u;function vn(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(hw.test(n))return null;let o=fw.exec(n),s=o===null?Number.NaN:Number.parseInt(o[1],10);return Number.isInteger(s)&&s>=0?s:null}function qf(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 Gf(e){return Wf("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 gs(e){if(Buffer.byteLength(e)>bn)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:y}=u,g=null,m=null;if(f!==void 0||y!==void 0){if(typeof f!=="string"||f.trim()===""||typeof y!=="string"||!lw.has(y))throw Error("list-page answered malformed container/containerSource");g=f,m=y}let _={id:u.id,title:u.title,status:u.status,owner:u.owner,container:g,containerSource:m,in_progress:l??null,in_progress_reason:p??null,updated_at:qf(u,"updated_at"),closed_at:qf(u,"closed_at")},x=n(d.path)?d.path:_.id;return{..._,path:x}}),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 pw(e,t){if(Buffer.byteLength(e)>bn)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=gs(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 ms(e){let t=Wf("sha256");for(let r of[...e.keys()].sort())t.update(`${r}\x00${e.get(r).row.version}
|
|
72
|
+
`);return t.digest("hex")}function mw(e,t){return JSON.stringify(e.columns)===JSON.stringify(t.columns)}function gw(e,t){return Buffer.from(JSON.stringify([e,t])).toString("base64url")}function yw(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 _w(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 Kf(e){return/\bpage-source-(?:moved|not-reconciled)\b/u.test(e)}function ww(e){return/\byrd-issues-(?:provider-not-json|verb-unsupported)\b/u.test(e)}function Sw(e){return/\blist-page-serve is not declared\b/u.test(e)||/\byrd-issues-verb-unsupported\b/u.test(e)}function vw(e){return e.map((t)=>JSON.stringify({verb:"list-page",result:t})).join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}var
|
|
75
|
-
`);function
|
|
76
|
-
`).map((r)=>r.trim()).find((r)=>r!=="")??"";return t.length>
|
|
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??
|
|
78
|
-
`,{mode:384}),
|
|
79
|
-
`,{mode:384}),
|
|
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};
|
|
74
|
+
`}var Vf=(e)=>Math.round(e/1048576);function W(e){if(e instanceof Error&&"code"in e&&typeof e.code==="string")return e.code;return e instanceof Error?e.message:String(e)}var xw=['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 Jf(e,t){return Y_("/bin/sh",["-c",xw,"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 Yf(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 _s=(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=Jf([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)},y=setTimeout(f,t);r.addEventListener("abort",f,{once:!0});let g=(_)=>(x)=>{if(l+=x.length,l>bn)return f();if(_==="out")d+=x;else u+=x};c.stdout.setEncoding("utf8").on("data",g("out")),c.stderr.setEncoding("utf8").on("data",g("err"));let m=!0;c.on("error",(_)=>{m=!1,clearTimeout(y),s(_)}),c.on("close",(_,x)=>{if(clearTimeout(y),p!==void 0)clearTimeout(p);if(Et(c,"SIGKILL"),r.removeEventListener("abort",f),!m)return;let v=Yf(i,_,u);if(v!==void 0)s(v);else o({pid:c.pid,code:x===null?_:null,stdout:d,stderr:u})})}),bw=(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}},Ew=(e,{signal:t,onLine:r})=>new Promise((n,o)=>{let[s,...i]=e;if(s===void 0){o(Error("no command"));return}let a=Jf([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}),X_({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 y=Yf(s,p,c);if(y!==void 0)o(y);else n({pid:a.pid,code:f===null?p:null,stdout:"",stderr:c})})});import{createHash as Iw}from"node:crypto";function Qf(e){return e.kind==="command"}var kw="all",Rw=60000,Xf=400,It=(e)=>e instanceof Error?e.message:String(e);function ws(e){let t=e.split(`
|
|
76
|
+
`).map((r)=>r.trim()).find((r)=>r!=="")??"";return t.length>Xf?`${t.slice(0,Xf)}…`:t}function Cw(e,t){if(typeof e.info==="function")e.info(t);else e.error(t)}class Ss{sourceId;#e;#o;#r;#s;#n;#l;#c=0;#f;#u;#h=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??_s,this.#r=e.now??Date.now,this.#n=r,this.#l=e.childTimeoutMs??Rw,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.#b()})}get epoch(){return this.#s.epoch}start(){this.#p()}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})}#p(){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.#p()},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.#l,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}${ws(t.stderr)===""?"":`: ${ws(t.stderr)}`}`);if(t.stderr.trim()!=="")Cw(this.#e.log,`hightea-source: ${this.sourceId} read warned: ${ws(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??Iw("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:kw,columns:d.columns,extra:d.extra??null});if(!p.success){let f=p.error.issues.slice(0,3).map((y)=>`${y.path.join(".")||"row"}: ${y.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.#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}#b(){let e=this.#h.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.#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.#m(this.#h)}async#R(){return this.#f??await this.#w()}#O(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}}}#T(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=ne(c);if(ne({...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.#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.#T(e.args,t,await this.#R())};case"read":return{...t,op:"read",outcome:"applied",body:{observation:this.#O(await this.#R(),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 eh(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)=>eh(n,t+1)).reduce((n,o)=>o.length<n.length?o:n)})}var Ow="x-hightea/source/request";function th(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(ne(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=ql.safeParse(u);if(!l.success){let p=eh(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!==Ow)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=Bl.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 rh="x-hh-records";var nh="records",Tw=(e)=>{if(!e.startsWith("x-hh-records://"))return;let t=e.slice(15);if(t===""||t.includes("/")||t.includes("?"))return;return decodeURIComponent(t)};function oh(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=Tw(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:ke,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!==ke)throw Error(`x-hh-records:// offers no operation ${a.id}; only ${ke}`);let p=Kl.safeParse(d??{});if(!p.success)throw Error(`${ke} 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 Aw,renameSync as sh,unlinkSync as $w,writeFileSync as ih}from"node:fs";import{join as vs}from"node:path";var Pw="pipe-connected.json",ah="pipe-refused.json";function ch(e=new URL("./plugin.json",import.meta.url)){let t;try{t=JSON.parse(Aw(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 uh(e,t,r=new Date){let n=vs(e,Pw),o=`${n}.${process.pid}.tmp`;ih(o,`${JSON.stringify({version:t,at:r.toISOString()},null,2)}
|
|
78
|
+
`,{mode:384}),sh(o,n)}function dh(e,t,r,n=new Date){let o=vs(e,ah),s=`${o}.${process.pid}.tmp`,i={...r===void 0?{}:{version:r},at:n.toISOString(),error:t};ih(s,`${JSON.stringify(i,null,2)}
|
|
79
|
+
`,{mode:384}),sh(s,o)}function lh(e){try{$w(vs(e,ah))}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 Nw(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 En(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 Nw(r,i,c);return c}}function fh(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:"thread_read",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:"room_post",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:fh(e)})}];function xs(e){return ur.find((t)=>t.name===e)}function hh(e){return xs(e)?.readOnly===!0?[rs]:[rs,df]}var ph="hightea";class Ke extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}function zw(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 gh(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 bs{#e;#o;#r=new Map;#s;constructor(e){this.#e=e,this.#o=e.house??En}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 j)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=xs(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==="thread_read"||s==="room_post"){let d=await this.#n(r.token),u=zw(d.threadRef),l=`${u.roomId}/${u.rootMessageId}`,p=`${n}|${l}`;if(s==="thread_read"){await this.#c().admit({deliveryId:d.deliveryId,threadRef:l,triggeringMessageIds:d.triggeringMessageIds??[d.deliveryId]},r.token);let m=this.#r.get(p),_=await this.#o(this.#e.mcpUrl,a,"thread_read",{roomId:u.roomId,messageId:u.rootMessageId,...m===void 0?{}:{after:m}}),x=Mw(_),v=x.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,x))}]}}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 y=String(i.text??"");a["idempotency-key"]=d.deliveryId;let g=await this.#o(this.#e.mcpUrl,a,"room_post",{text:y,roomId:u.roomId,deliveryId:d.deliveryId,replyId:d.deliveryId,sig:Tf(f,{workspaceId:this.#e.workspaceId,roomId:u.roomId,rootMessageId:u.rootMessageId,authorMemberId:d.member,clientId:d.deliveryId,body:y})});return{content:[{type:"text",text:mh(g)}]}}let c=await this.#o(this.#e.mcpUrl,a,s,i);return{content:[{type:"text",text:mh(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),"thread_read",{limit:1});return Dw(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),"thread_read",t)).result?.structuredContent,now:this.#e.now??Date.now});return this.#s}}function Mw(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","thread_read returned no valid root/replies paging result");return t}function mh(e){return(e.result?.content??[]).map((t)=>t.text).join(`
|
|
80
|
+
`)}function Dw(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 yh=/^[A-Za-z0-9_.:-]{1,200}$/u,Lw=/^[A-Z_]{1,64}$/u;function _h(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"&&yh.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"||!yh.test(d)||typeof u!=="string"||!Lw.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 wh(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 Uw}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 jw(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 Fw(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 Sh=4194304;function Hw(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:gh(o);if(n.method==="tools/call"){if(s===void 0)return jw(t);let d=n.params?.name;if(typeof d==="string"){let u=Fw(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 vh(e,t){let r=t.hostname??"127.0.0.1",n=Hw(e,t),o=t.log??{error:(a)=>console.error(a)},s=Uw((a,c)=>void Bw(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 Bw(e,t,r,n){try{let o=[],s=0;for await(let u of e){if(s+=u.length,s>Sh){n.error(`hightea-mcp: a request body over ${String(Sh)} 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 qw=(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},X="hightea-host",Gw="hightea-pipe",xh=`plugin:${X}`,Kw=[xh,`plugin:${Gw}`],Vw=ur.map((e)=>e.name);function Ww(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 Jw(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 Yw(e){let t=e.headers;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`${X}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);return t}function Xw(e,t,r){let n=t.houseId;if(typeof t.workspaceId!=="string"||t.workspaceId===""){if(typeof n!=="string"||n==="")throw Error("hightea-host: the plugin entry names no workspace (workspaceId)");t={...t,workspaceId:n}}let o=Yw(t),s=typeof t.pluginVersion==="string"&&t.pluginVersion!==""?{version:t.pluginVersion}:ch(),i="version"in s?s.version:void 0,a=(I)=>{if(e.configDir===void 0)return;try{dh(e.configDir,String(I),i)}catch(O){e.log.error(`${X}: could not record the refused start in ${e.configDir}: ${String(O)}`)}};if(!("version"in s))e.log.error(`${X}: hello will name no plugin version: ${s.error}`);let c=!1,d,u=!1,l,p,f=new Map,y,g=new Map,m,_=oh({sources:()=>[...f.values()].map((I)=>({source:I.sourceId,epoch:I.epoch})),log:e.log,assign:async(I,O)=>{if(m===void 0)throw Error("records:assign: no source is listening on this host yet");return m(I,O)}});_.bind(e.registerChannel(rh,_.channel)),e.registerGrants(nh,{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:[ke]});let x=async()=>{if(u=!0,l!==void 0)clearTimeout(l);l=void 0,p?.close(),await Promise.all([...g.values()].map((I)=>I.stop?.()))};e.registerClose(x),e.registerClose(()=>y?.stop());let v=e.configDir===void 0?Promise.resolve(void 0):Of(e.configDir).catch((I)=>{let O=I instanceof Error?I:Error(String(I));return e.log.error(`${X}: ${O.message}`),O}),b=new sr({configDir:e.configDir,workspaceId:t.workspaceId,ownAgents:new Set(t.agents.map(([I])=>I)),hostKey:v,readThread:async(I,O)=>{if(t.mcpUrl===void 0)throw new j("ROOM_ASKS_UNTRUSTED","this host has no house MCP endpoint to read the ask from");return(await En(t.mcpUrl,kt(I),"thread_read",O)).result?.structuredContent}}),E=r.askGate??b;if(e.registerSessionMeta===void 0)e.log.error(`${X}: 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",(I)=>d?.agentMemberOf(I));e.on("listening",()=>{if(u||l!==void 0||p!==void 0)return;l=setTimeout(()=>{l=void 0,C().catch((I)=>{e.log.error(`${X}: the host could not start its connections: ${String(I)}`),a(I)})},100)});async function C(){if(u)return;let I,O=o[gf]??o[yf]??"";f=new Map,g=new Map;for(let A of t.sources??[]){if(Qf(A)){g.set(A.sourceId,new Ss({config:A,workspaceId:t.workspaceId,hostId:O,log:e.log,push:(N)=>Ne.sourcePush(N),...r.sourceChildren===void 0?{}:{run:r.sourceChildren.run}}));continue}if(A.kind!==void 0&&A.kind!=="km")throw Error(`${X}: the plugin entry names a source kind it cannot construct (${JSON.stringify(A.kind)}) for ${A.sourceId}, so this start is refused rather than offering it as km`);let U=new ys({config:A,workspaceId:t.workspaceId,hostId:O,log:e.log,...r.sourceChildren,onRecords:(N)=>_.observe(A.sourceId,N.map(qw)),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(A.sourceId,U),g.set(A.sourceId,U)}m=async(A,U)=>{let N=[...f.values()].find((bh)=>A.address.startsWith(`issue:${bh.sourceId}/`));if(N===void 0)return{outcome:"refused",code:"INVALID_ADDRESS"};let Rt=U?.owner?.id??`client:${U?.client??"unknown"}`;return N.assign(A,{workspaceId:t.workspaceId,sourceId:N.sourceId,hostId:O},Rt)};let G=new Set(g.keys()),D=th({workspaceId:t.workspaceId,hostId:O,bindings:()=>G,log:e.log,handler:{handle:(A)=>{let U=g.get(A.sourceId);if(U===void 0)return e.log.error(`hightea-source: no handler for ${A.sourceId} although it is bound here`),Promise.resolve({workspaceId:A.workspaceId,sourceId:A.sourceId,hostId:A.hostId,op:A.op,outcome:"refused",code:"SOURCE_UNAVAILABLE"});return U.handle(A)}}}),Q;if(t.hostToolsPort!==void 0&&t.mcpUrl!==void 0)try{let A=new bs({mcpUrl:t.mcpUrl,workspaceId:t.workspaceId,configDir:e.configDir,ownAgents:new Set(t.agents.map(([N])=>N)),hostKey:v,gate:E}),U=vh(A,{port:t.hostToolsPort,resourceMetadataUrl:`http://127.0.0.1:${String(t.hostToolsPort)}/.well-known/oauth-protected-resource`,log:e.log,requiredScopes:hh});if(await U.ready,u){U.stop();return}y=U,Q={resource:U.url,name:ph}}catch(A){e.log.error(`${X}: 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(A)}`)}let Ne=Lf({dial:(A)=>{let U=new Ri(t.cloudUrl,{headers:o,handshakeTimeout:15000,followRedirects:!1});return U.on("unexpected-response",(N,Rt)=>{A(Rt.statusCode??0),Rt.resume(),U.terminate()}),U},receive:(A,U)=>{let N=_h(A);if(N!==null){(e.log.info??e.log.error).call(e.log,wh(N));return}if(D.receive(A,U))return;In.fromCloud(A)},log:e.log,opened:(A)=>{I??=In.start(X);let U=()=>{if(u)return;if(e.configDir!==void 0)try{lh(e.configDir)}catch(N){e.log.error(`${X}: 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{uh(e.configDir,i)}catch(N){e.log.error(`${X}: could not stamp this bundle's first connection in ${e.configDir}: ${String(N)}`)}};I.then(U,(N)=>{if(u)return;if(N instanceof vt&&f.size>0){e.log.error(`${X}: agent conversations unavailable; declared sources remain connected: ${String(N)}`),U();return}if(e.log.error(`${X}: could not start on the local ahpd: ${String(N)}`),a(N),A.close===void 0)e.log.error(`${X}: this connection cannot be closed by name`);else A.close(4001,Jw(N));x()})}});p=Ne;for(let A of g.values())A.start?.();let dr=Ww(e.connect()),In=new fs(r.peer===void 0?dr:r.peer(dr),Ne,{workspaceId:t.workspaceId,agents:new Map(t.agents),owner:xh,tools:t.mcpUrl===void 0?[]:Vw,...Q===void 0?{}:{hostTools:Q},startSession:(A,U)=>e.startSession(A,U),log:e.log,store:Df(e.records("hightea"),Kw,(A)=>e.sessionOwner(A),e.log,e.records("hightea/chats")),admitTurn:(A)=>E.admit(A),handshake:{...i===void 0?{}:{plugin:{name:X,version:i}},ahpd:t.ahpdVersion,capabilities:[of,sf,ln],sources:()=>[...g.keys()]}});d=In}}function b0(e,t){Xw(e,t,{})}export{Gw as LEGACY_NAME,fs as WakePipe,b0 as apply,Xw as applyWith,X as name,fh as pageScreenshotArgs,Df as recordsPipeStore,Ww as shareListener,Jw as startFailureReason};
|