@silverhand-ai/daemon 0.0.1-alpha.7 → 0.0.1-alpha.8

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.
Files changed (3) hide show
  1. package/dist/cli.js +50 -50
  2. package/dist/daemon.js +65 -64
  3. package/package.json +1 -1
package/dist/daemon.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire}from"node:module";const require=createRequire(import.meta.url);
3
- var P0=Object.create;var _l=Object.defineProperty;var E0=Object.getOwnPropertyDescriptor;var C0=Object.getOwnPropertyNames;var T0=Object.getPrototypeOf,A0=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Xi=(t,e)=>{for(var r in e)_l(t,r,{get:e[r],enumerable:!0})},I0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of C0(e))!A0.call(t,o)&&o!==r&&_l(t,o,{get:()=>e[o],enumerable:!(n=E0(e,o))||n.enumerable});return t};var Tt=(t,e,r)=>(r=t!=null?P0(T0(t)):{},I0(e||!t||!t.__esModule?_l(r,"default",{value:t,enumerable:!0}):r,t));var lr=k((BG,cy)=>{"use strict";var iy=["nodebuffer","arraybuffer","fragments"],ay=typeof Blob<"u";ay&&iy.push("blob");cy.exports={BINARY_TYPES:iy,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ay,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var bs=k((VG,rc)=>{"use strict";var{EMPTY_BUFFER:I$}=lr(),fd=Buffer[Symbol.species];function $$(t,e){if(t.length===0)return I$;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let o=0;o<t.length;o++){let i=t[o];r.set(i,n),n+=i.length}return n<e?new fd(r.buffer,r.byteOffset,n):r}function uy(t,e,r,n,o){for(let i=0;i<o;i++)r[n+i]=t[i]^e[i&3]}function ly(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function z$(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function hd(t){if(hd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new fd(t):ArrayBuffer.isView(t)?e=new fd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),hd.readOnly=!1),e}rc.exports={concat:$$,mask:uy,toArrayBuffer:z$,toBuffer:hd,unmask:ly};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");rc.exports.mask=function(e,r,n,o,i){i<48?uy(e,r,n,o,i):t.mask(e,r,n,o,i)},rc.exports.unmask=function(e,r){e.length<32?ly(e,r):t.unmask(e,r)}}catch{}});var my=k((KG,py)=>{"use strict";var dy=Symbol("kDone"),gd=Symbol("kRun"),_d=class{constructor(e){this[dy]=()=>{this.pending--,this[gd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gd]()}[gd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[dy])}}};py.exports=_d});var lo=k((GG,_y)=>{"use strict";var Ss=ue("zlib"),fy=bs(),O$=my(),{kStatusCode:hy}=lr(),D$=Buffer[Symbol.species],M$=Buffer.from([0,0,255,255]),oc=Symbol("permessage-deflate"),dr=Symbol("total-length"),co=Symbol("callback"),Ir=Symbol("buffers"),uo=Symbol("error"),nc,yd=class{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,!nc){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;nc=new O$(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[co];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),e}decompress(e,r,n){nc.add(o=>{this._decompress(e,r,(i,a)=>{o(),n(i,a)})})}compress(e,r,n){nc.add(o=>{this._compress(e,r,(i,a)=>{o(),n(i,a)})})}_decompress(e,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?Ss.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ss.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[oc]=this,this._inflate[dr]=0,this._inflate[Ir]=[],this._inflate.on("error",j$),this._inflate.on("data",gy)}this._inflate[co]=n,this._inflate.write(e),r&&this._inflate.write(M$),this._inflate.flush(()=>{let i=this._inflate[uo];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=fy.concat(this._inflate[Ir],this._inflate[dr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[dr]=0,this._inflate[Ir]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?Ss.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ss.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[dr]=0,this._deflate[Ir]=[],this._deflate.on("data",N$)}this._deflate[co]=n,this._deflate.write(e),this._deflate.flush(Ss.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=fy.concat(this._deflate[Ir],this._deflate[dr]);r&&(i=new D$(i.buffer,i.byteOffset,i.length-4)),this._deflate[co]=null,this._deflate[dr]=0,this._deflate[Ir]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};_y.exports=yd;function N$(t){this[Ir].push(t),this[dr]+=t.length}function gy(t){if(this[dr]+=t.length,this[oc]._maxPayload<1||this[dr]<=this[oc]._maxPayload){this[Ir].push(t);return}this[uo]=new RangeError("Max payload size exceeded"),this[uo].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[uo][hy]=1009,this.removeListener("data",gy),this.reset()}function j$(t){if(this[oc]._inflate=null,this[uo]){this[co](this[uo]);return}t[hy]=1007,this[co](t)}});var po=k((JG,sc)=>{"use strict";var{isUtf8:yy}=ue("buffer"),{hasBlob:L$}=lr(),F$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function H$(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function vd(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function U$(t){return L$&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}sc.exports={isBlob:U$,isValidStatusCode:H$,isValidUTF8:vd,tokenChars:F$};if(yy)sc.exports.isValidUTF8=function(t){return t.length<24?vd(t):yy(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");sc.exports.isValidUTF8=function(e){return e.length<32?vd(e):t(e)}}catch{}});var kd=k((YG,Ry)=>{"use strict";var{Writable:q$}=ue("stream"),vy=lo(),{BINARY_TYPES:W$,EMPTY_BUFFER:by,kStatusCode:Z$,kWebSocket:B$}=lr(),{concat:bd,toArrayBuffer:V$,unmask:K$}=bs(),{isValidStatusCode:G$,isValidUTF8:Sy}=po(),ic=Buffer[Symbol.species],yt=0,xy=1,wy=2,ky=3,Sd=4,xd=5,ac=6,wd=class extends q${constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||W$[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[B$]=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=yt}_write(e,r,n){if(this._opcode===8&&this._state==yt)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new ic(n.buffer,n.byteOffset+e,n.length-e),new ic(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new ic(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case yt:this.getInfo(e);break;case xy:this.getPayloadLength16(e);break;case wy:this.getPayloadLength64(e);break;case ky:this.getMask();break;case Sd:this.getData(e);break;case xd:case ac:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[vy.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=xy:this._payloadLength===127?this._state=wy: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 r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ky:this._state=Sd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Sd}getData(e){let r=by;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&K$(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=xd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[vy.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return r(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(i)}this.dataMessage(r),this._state===yt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=yt;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=bd(n,r):this._binaryType==="arraybuffer"?o=V$(bd(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=yt):(this._state=ac,setImmediate(()=>{this.emit("message",o,!0),this._state=yt,this.startLoop(e)}))}else{let o=bd(n,r);if(!this._skipUTF8Validation&&!Sy(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===xd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=yt):(this._state=ac,setImmediate(()=>{this.emit("message",o,!1),this._state=yt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,by),this.end();else{let n=e.readUInt16BE(0);if(!G$(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new ic(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Sy(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=yt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=yt):(this._state=ac,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=yt,this.startLoop(r)}))}createError(e,r,n,o,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=i,a[Z$]=o,a}};Ry.exports=wd});var Ed=k((QG,Cy)=>{"use strict";var{Duplex:XG}=ue("stream"),{randomFillSync:J$}=ue("crypto"),Py=lo(),{EMPTY_BUFFER:Y$,kWebSocket:X$,NOOP:Q$}=lr(),{isBlob:mo,isValidStatusCode:ez}=po(),{mask:Ey,toBuffer:hn}=bs(),vt=Symbol("kByteLength"),tz=Buffer.alloc(4),cc=8*1024,gn,fo=cc,$t=0,rz=1,nz=2,Rd=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=$t,this.onerror=Q$,this[X$]=void 0}static frame(e,r){let n,o=!1,i=2,a=!1;r.mask&&(n=r.maskBuffer||tz,r.generateMask?r.generateMask(n):(fo===cc&&(gn===void 0&&(gn=Buffer.alloc(cc)),J$(gn,0,cc),fo=0),n[0]=gn[fo++],n[1]=gn[fo++],n[2]=gn[fo++],n[3]=gn[fo++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!r.mask||a)&&r[vt]!==void 0?c=r[vt]:(e=Buffer.from(e),c=e.length):(c=e.length,o=r.mask&&r.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let l=Buffer.allocUnsafe(o?c+i:i);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=u,u===126?l.writeUInt16BE(c,2):u===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],a?[l,e]:o?(Ey(e,n,l,i,c),[l]):(Ey(e,n,e,0,c),[l,e])):[l,e]}close(e,r,n,o){let i;if(e===void 0)i=Y$;else{if(typeof e!="number"||!ez(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof r=="string"?i.write(r,2):i.set(r,2)}}let a={[vt]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==$t?this.enqueue([this.dispatch,i,!1,a,o]):this.sendFrame(t.frame(i,a),o)}ping(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):mo(e)?(o=e.size,i=!1):(e=hn(e),o=e.length,i=hn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[vt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mo(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==$t?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}pong(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):mo(e)?(o=e.size,i=!1):(e=hn(e),o=e.length,i=hn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[vt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mo(e)?this._state!==$t?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==$t?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}send(e,r,n){let o=this._extensions[Py.extensionName],i=r.binary?2:1,a=r.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):mo(e)?(c=e.size,u=!1):(e=hn(e),c=e.length,u=hn.readOnly),this._firstFragment?(this._firstFragment=!1,a&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=o._threshold),this._compress=a):(a=!1,i=0),r.fin&&(this._firstFragment=!0);let l={[vt]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};mo(e)?this._state!==$t?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==$t?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[vt],this._state=nz,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Pd,this,c,o);return}this._bufferedBytes-=n[vt];let a=hn(i);r?this.dispatch(a,r,n,o):(this._state=$t,this.sendFrame(t.frame(a,n),o),this.dequeue())}).catch(i=>{process.nextTick(oz,this,i,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let i=this._extensions[Py.extensionName];this._bufferedBytes+=n[vt],this._state=rz,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Pd(this,u,o);return}this._bufferedBytes-=n[vt],this._state=$t,n.readOnly=!1,this.sendFrame(t.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===$t&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][vt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][vt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Cy.exports=Rd;function Pd(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let o=t._queue[n],i=o[o.length-1];typeof i=="function"&&i(e)}}function oz(t,e,r){Pd(t,e,r),t.onerror(e)}});var Ny=k((e3,My)=>{"use strict";var{kForOnEventAttribute:xs,kListener:Cd}=lr(),Ty=Symbol("kCode"),Ay=Symbol("kData"),Iy=Symbol("kError"),$y=Symbol("kMessage"),zy=Symbol("kReason"),ho=Symbol("kTarget"),Oy=Symbol("kType"),Dy=Symbol("kWasClean"),pr=class{constructor(e){this[ho]=null,this[Oy]=e}get target(){return this[ho]}get type(){return this[Oy]}};Object.defineProperty(pr.prototype,"target",{enumerable:!0});Object.defineProperty(pr.prototype,"type",{enumerable:!0});var _n=class extends pr{constructor(e,r={}){super(e),this[Ty]=r.code===void 0?0:r.code,this[zy]=r.reason===void 0?"":r.reason,this[Dy]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ty]}get reason(){return this[zy]}get wasClean(){return this[Dy]}};Object.defineProperty(_n.prototype,"code",{enumerable:!0});Object.defineProperty(_n.prototype,"reason",{enumerable:!0});Object.defineProperty(_n.prototype,"wasClean",{enumerable:!0});var go=class extends pr{constructor(e,r={}){super(e),this[Iy]=r.error===void 0?null:r.error,this[$y]=r.message===void 0?"":r.message}get error(){return this[Iy]}get message(){return this[$y]}};Object.defineProperty(go.prototype,"error",{enumerable:!0});Object.defineProperty(go.prototype,"message",{enumerable:!0});var ws=class extends pr{constructor(e,r={}){super(e),this[Ay]=r.data===void 0?null:r.data}get data(){return this[Ay]}};Object.defineProperty(ws.prototype,"data",{enumerable:!0});var sz={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[xs]&&o[Cd]===e&&!o[xs])return;let n;if(t==="message")n=function(i,a){let c=new ws("message",{data:a?i:i.toString()});c[ho]=this,uc(e,this,c)};else if(t==="close")n=function(i,a){let c=new _n("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ho]=this,uc(e,this,c)};else if(t==="error")n=function(i){let a=new go("error",{error:i,message:i.message});a[ho]=this,uc(e,this,a)};else if(t==="open")n=function(){let i=new pr("open");i[ho]=this,uc(e,this,i)};else return;n[xs]=!!r[xs],n[Cd]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Cd]===e&&!r[xs]){this.removeListener(t,r);break}}};My.exports={CloseEvent:_n,ErrorEvent:go,Event:pr,EventTarget:sz,MessageEvent:ws};function uc(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var lc=k((t3,jy)=>{"use strict";var{tokenChars:ks}=po();function Yt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function iz(t){let e=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,a,c,u=-1,l=-1,d=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),a===void 0)if(d===-1&&ks[l]===1)u===-1&&(u=p);else if(p!==0&&(l===32||l===9))d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(u,d);l===44?(Yt(e,f,r),r=Object.create(null)):a=f,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(d===-1&&ks[l]===1)u===-1&&(u=p);else if(l===32||l===9)d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Yt(r,t.slice(u,d),!0),l===44&&(Yt(e,a,r),r=Object.create(null),a=void 0),u=d=-1}else if(l===61&&u!==-1&&d===-1)c=t.slice(u,p),u=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(ks[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:n||(n=!0),o=!1}else if(i)if(ks[l]===1)u===-1&&(u=p);else if(l===34&&u!==-1)i=!1,d=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)i=!0;else if(d===-1&&ks[l]===1)u===-1&&(u=p);else if(u!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(u,d);n&&(f=f.replace(/\\/g,""),n=!1),Yt(r,c,f),l===44&&(Yt(e,a,r),r=Object.create(null),a=void 0),c=void 0,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let m=t.slice(u,d);return a===void 0?Yt(e,m,r):(c===void 0?Yt(r,m,!0):n?Yt(r,c,m.replace(/\\/g,"")):Yt(r,c,m),Yt(e,a,r)),e}function az(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(o=>{let i=n[o];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?o:`${o}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}jy.exports={format:az,parse:iz}});var fc=k((o3,Jy)=>{"use strict";var cz=ue("events"),uz=ue("https"),lz=ue("http"),Hy=ue("net"),dz=ue("tls"),{randomBytes:pz,createHash:mz}=ue("crypto"),{Duplex:r3,Readable:n3}=ue("stream"),{URL:Td}=ue("url"),$r=lo(),fz=kd(),hz=Ed(),{isBlob:gz}=po(),{BINARY_TYPES:Ly,CLOSE_TIMEOUT:_z,EMPTY_BUFFER:dc,GUID:yz,kForOnEventAttribute:Ad,kListener:vz,kStatusCode:bz,kWebSocket:ze,NOOP:Uy}=lr(),{EventTarget:{addEventListener:Sz,removeEventListener:xz}}=Ny(),{format:wz,parse:kz}=lc(),{toBuffer:Rz}=bs(),qy=Symbol("kAborted"),Id=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],Pz=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Se=class t extends cz{constructor(e,r,n){super(),this._binaryType=Ly[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=dc,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Wy(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ly.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new fz({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new hz(e,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[ze]=this,i[ze]=this,e[ze]=this,o.on("conclude",Tz),o.on("drain",Az),o.on("error",Iz),o.on("message",$z),o.on("ping",zz),o.on("pong",Oz),i.onerror=Dz,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Vy),e.on("data",mc),e.on("end",Ky),e.on("error",Gy),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[$r.extensionName]&&this._extensions[$r.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),By(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||dc,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||dc,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){$d(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[$r.extensionName]||(o.compress=!1),this._sender.send(e||dc,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Se,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(Se.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(Se,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(Se.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(Se,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(Se.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(Se,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});Object.defineProperty(Se.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Se.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Se.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ad])return e[vz];return null},set(e){for(let r of this.listeners(t))if(r[Ad]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Ad]:!0})}})});Se.prototype.addEventListener=Sz;Se.prototype.removeEventListener=xz;Jy.exports=Se;function Wy(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_z,protocolVersion:Id[1],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(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Id.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Id.join(", ")})`);let i;if(e instanceof Td)i=e;else try{i=new Td(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let g=new SyntaxError(u);if(t._redirects===0)throw g;pc(t,g);return}let l=a?443:80,d=pz(16).toString("base64"),p=a?uz.request:lz.request,m=new Set,f;if(o.createConnection=o.createConnection||(a?Cz:Ez),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(f=new $r({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=wz({[$r.extensionName]:f.offer()})),r.length){for(let g of r){if(typeof g!="string"||!Pz.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),c){let g=o.path.split(":");o.socketPath=g[0],o.path=g[1]}let _;if(o.followRedirects){if(t._redirects===0){t._originalIpc=c,t._originalSecure=a,t._originalHostOrSocketPath=c?o.socketPath:i.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[y,S]of Object.entries(g))n.headers[y.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=c?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!a)&&(delete o.headers.authorization,delete o.headers.cookie,g||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),_=t._req=p(o),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=p(o);o.timeout&&_.on("timeout",()=>{ct(t,_,"Opening handshake has timed out")}),_.on("error",g=>{_===null||_[qy]||(_=t._req=null,pc(t,g))}),_.on("response",g=>{let y=g.headers.location,S=g.statusCode;if(y&&o.followRedirects&&S>=300&&S<400){if(++t._redirects>o.maxRedirects){ct(t,_,"Maximum redirects exceeded");return}_.abort();let x;try{x=new Td(y,e)}catch{let T=new SyntaxError(`Invalid URL: ${y}`);pc(t,T);return}Wy(t,x,r,n)}else t.emit("unexpected-response",_,g)||ct(t,_,`Unexpected server response: ${g.statusCode}`)}),_.on("upgrade",(g,y,S)=>{if(t.emit("upgrade",g),t.readyState!==Se.CONNECTING)return;_=t._req=null;let x=g.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ct(t,y,"Invalid Upgrade header");return}let w=mz("sha1").update(d+yz).digest("base64");if(g.headers["sec-websocket-accept"]!==w){ct(t,y,"Invalid Sec-WebSocket-Accept header");return}let T=g.headers["sec-websocket-protocol"],v;if(T!==void 0?m.size?m.has(T)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":m.size&&(v="Server sent no subprotocol"),v){ct(t,y,v);return}T&&(t._protocol=T);let P=g.headers["sec-websocket-extensions"];if(P!==void 0){if(!f){ct(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=kz(P)}catch{ct(t,y,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(O);if(J.length!==1||J[0]!==$r.extensionName){ct(t,y,"Server indicated an extension that was not requested");return}try{f.accept(O[$r.extensionName])}catch{ct(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[$r.extensionName]=f}t.setSocket(y,S,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(_,t):_.end()}function pc(t,e){t._readyState=Se.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ez(t){return t.path=t.socketPath,Hy.connect(t)}function Cz(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Hy.isIP(t.host)?"":t.host),dz.connect(t)}function ct(t,e,r){t._readyState=Se.CLOSING;let n=new Error(r);Error.captureStackTrace(n,ct),e.setHeader?(e[qy]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(pc,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function $d(t,e,r){if(e){let n=gz(e)?e.size:Rz(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${mr[t.readyState]})`);process.nextTick(r,n)}}function Tz(t,e){let r=this[ze];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[ze]!==void 0&&(r._socket.removeListener("data",mc),process.nextTick(Zy,r._socket),t===1005?r.close():r.close(t,e))}function Az(){let t=this[ze];t.isPaused||t._socket.resume()}function Iz(t){let e=this[ze];e._socket[ze]!==void 0&&(e._socket.removeListener("data",mc),process.nextTick(Zy,e._socket),e.close(t[bz])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Fy(){this[ze].emitClose()}function $z(t,e){this[ze].emit("message",t,e)}function zz(t){let e=this[ze];e._autoPong&&e.pong(t,!this._isServer,Uy),e.emit("ping",t)}function Oz(t){this[ze].emit("pong",t)}function Zy(t){t.resume()}function Dz(t){let e=this[ze];e.readyState!==Se.CLOSED&&(e.readyState===Se.OPEN&&(e._readyState=Se.CLOSING,By(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function By(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Vy(){let t=this[ze];if(this.removeListener("close",Vy),this.removeListener("data",mc),this.removeListener("end",Ky),t._readyState=Se.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ze]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Fy),t._receiver.on("finish",Fy))}function mc(t){this[ze]._receiver.write(t)||this.pause()}function Ky(){let t=this[ze];t._readyState=Se.CLOSING,t._receiver.end(),this.end()}function Gy(){let t=this[ze];this.removeListener("error",Gy),this.on("error",Uy),t&&(t._readyState=Se.CLOSING,this.destroy())}});var ev=k((i3,Qy)=>{"use strict";var s3=fc(),{Duplex:Mz}=ue("stream");function Yy(t){t.emit("close")}function Nz(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Xy(t){this.removeListener("error",Xy),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function jz(t,e){let r=!0,n=new Mz({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||t.pause()}),t.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(Yy,n);return}let a=!1;t.once("error",function(u){a=!0,i(u)}),t.once("close",function(){a||i(o),process.nextTick(Yy,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(o,i,a){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(o,i,a)});return}t.send(o,a)},n.on("end",Nz),n.on("error",Xy),n}Qy.exports=jz});var zd=k((a3,tv)=>{"use strict";var{tokenChars:Lz}=po();function Fz(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){let a=t.charCodeAt(o);if(n===-1&&Lz[a]===1)r===-1&&(r=o);else if(o!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=o);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=t.slice(r,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}tv.exports={parse:Fz}});var cv=k((u3,av)=>{"use strict";var Hz=ue("events"),hc=ue("http"),{Duplex:c3}=ue("stream"),{createHash:Uz}=ue("crypto"),rv=lc(),yn=lo(),qz=zd(),Wz=fc(),{CLOSE_TIMEOUT:Zz,GUID:Bz,kWebSocket:Vz}=lr(),Kz=/^[+/0-9A-Za-z]{22}==$/,nv=0,ov=1,iv=2,Od=class extends Hz{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Zz,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wz,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=hc.createServer((n,o)=>{let i=hc.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Gz(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,a)=>{this.handleUpgrade(o,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=nv}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===iv){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Rs,this);return}if(e&&this.once("close",e),this._state!==ov)if(this._state=ov,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Rs,this):process.nextTick(Rs,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Rs(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,o){r.on("error",sv);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vn(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){vn(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!Kz.test(i)){vn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){vn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ps(r,400);return}let u=e.headers["sec-websocket-protocol"],l=new Set;if(u!==void 0)try{l=qz.parse(u)}catch{vn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let m=new yn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=rv.parse(d);f[yn.extensionName]&&(m.accept(f[yn.extensionName]),p[yn.extensionName]=m)}catch{vn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,_,g,y)=>{if(!f)return Ps(r,_||401,g,y);this.completeUpgrade(p,i,l,e,r,n,o)});return}if(!this.options.verifyClient(m))return Ps(r,401)}this.completeUpgrade(p,i,l,e,r,n,o)}completeUpgrade(e,r,n,o,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[Vz])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>nv)return Ps(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Uz("sha1").update(r+Bz).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[yn.extensionName]){let p=e[yn.extensionName].params,m=rv.format({[yn.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
3
+ var M0=Object.create;var Sl=Object.defineProperty;var N0=Object.getOwnPropertyDescriptor;var j0=Object.getOwnPropertyNames;var L0=Object.getPrototypeOf,F0=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Qi=(t,e)=>{for(var r in e)Sl(t,r,{get:e[r],enumerable:!0})},H0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of j0(e))!F0.call(t,o)&&o!==r&&Sl(t,o,{get:()=>e[o],enumerable:!(n=N0(e,o))||n.enumerable});return t};var At=(t,e,r)=>(r=t!=null?M0(L0(t)):{},H0(e||!t||!t.__esModule?Sl(r,"default",{value:t,enumerable:!0}):r,t));var dr=k((P3,by)=>{"use strict";var yy=["nodebuffer","arraybuffer","fragments"],vy=typeof Blob<"u";vy&&yy.push("blob");by.exports={BINARY_TYPES:yy,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:vy,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ss=k((E3,ic)=>{"use strict";var{EMPTY_BUFFER:dz}=dr(),bd=Buffer[Symbol.species];function pz(t,e){if(t.length===0)return dz;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let o=0;o<t.length;o++){let i=t[o];r.set(i,n),n+=i.length}return n<e?new bd(r.buffer,r.byteOffset,n):r}function Sy(t,e,r,n,o){for(let i=0;i<o;i++)r[n+i]=t[i]^e[i&3]}function xy(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function mz(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sd(t){if(Sd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new bd(t):ArrayBuffer.isView(t)?e=new bd(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sd.readOnly=!1),e}ic.exports={concat:pz,mask:Sy,toArrayBuffer:mz,toBuffer:Sd,unmask:xy};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");ic.exports.mask=function(e,r,n,o,i){i<48?Sy(e,r,n,o,i):t.mask(e,r,n,o,i)},ic.exports.unmask=function(e,r){e.length<32?xy(e,r):t.unmask(e,r)}}catch{}});var Ry=k((C3,ky)=>{"use strict";var wy=Symbol("kDone"),xd=Symbol("kRun"),wd=class{constructor(e){this[wy]=()=>{this.pending--,this[xd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xd]()}[xd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wy])}}};ky.exports=wd});var po=k((T3,Ty)=>{"use strict";var xs=ue("zlib"),Py=Ss(),fz=Ry(),{kStatusCode:Ey}=dr(),hz=Buffer[Symbol.species],gz=Buffer.from([0,0,255,255]),cc=Symbol("permessage-deflate"),pr=Symbol("total-length"),uo=Symbol("callback"),$r=Symbol("buffers"),lo=Symbol("error"),ac,kd=class{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,!ac){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ac=new fz(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[uo];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),e}decompress(e,r,n){ac.add(o=>{this._decompress(e,r,(i,a)=>{o(),n(i,a)})})}compress(e,r,n){ac.add(o=>{this._compress(e,r,(i,a)=>{o(),n(i,a)})})}_decompress(e,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?xs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=xs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[cc]=this,this._inflate[pr]=0,this._inflate[$r]=[],this._inflate.on("error",yz),this._inflate.on("data",Cy)}this._inflate[uo]=n,this._inflate.write(e),r&&this._inflate.write(gz),this._inflate.flush(()=>{let i=this._inflate[lo];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=Py.concat(this._inflate[$r],this._inflate[pr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pr]=0,this._inflate[$r]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?xs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=xs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[pr]=0,this._deflate[$r]=[],this._deflate.on("data",_z)}this._deflate[uo]=n,this._deflate.write(e),this._deflate.flush(xs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Py.concat(this._deflate[$r],this._deflate[pr]);r&&(i=new hz(i.buffer,i.byteOffset,i.length-4)),this._deflate[uo]=null,this._deflate[pr]=0,this._deflate[$r]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Ty.exports=kd;function _z(t){this[$r].push(t),this[pr]+=t.length}function Cy(t){if(this[pr]+=t.length,this[cc]._maxPayload<1||this[pr]<=this[cc]._maxPayload){this[$r].push(t);return}this[lo]=new RangeError("Max payload size exceeded"),this[lo].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lo][Ey]=1009,this.removeListener("data",Cy),this.reset()}function yz(t){if(this[cc]._inflate=null,this[lo]){this[uo](this[lo]);return}t[Ey]=1007,this[uo](t)}});var mo=k((A3,uc)=>{"use strict";var{isUtf8:Ay}=ue("buffer"),{hasBlob:vz}=dr(),bz=[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 Sz(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Rd(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function xz(t){return vz&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}uc.exports={isBlob:xz,isValidStatusCode:Sz,isValidUTF8:Rd,tokenChars:bz};if(Ay)uc.exports.isValidUTF8=function(t){return t.length<24?Rd(t):Ay(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");uc.exports.isValidUTF8=function(e){return e.length<32?Rd(e):t(e)}}catch{}});var Ad=k((I3,Ny)=>{"use strict";var{Writable:wz}=ue("stream"),Iy=po(),{BINARY_TYPES:kz,EMPTY_BUFFER:$y,kStatusCode:Rz,kWebSocket:Pz}=dr(),{concat:Pd,toArrayBuffer:Ez,unmask:Cz}=Ss(),{isValidStatusCode:Tz,isValidUTF8:zy}=mo(),lc=Buffer[Symbol.species],vt=0,Oy=1,Dy=2,My=3,Ed=4,Cd=5,dc=6,Td=class extends wz{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kz[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Pz]=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=vt}_write(e,r,n){if(this._opcode===8&&this._state==vt)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new lc(n.buffer,n.byteOffset+e,n.length-e),new lc(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new lc(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case vt:this.getInfo(e);break;case Oy:this.getPayloadLength16(e);break;case Dy:this.getPayloadLength64(e);break;case My:this.getMask();break;case Ed:this.getData(e);break;case Cd:case dc:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Iy.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Oy:this._payloadLength===127?this._state=Dy: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 r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=My:this._state=Ed}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ed}getData(e){let r=$y;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Cz(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Cd,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Iy.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return r(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(i)}this.dataMessage(r),this._state===vt&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=vt;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Pd(n,r):this._binaryType==="arraybuffer"?o=Ez(Pd(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=vt):(this._state=dc,setImmediate(()=>{this.emit("message",o,!0),this._state=vt,this.startLoop(e)}))}else{let o=Pd(n,r);if(!this._skipUTF8Validation&&!zy(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Cd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=vt):(this._state=dc,setImmediate(()=>{this.emit("message",o,!1),this._state=vt,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,$y),this.end();else{let n=e.readUInt16BE(0);if(!Tz(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new lc(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zy(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=vt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=vt):(this._state=dc,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=vt,this.startLoop(r)}))}createError(e,r,n,o,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=i,a[Rz]=o,a}};Ny.exports=Td});var zd=k((z3,Fy)=>{"use strict";var{Duplex:$3}=ue("stream"),{randomFillSync:Az}=ue("crypto"),jy=po(),{EMPTY_BUFFER:Iz,kWebSocket:$z,NOOP:zz}=dr(),{isBlob:fo,isValidStatusCode:Oz}=mo(),{mask:Ly,toBuffer:gn}=Ss(),bt=Symbol("kByteLength"),Dz=Buffer.alloc(4),pc=8*1024,_n,ho=pc,zt=0,Mz=1,Nz=2,Id=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=zt,this.onerror=zz,this[$z]=void 0}static frame(e,r){let n,o=!1,i=2,a=!1;r.mask&&(n=r.maskBuffer||Dz,r.generateMask?r.generateMask(n):(ho===pc&&(_n===void 0&&(_n=Buffer.alloc(pc)),Az(_n,0,pc),ho=0),n[0]=_n[ho++],n[1]=_n[ho++],n[2]=_n[ho++],n[3]=_n[ho++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!r.mask||a)&&r[bt]!==void 0?c=r[bt]:(e=Buffer.from(e),c=e.length):(c=e.length,o=r.mask&&r.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let l=Buffer.allocUnsafe(o?c+i:i);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=u,u===126?l.writeUInt16BE(c,2):u===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],a?[l,e]:o?(Ly(e,n,l,i,c),[l]):(Ly(e,n,e,0,c),[l,e])):[l,e]}close(e,r,n,o){let i;if(e===void 0)i=Iz;else{if(typeof e!="number"||!Oz(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof r=="string"?i.write(r,2):i.set(r,2)}}let a={[bt]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==zt?this.enqueue([this.dispatch,i,!1,a,o]):this.sendFrame(t.frame(i,a),o)}ping(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):fo(e)?(o=e.size,i=!1):(e=gn(e),o=e.length,i=gn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[bt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};fo(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==zt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}pong(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):fo(e)?(o=e.size,i=!1):(e=gn(e),o=e.length,i=gn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[bt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};fo(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==zt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}send(e,r,n){let o=this._extensions[jy.extensionName],i=r.binary?2:1,a=r.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):fo(e)?(c=e.size,u=!1):(e=gn(e),c=e.length,u=gn.readOnly),this._firstFragment?(this._firstFragment=!1,a&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=o._threshold),this._compress=a):(a=!1,i=0),r.fin&&(this._firstFragment=!0);let l={[bt]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};fo(e)?this._state!==zt?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==zt?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[bt],this._state=Nz,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick($d,this,c,o);return}this._bufferedBytes-=n[bt];let a=gn(i);r?this.dispatch(a,r,n,o):(this._state=zt,this.sendFrame(t.frame(a,n),o),this.dequeue())}).catch(i=>{process.nextTick(jz,this,i,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let i=this._extensions[jy.extensionName];this._bufferedBytes+=n[bt],this._state=Mz,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");$d(this,u,o);return}this._bufferedBytes-=n[bt],this._state=zt,n.readOnly=!1,this.sendFrame(t.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===zt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][bt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Fy.exports=Id;function $d(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let o=t._queue[n],i=o[o.length-1];typeof i=="function"&&i(e)}}function jz(t,e,r){$d(t,e,r),t.onerror(e)}});var Gy=k((O3,Ky)=>{"use strict";var{kForOnEventAttribute:ws,kListener:Od}=dr(),Hy=Symbol("kCode"),Uy=Symbol("kData"),qy=Symbol("kError"),Wy=Symbol("kMessage"),Zy=Symbol("kReason"),go=Symbol("kTarget"),By=Symbol("kType"),Vy=Symbol("kWasClean"),mr=class{constructor(e){this[go]=null,this[By]=e}get target(){return this[go]}get type(){return this[By]}};Object.defineProperty(mr.prototype,"target",{enumerable:!0});Object.defineProperty(mr.prototype,"type",{enumerable:!0});var yn=class extends mr{constructor(e,r={}){super(e),this[Hy]=r.code===void 0?0:r.code,this[Zy]=r.reason===void 0?"":r.reason,this[Vy]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Hy]}get reason(){return this[Zy]}get wasClean(){return this[Vy]}};Object.defineProperty(yn.prototype,"code",{enumerable:!0});Object.defineProperty(yn.prototype,"reason",{enumerable:!0});Object.defineProperty(yn.prototype,"wasClean",{enumerable:!0});var _o=class extends mr{constructor(e,r={}){super(e),this[qy]=r.error===void 0?null:r.error,this[Wy]=r.message===void 0?"":r.message}get error(){return this[qy]}get message(){return this[Wy]}};Object.defineProperty(_o.prototype,"error",{enumerable:!0});Object.defineProperty(_o.prototype,"message",{enumerable:!0});var ks=class extends mr{constructor(e,r={}){super(e),this[Uy]=r.data===void 0?null:r.data}get data(){return this[Uy]}};Object.defineProperty(ks.prototype,"data",{enumerable:!0});var Lz={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[ws]&&o[Od]===e&&!o[ws])return;let n;if(t==="message")n=function(i,a){let c=new ks("message",{data:a?i:i.toString()});c[go]=this,mc(e,this,c)};else if(t==="close")n=function(i,a){let c=new yn("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[go]=this,mc(e,this,c)};else if(t==="error")n=function(i){let a=new _o("error",{error:i,message:i.message});a[go]=this,mc(e,this,a)};else if(t==="open")n=function(){let i=new mr("open");i[go]=this,mc(e,this,i)};else return;n[ws]=!!r[ws],n[Od]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Od]===e&&!r[ws]){this.removeListener(t,r);break}}};Ky.exports={CloseEvent:yn,ErrorEvent:_o,Event:mr,EventTarget:Lz,MessageEvent:ks};function mc(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var fc=k((D3,Jy)=>{"use strict";var{tokenChars:Rs}=mo();function Xt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Fz(t){let e=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,a,c,u=-1,l=-1,d=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),a===void 0)if(d===-1&&Rs[l]===1)u===-1&&(u=p);else if(p!==0&&(l===32||l===9))d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(u,d);l===44?(Xt(e,f,r),r=Object.create(null)):a=f,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(d===-1&&Rs[l]===1)u===-1&&(u=p);else if(l===32||l===9)d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Xt(r,t.slice(u,d),!0),l===44&&(Xt(e,a,r),r=Object.create(null),a=void 0),u=d=-1}else if(l===61&&u!==-1&&d===-1)c=t.slice(u,p),u=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Rs[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:n||(n=!0),o=!1}else if(i)if(Rs[l]===1)u===-1&&(u=p);else if(l===34&&u!==-1)i=!1,d=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Rs[l]===1)u===-1&&(u=p);else if(u!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(u,d);n&&(f=f.replace(/\\/g,""),n=!1),Xt(r,c,f),l===44&&(Xt(e,a,r),r=Object.create(null),a=void 0),c=void 0,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let m=t.slice(u,d);return a===void 0?Xt(e,m,r):(c===void 0?Xt(r,m,!0):n?Xt(r,c,m.replace(/\\/g,"")):Xt(r,c,m),Xt(e,a,r)),e}function Hz(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(o=>{let i=n[o];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?o:`${o}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Jy.exports={format:Hz,parse:Fz}});var yc=k((j3,cv)=>{"use strict";var Uz=ue("events"),qz=ue("https"),Wz=ue("http"),Qy=ue("net"),Zz=ue("tls"),{randomBytes:Bz,createHash:Vz}=ue("crypto"),{Duplex:M3,Readable:N3}=ue("stream"),{URL:Dd}=ue("url"),zr=po(),Kz=Ad(),Gz=zd(),{isBlob:Jz}=mo(),{BINARY_TYPES:Yy,CLOSE_TIMEOUT:Yz,EMPTY_BUFFER:hc,GUID:Xz,kForOnEventAttribute:Md,kListener:Qz,kStatusCode:eO,kWebSocket:ze,NOOP:ev}=dr(),{EventTarget:{addEventListener:tO,removeEventListener:rO}}=Gy(),{format:nO,parse:oO}=fc(),{toBuffer:sO}=Ss(),tv=Symbol("kAborted"),Nd=[8,13],fr=["CONNECTING","OPEN","CLOSING","CLOSED"],iO=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Se=class t extends Uz{constructor(e,r,n){super(),this._binaryType=Yy[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=hc,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),rv(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yy.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new Kz({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Gz(e,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[ze]=this,i[ze]=this,e[ze]=this,o.on("conclude",uO),o.on("drain",lO),o.on("error",dO),o.on("message",pO),o.on("ping",mO),o.on("pong",fO),i.onerror=hO,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",sv),e.on("data",_c),e.on("end",iv),e.on("error",av),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[zr.extensionName]&&this._extensions[zr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ov(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jd(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||hc,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jd(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||hc,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){jd(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[zr.extensionName]||(o.compress=!1),this._sender.send(e||hc,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ut(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Se,"CONNECTING",{enumerable:!0,value:fr.indexOf("CONNECTING")});Object.defineProperty(Se.prototype,"CONNECTING",{enumerable:!0,value:fr.indexOf("CONNECTING")});Object.defineProperty(Se,"OPEN",{enumerable:!0,value:fr.indexOf("OPEN")});Object.defineProperty(Se.prototype,"OPEN",{enumerable:!0,value:fr.indexOf("OPEN")});Object.defineProperty(Se,"CLOSING",{enumerable:!0,value:fr.indexOf("CLOSING")});Object.defineProperty(Se.prototype,"CLOSING",{enumerable:!0,value:fr.indexOf("CLOSING")});Object.defineProperty(Se,"CLOSED",{enumerable:!0,value:fr.indexOf("CLOSED")});Object.defineProperty(Se.prototype,"CLOSED",{enumerable:!0,value:fr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Se.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Se.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Md])return e[Qz];return null},set(e){for(let r of this.listeners(t))if(r[Md]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Md]:!0})}})});Se.prototype.addEventListener=tO;Se.prototype.removeEventListener=rO;cv.exports=Se;function rv(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Yz,protocolVersion:Nd[1],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(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Nd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Nd.join(", ")})`);let i;if(e instanceof Dd)i=e;else try{i=new Dd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let g=new SyntaxError(u);if(t._redirects===0)throw g;gc(t,g);return}let l=a?443:80,d=Bz(16).toString("base64"),p=a?qz.request:Wz.request,m=new Set,f;if(o.createConnection=o.createConnection||(a?cO:aO),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(f=new zr({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=nO({[zr.extensionName]:f.offer()})),r.length){for(let g of r){if(typeof g!="string"||!iO.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),c){let g=o.path.split(":");o.socketPath=g[0],o.path=g[1]}let _;if(o.followRedirects){if(t._redirects===0){t._originalIpc=c,t._originalSecure=a,t._originalHostOrSocketPath=c?o.socketPath:i.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[y,S]of Object.entries(g))n.headers[y.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=c?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!a)&&(delete o.headers.authorization,delete o.headers.cookie,g||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),_=t._req=p(o),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=p(o);o.timeout&&_.on("timeout",()=>{ut(t,_,"Opening handshake has timed out")}),_.on("error",g=>{_===null||_[tv]||(_=t._req=null,gc(t,g))}),_.on("response",g=>{let y=g.headers.location,S=g.statusCode;if(y&&o.followRedirects&&S>=300&&S<400){if(++t._redirects>o.maxRedirects){ut(t,_,"Maximum redirects exceeded");return}_.abort();let x;try{x=new Dd(y,e)}catch{let T=new SyntaxError(`Invalid URL: ${y}`);gc(t,T);return}rv(t,x,r,n)}else t.emit("unexpected-response",_,g)||ut(t,_,`Unexpected server response: ${g.statusCode}`)}),_.on("upgrade",(g,y,S)=>{if(t.emit("upgrade",g),t.readyState!==Se.CONNECTING)return;_=t._req=null;let x=g.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ut(t,y,"Invalid Upgrade header");return}let w=Vz("sha1").update(d+Xz).digest("base64");if(g.headers["sec-websocket-accept"]!==w){ut(t,y,"Invalid Sec-WebSocket-Accept header");return}let T=g.headers["sec-websocket-protocol"],v;if(T!==void 0?m.size?m.has(T)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":m.size&&(v="Server sent no subprotocol"),v){ut(t,y,v);return}T&&(t._protocol=T);let P=g.headers["sec-websocket-extensions"];if(P!==void 0){if(!f){ut(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=oO(P)}catch{ut(t,y,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(O);if(J.length!==1||J[0]!==zr.extensionName){ut(t,y,"Server indicated an extension that was not requested");return}try{f.accept(O[zr.extensionName])}catch{ut(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[zr.extensionName]=f}t.setSocket(y,S,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(_,t):_.end()}function gc(t,e){t._readyState=Se.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function aO(t){return t.path=t.socketPath,Qy.connect(t)}function cO(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Qy.isIP(t.host)?"":t.host),Zz.connect(t)}function ut(t,e,r){t._readyState=Se.CLOSING;let n=new Error(r);Error.captureStackTrace(n,ut),e.setHeader?(e[tv]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(gc,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function jd(t,e,r){if(e){let n=Jz(e)?e.size:sO(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${fr[t.readyState]})`);process.nextTick(r,n)}}function uO(t,e){let r=this[ze];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[ze]!==void 0&&(r._socket.removeListener("data",_c),process.nextTick(nv,r._socket),t===1005?r.close():r.close(t,e))}function lO(){let t=this[ze];t.isPaused||t._socket.resume()}function dO(t){let e=this[ze];e._socket[ze]!==void 0&&(e._socket.removeListener("data",_c),process.nextTick(nv,e._socket),e.close(t[eO])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Xy(){this[ze].emitClose()}function pO(t,e){this[ze].emit("message",t,e)}function mO(t){let e=this[ze];e._autoPong&&e.pong(t,!this._isServer,ev),e.emit("ping",t)}function fO(t){this[ze].emit("pong",t)}function nv(t){t.resume()}function hO(t){let e=this[ze];e.readyState!==Se.CLOSED&&(e.readyState===Se.OPEN&&(e._readyState=Se.CLOSING,ov(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ov(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sv(){let t=this[ze];if(this.removeListener("close",sv),this.removeListener("data",_c),this.removeListener("end",iv),t._readyState=Se.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ze]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Xy),t._receiver.on("finish",Xy))}function _c(t){this[ze]._receiver.write(t)||this.pause()}function iv(){let t=this[ze];t._readyState=Se.CLOSING,t._receiver.end(),this.end()}function av(){let t=this[ze];this.removeListener("error",av),this.on("error",ev),t&&(t._readyState=Se.CLOSING,this.destroy())}});var pv=k((F3,dv)=>{"use strict";var L3=yc(),{Duplex:gO}=ue("stream");function uv(t){t.emit("close")}function _O(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lv(t){this.removeListener("error",lv),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function yO(t,e){let r=!0,n=new gO({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||t.pause()}),t.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(uv,n);return}let a=!1;t.once("error",function(u){a=!0,i(u)}),t.once("close",function(){a||i(o),process.nextTick(uv,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(o,i,a){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(o,i,a)});return}t.send(o,a)},n.on("end",_O),n.on("error",lv),n}dv.exports=yO});var Ld=k((H3,mv)=>{"use strict";var{tokenChars:vO}=mo();function bO(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){let a=t.charCodeAt(o);if(n===-1&&vO[a]===1)r===-1&&(r=o);else if(o!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=o);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=t.slice(r,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}mv.exports={parse:bO}});var bv=k((q3,vv)=>{"use strict";var SO=ue("events"),vc=ue("http"),{Duplex:U3}=ue("stream"),{createHash:xO}=ue("crypto"),fv=fc(),vn=po(),wO=Ld(),kO=yc(),{CLOSE_TIMEOUT:RO,GUID:PO,kWebSocket:EO}=dr(),CO=/^[+/0-9A-Za-z]{22}==$/,hv=0,gv=1,yv=2,Fd=class extends SO{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:RO,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kO,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=vc.createServer((n,o)=>{let i=vc.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=TO(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,a)=>{this.handleUpgrade(o,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=hv}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yv){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ps,this);return}if(e&&this.once("close",e),this._state!==gv)if(this._state=gv,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ps,this):process.nextTick(Ps,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Ps(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,o){r.on("error",_v);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){bn(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){bn(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!CO.test(i)){bn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){bn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Es(r,400);return}let u=e.headers["sec-websocket-protocol"],l=new Set;if(u!==void 0)try{l=wO.parse(u)}catch{bn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let m=new vn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=fv.parse(d);f[vn.extensionName]&&(m.accept(f[vn.extensionName]),p[vn.extensionName]=m)}catch{bn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,_,g,y)=>{if(!f)return Es(r,_||401,g,y);this.completeUpgrade(p,i,l,e,r,n,o)});return}if(!this.options.verifyClient(m))return Es(r,401)}this.completeUpgrade(p,i,l,e,r,n,o)}completeUpgrade(e,r,n,o,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[EO])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>hv)return Es(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${xO("sha1").update(r+PO).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[vn.extensionName]){let p=e[vn.extensionName].params,m=fv.format({[vn.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
4
4
  `).join(`\r
5
- `)),i.removeListener("error",sv),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Rs,this)})),c(d,o)}};av.exports=Od;function Gz(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Rs(t){t._state=iv,t.emit("close")}function sv(){this.destroy()}function Ps(t,e,r,n){r=r||hc.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${hc.STATUS_CODES[e]}\r
5
+ `)),i.removeListener("error",_v),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ps,this)})),c(d,o)}};vv.exports=Fd;function TO(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Ps(t){t._state=yv,t.emit("close")}function _v(){this.destroy()}function Es(t,e,r,n){r=r||vc.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${vc.STATUS_CODES[e]}\r
6
6
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
7
7
  `)+`\r
8
8
  \r
9
- `+r)}function vn(t,e,r,n,o,i){if(t.listenerCount("wsClientError")){let a=new Error(o);Error.captureStackTrace(a,vn),t.emit("wsClientError",a,r,e)}else Ps(r,n,o,i)}});var ni=k(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var ti=class{};oe._CodeOrName=ti;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Tn=class extends ti{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=Tn;var kt=class extends ti{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Tn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=kt;oe.nil=new kt("");function Aw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Tm(r,e[n]),r.push(t[++n]);return new kt(r)}oe._=Aw;var Cm=new kt("+");function Iw(t,...e){let r=[ri(t[0])],n=0;for(;n<e.length;)r.push(Cm),Tm(r,e[n]),r.push(Cm,ri(t[++n]));return dj(r),new kt(r)}oe.str=Iw;function Tm(t,e){e instanceof kt?t.push(...e._items):e instanceof Tn?t.push(e):t.push(fj(e))}oe.addCodeArg=Tm;function dj(t){let e=1;for(;e<t.length-1;){if(t[e]===Cm){let r=pj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function pj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Tn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Tn))return`"${t}${e.slice(1)}`}function mj(t,e){return e.emptyStr()?t:t.emptyStr()?e:Iw`${t}${e}`}oe.strConcat=mj;function fj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ri(Array.isArray(t)?t.join(","):t)}function hj(t){return new kt(ri(t))}oe.stringify=hj;function ri(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=ri;function gj(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new kt(`.${t}`):Aw`[${t}]`}oe.getProperty=gj;function _j(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=_j;function yj(t){return new kt(t.toString())}oe.regexpCode=yj});var $m=k(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.ValueScope=nt.ValueScopeName=nt.Scope=nt.varKinds=nt.UsedValueState=void 0;var rt=ni(),Am=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},uu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(uu||(nt.UsedValueState=uu={}));nt.varKinds={const:new rt.Name("const"),let:new rt.Name("let"),var:new rt.Name("var")};var lu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof rt.Name?e:this.name(e)}name(e){return new rt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};nt.Scope=lu;var du=class extends rt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,rt._)`.${new rt.Name(r)}[${n}]`}};nt.ValueScopeName=du;var vj=(0,rt._)`\n`,Im=class extends lu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vj:rt.nil}}get(){return this._scope}name(e){return new du(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,a=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let d=c.get(a);if(d)return d}else c=this._values[i]=new Map;c.set(a,o);let u=this._scope[i]||(this._scope[i]=[]),l=u.length;return u[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,rt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let i=rt.nil;for(let a in e){let c=e[a];if(!c)continue;let u=n[a]=n[a]||new Map;c.forEach(l=>{if(u.has(l))return;u.set(l,uu.Started);let d=r(l);if(d){let p=this.opts.es5?nt.varKinds.var:nt.varKinds.const;i=(0,rt._)`${i}${p} ${l} = ${d};${this.opts._n}`}else if(d=o?.(l))i=(0,rt._)`${i}${d}${this.opts._n}`;else throw new Am(l);u.set(l,uu.Completed)})}return i}};nt.ValueScope=Im});var V=k(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var Q=ni(),jt=$m(),jr=ni();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return jr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return jr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return jr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return jr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return jr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return jr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return jr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return jr.Name}});var hu=$m();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return hu.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return hu.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return hu.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return hu.varKinds}});K.operators={GT:new Q._Code(">"),GTE:new Q._Code(">="),LT:new Q._Code("<"),LTE:new Q._Code("<="),EQ:new Q._Code("==="),NEQ:new Q._Code("!=="),NOT:new Q._Code("!"),OR:new Q._Code("||"),AND:new Q._Code("&&"),ADD:new Q._Code("+")};var _r=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},zm=class extends _r{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?jt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=jo(this.rhs,e,r)),this}get names(){return this.rhs instanceof Q._CodeOrName?this.rhs.names:{}}},pu=class extends _r{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Q.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=jo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Q.Name?{}:{...this.lhs.names};return fu(e,this.rhs)}},Om=class extends pu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Dm=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mm=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Nm=class extends _r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},jm=class extends _r{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=jo(this.code,e,r),this}get names(){return this.code instanceof Q._CodeOrName?this.code.names:{}}},oi=class extends _r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(e,r)||(bj(e,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>$n(e,r.names),{})}},yr=class extends oi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Lm=class extends oi{},No=class extends yr{};No.kind="else";var An=class t extends yr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new No(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t($w(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=jo(this.condition,e,r),this}get names(){let e=super.names;return fu(e,this.condition),this.else&&$n(e,this.else.names),e}};An.kind="if";var In=class extends yr{};In.kind="for";var Fm=class extends In{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=jo(this.iteration,e,r),this}get names(){return $n(super.names,this.iteration.names)}},Hm=class extends In{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?jt.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=fu(super.names,this.from);return fu(e,this.to)}},mu=class extends In{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=jo(this.iterable,e,r),this}get names(){return $n(super.names,this.iterable.names)}},si=class extends yr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};si.kind="func";var ii=class extends oi{render(e){return"return "+super.render(e)}};ii.kind="return";var Um=class extends yr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&$n(e,this.catch.names),this.finally&&$n(e,this.finally.names),e}},ai=class extends yr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ai.kind="catch";var ci=class extends yr{render(e){return"finally"+super.render(e)}};ci.kind="finally";var qm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
10
- `:""},this._extScope=e,this._scope=new jt.Scope({parent:e}),this._nodes=[new Lm]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new zm(e,i,n)),i}const(e,r,n){return this._def(jt.varKinds.const,e,r,n)}let(e,r,n){return this._def(jt.varKinds.let,e,r,n)}var(e,r,n){return this._def(jt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new pu(e,r,n))}add(e,r){return this._leafNode(new Om(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Q.nil&&this._leafNode(new jm(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Q.addCodeArg)(r,o));return r.push("}"),new Q._Code(r)}if(e,r,n){if(this._blockNode(new An(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new An(e))}else(){return this._elseNode(new No)}endIf(){return this._endBlockNode(An,No)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fm(e),r)}forRange(e,r,n,o,i=this.opts.es5?jt.varKinds.var:jt.varKinds.let){let a=this._scope.toName(e);return this._for(new Hm(i,a,r,n),()=>o(a))}forOf(e,r,n,o=jt.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let a=r instanceof Q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Q._)`${a}.length`,c=>{this.var(i,(0,Q._)`${a}[${c}]`),n(i)})}return this._for(new mu("of",o,i,r),()=>n(i))}forIn(e,r,n,o=this.opts.es5?jt.varKinds.var:jt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Q._)`Object.keys(${r})`,n);let i=this._scope.toName(e);return this._for(new mu("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(In)}label(e){return this._leafNode(new Dm(e))}break(e){return this._leafNode(new Mm(e))}return(e){let r=new ii;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ii)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Um;if(this._blockNode(o),this.code(e),r){let i=this.name("e");this._currNode=o.catch=new ai(i),r(i)}return n&&(this._currNode=o.finally=new ci,this.code(n)),this._endBlockNode(ai,ci)}throw(e){return this._leafNode(new Nm(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Q.nil,n,o){return this._blockNode(new si(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(si)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof An))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=qm;function $n(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function fu(t,e){return e instanceof Q._CodeOrName?$n(t,e.names):t}function jo(t,e,r){if(t instanceof Q.Name)return n(t);if(!o(t))return t;return new Q._Code(t._items.reduce((i,a)=>(a instanceof Q.Name&&(a=n(a)),a instanceof Q._Code?i.push(...a._items):i.push(a),i),[]));function n(i){let a=r[i.str];return a===void 0||e[i.str]!==1?i:(delete e[i.str],a)}function o(i){return i instanceof Q._Code&&i._items.some(a=>a instanceof Q.Name&&e[a.str]===1&&r[a.str]!==void 0)}}function bj(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function $w(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Q._)`!${Wm(t)}`}K.not=$w;var Sj=zw(K.operators.AND);function xj(...t){return t.reduce(Sj)}K.and=xj;var wj=zw(K.operators.OR);function kj(...t){return t.reduce(wj)}K.or=kj;function zw(t){return(e,r)=>e===Q.nil?r:r===Q.nil?e:(0,Q._)`${Wm(e)} ${t} ${Wm(r)}`}function Wm(t){return t instanceof Q.Name?t:(0,Q._)`(${t})`}});var te=k(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var pe=V(),Rj=ni();function Pj(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=Pj;function Ej(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Mw(t,e),!Nw(e,t.self.RULES.all))}G.alwaysValidSchema=Ej;function Mw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let i in e)o[i]||Fw(t,`unknown keyword: "${i}"`)}G.checkUnknownRules=Mw;function Nw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Nw;function Cj(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=Cj;function Tj({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,pe._)`${r}`}return(0,pe._)`${t}${e}${(0,pe.getProperty)(n)}`}G.schemaRefOrVal=Tj;function Aj(t){return jw(decodeURIComponent(t))}G.unescapeFragment=Aj;function Ij(t){return encodeURIComponent(Bm(t))}G.escapeFragment=Ij;function Bm(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=Bm;function jw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=jw;function $j(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=$j;function Ow({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,i,a,c)=>{let u=a===void 0?i:a instanceof pe.Name?(i instanceof pe.Name?t(o,i,a):e(o,i,a),a):i instanceof pe.Name?(e(o,a,i),i):r(i,a);return c===pe.Name&&!(u instanceof pe.Name)?n(o,u):u}}G.mergeEvaluated={props:Ow({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,pe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,pe._)`${r} || {}`).code((0,pe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,pe._)`${r} || {}`),Vm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Lw}),items:Ow({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,pe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,pe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Lw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,pe._)`{}`);return e!==void 0&&Vm(t,r,e),r}G.evaluatedPropsToName=Lw;function Vm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}G.setEvaluated=Vm;var Dw={};function zj(t,e){return t.scopeValue("func",{ref:e,code:Dw[e.code]||(Dw[e.code]=new Rj._Code(e.code))})}G.useFunc=zj;var Zm;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Zm||(G.Type=Zm={}));function Oj(t,e,r){if(t instanceof pe.Name){let n=e===Zm.Num;return r?n?(0,pe._)`"[" + ${t} + "]"`:(0,pe._)`"['" + ${t} + "']"`:n?(0,pe._)`"/" + ${t}`:(0,pe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,pe.getProperty)(t).toString():"/"+Bm(t)}G.getErrorPath=Oj;function Fw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=Fw});var vr=k(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});var We=V(),Dj={data:new We.Name("data"),valCxt:new We.Name("valCxt"),instancePath:new We.Name("instancePath"),parentData:new We.Name("parentData"),parentDataProperty:new We.Name("parentDataProperty"),rootData:new We.Name("rootData"),dynamicAnchors:new We.Name("dynamicAnchors"),vErrors:new We.Name("vErrors"),errors:new We.Name("errors"),this:new We.Name("this"),self:new We.Name("self"),scope:new We.Name("scope"),json:new We.Name("json"),jsonPos:new We.Name("jsonPos"),jsonLen:new We.Name("jsonLen"),jsonPart:new We.Name("jsonPart")};Km.default=Dj});var ui=k(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.extendErrors=Ze.resetErrorsCount=Ze.reportExtraError=Ze.reportError=Ze.keyword$DataError=Ze.keywordError=void 0;var re=V(),gu=te(),Je=vr();Ze.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function Mj(t,e=Ze.keywordError,r,n){let{it:o}=t,{gen:i,compositeRule:a,allErrors:c}=o,u=qw(t,e,r);n??(a||c)?Hw(i,u):Uw(o,(0,re._)`[${u}]`)}Ze.reportError=Mj;function Nj(t,e=Ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:i,allErrors:a}=n,c=qw(t,e,r);Hw(o,c),i||a||Uw(n,Je.default.vErrors)}Ze.reportExtraError=Nj;function jj(t,e){t.assign(Je.default.errors,e),t.if((0,re._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Ze.resetErrorsCount=jj;function Lj({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let a=t.name("err");t.forRange("i",o,Je.default.errors,c=>{t.const(a,(0,re._)`${Je.default.vErrors}[${c}]`),t.if((0,re._)`${a}.instancePath === undefined`,()=>t.assign((0,re._)`${a}.instancePath`,(0,re.strConcat)(Je.default.instancePath,i.errorPath))),t.assign((0,re._)`${a}.schemaPath`,(0,re.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,re._)`${a}.schema`,r),t.assign((0,re._)`${a}.data`,n))})}Ze.extendErrors=Lj;function Hw(t,e){let r=t.const("err",e);t.if((0,re._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Je.default.vErrors}.push(${r})`),t.code((0,re._)`${Je.default.errors}++`)}function Uw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var zn={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function qw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:Fj(t,e,r)}function Fj(t,e,r={}){let{gen:n,it:o}=t,i=[Hj(o,r),Uj(t,r)];return qj(t,e,i),n.object(...i)}function Hj({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,gu.getErrorPath)(e,gu.Type.Str)}`:t;return[Je.default.instancePath,(0,re.strConcat)(Je.default.instancePath,r)]}function Uj({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,gu.getErrorPath)(r,gu.Type.Str)}`),[zn.schemaPath,o]}function qj(t,{params:e,message:r},n){let{keyword:o,data:i,schemaValue:a,it:c}=t,{opts:u,propertyName:l,topSchemaRef:d,schemaPath:p}=c;n.push([zn.keyword,o],[zn.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),u.messages&&n.push([zn.message,typeof r=="function"?r(t):r]),u.verbose&&n.push([zn.schema,a],[zn.parentSchema,(0,re._)`${d}${p}`],[Je.default.data,i]),l&&n.push([zn.propertyName,l])}});var Zw=k(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.boolOrEmptySchema=Lo.topBoolOrEmptySchema=void 0;var Wj=ui(),Zj=V(),Bj=vr(),Vj={message:"boolean schema is false"};function Kj(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ww(t,!1):typeof r=="object"&&r.$async===!0?e.return(Bj.default.data):(e.assign((0,Zj._)`${n}.errors`,null),e.return(!0))}Lo.topBoolOrEmptySchema=Kj;function Gj(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ww(t)):r.var(e,!0)}Lo.boolOrEmptySchema=Gj;function Ww(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Wj.reportError)(o,Vj,void 0,e)}});var Gm=k(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.getRules=Fo.isJSONType=void 0;var Jj=["string","number","integer","boolean","null","object","array"],Yj=new Set(Jj);function Xj(t){return typeof t=="string"&&Yj.has(t)}Fo.isJSONType=Xj;function Qj(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Fo.getRules=Qj});var Jm=k(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.shouldUseRule=Lr.shouldUseGroup=Lr.schemaHasRulesForType=void 0;function eL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Bw(t,n)}Lr.schemaHasRulesForType=eL;function Bw(t,e){return e.rules.some(r=>Vw(t,r))}Lr.shouldUseGroup=Bw;function Vw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Lr.shouldUseRule=Vw});var li=k(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var tL=Gm(),rL=Jm(),nL=ui(),Z=V(),Kw=te(),Ho;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ho||(Be.DataType=Ho={}));function oL(t){let e=Gw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Be.getSchemaTypes=oL;function Gw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(tL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Gw;function sL(t,e){let{gen:r,data:n,opts:o}=t,i=iL(e,o.coerceTypes),a=e.length>0&&!(i.length===0&&e.length===1&&(0,rL.schemaHasRulesForType)(t,e[0]));if(a){let c=Xm(e,n,o.strictNumbers,Ho.Wrong);r.if(c,()=>{i.length?aL(t,e,i):Qm(t)})}return a}Be.coerceAndCheckDataType=sL;var Jw=new Set(["string","number","integer","boolean","null"]);function iL(t,e){return e?t.filter(r=>Jw.has(r)||e==="array"&&r==="array"):[]}function aL(t,e,r){let{gen:n,data:o,opts:i}=t,a=n.let("dataType",(0,Z._)`typeof ${o}`),c=n.let("coerced",(0,Z._)`undefined`);i.coerceTypes==="array"&&n.if((0,Z._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Z._)`${o}[0]`).assign(a,(0,Z._)`typeof ${o}`).if(Xm(e,o,i.strictNumbers),()=>n.assign(c,o))),n.if((0,Z._)`${c} !== undefined`);for(let l of r)(Jw.has(l)||l==="array"&&i.coerceTypes==="array")&&u(l);n.else(),Qm(t),n.endIf(),n.if((0,Z._)`${c} !== undefined`,()=>{n.assign(o,c),cL(t,c)});function u(l){switch(l){case"string":n.elseIf((0,Z._)`${a} == "number" || ${a} == "boolean"`).assign(c,(0,Z._)`"" + ${o}`).elseIf((0,Z._)`${o} === null`).assign(c,(0,Z._)`""`);return;case"number":n.elseIf((0,Z._)`${a} == "boolean" || ${o} === null
9
+ `+r)}function bn(t,e,r,n,o,i){if(t.listenerCount("wsClientError")){let a=new Error(o);Error.captureStackTrace(a,bn),t.emit("wsClientError",a,r,e)}else Es(r,n,o,i)}});var oi=k(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var ri=class{};oe._CodeOrName=ri;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var An=class extends ri{constructor(e){if(super(),!oe.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};oe.Name=An;var Rt=class extends ri{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof An&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=Rt;oe.nil=new Rt("");function Uw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Dm(r,e[n]),r.push(t[++n]);return new Rt(r)}oe._=Uw;var Om=new Rt("+");function qw(t,...e){let r=[ni(t[0])],n=0;for(;n<e.length;)r.push(Om),Dm(r,e[n]),r.push(Om,ni(t[++n]));return Zj(r),new Rt(r)}oe.str=qw;function Dm(t,e){e instanceof Rt?t.push(...e._items):e instanceof An?t.push(e):t.push(Kj(e))}oe.addCodeArg=Dm;function Zj(t){let e=1;for(;e<t.length-1;){if(t[e]===Om){let r=Bj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Bj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof An||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof An))return`"${t}${e.slice(1)}`}function Vj(t,e){return e.emptyStr()?t:t.emptyStr()?e:qw`${t}${e}`}oe.strConcat=Vj;function Kj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ni(Array.isArray(t)?t.join(","):t)}function Gj(t){return new Rt(ni(t))}oe.stringify=Gj;function ni(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=ni;function Jj(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new Rt(`.${t}`):Uw`[${t}]`}oe.getProperty=Jj;function Yj(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new Rt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=Yj;function Xj(t){return new Rt(t.toString())}oe.regexpCode=Xj});var jm=k(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ValueScope=ot.ValueScopeName=ot.Scope=ot.varKinds=ot.UsedValueState=void 0;var nt=oi(),Mm=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},mu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(mu||(ot.UsedValueState=mu={}));ot.varKinds={const:new nt.Name("const"),let:new nt.Name("let"),var:new nt.Name("var")};var fu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof nt.Name?e:this.name(e)}name(e){return new nt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ot.Scope=fu;var hu=class extends nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,nt._)`.${new nt.Name(r)}[${n}]`}};ot.ValueScopeName=hu;var Qj=(0,nt._)`\n`,Nm=class extends fu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Qj:nt.nil}}get(){return this._scope}name(e){return new hu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,a=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let d=c.get(a);if(d)return d}else c=this._values[i]=new Map;c.set(a,o);let u=this._scope[i]||(this._scope[i]=[]),l=u.length;return u[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,nt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let i=nt.nil;for(let a in e){let c=e[a];if(!c)continue;let u=n[a]=n[a]||new Map;c.forEach(l=>{if(u.has(l))return;u.set(l,mu.Started);let d=r(l);if(d){let p=this.opts.es5?ot.varKinds.var:ot.varKinds.const;i=(0,nt._)`${i}${p} ${l} = ${d};${this.opts._n}`}else if(d=o?.(l))i=(0,nt._)`${i}${d}${this.opts._n}`;else throw new Mm(l);u.set(l,mu.Completed)})}return i}};ot.ValueScope=Nm});var V=k(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var Q=oi(),Lt=jm(),Lr=oi();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return Lr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return Lr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return Lr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return Lr.Name}});var vu=jm();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return vu.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return vu.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return vu.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return vu.varKinds}});K.operators={GT:new Q._Code(">"),GTE:new Q._Code(">="),LT:new Q._Code("<"),LTE:new Q._Code("<="),EQ:new Q._Code("==="),NEQ:new Q._Code("!=="),NOT:new Q._Code("!"),OR:new Q._Code("||"),AND:new Q._Code("&&"),ADD:new Q._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Lm=class extends yr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Lt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Lo(this.rhs,e,r)),this}get names(){return this.rhs instanceof Q._CodeOrName?this.rhs.names:{}}},gu=class extends yr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Q.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Lo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Q.Name?{}:{...this.lhs.names};return yu(e,this.rhs)}},Fm=class extends gu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Hm=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Um=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},qm=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wm=class extends yr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Lo(this.code,e,r),this}get names(){return this.code instanceof Q._CodeOrName?this.code.names:{}}},si=class extends yr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(e,r)||(eL(e,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>zn(e,r.names),{})}},vr=class extends si{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Zm=class extends si{},jo=class extends vr{};jo.kind="else";var In=class t extends vr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new jo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ww(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Lo(this.condition,e,r),this}get names(){let e=super.names;return yu(e,this.condition),this.else&&zn(e,this.else.names),e}};In.kind="if";var $n=class extends vr{};$n.kind="for";var Bm=class extends $n{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Lo(this.iteration,e,r),this}get names(){return zn(super.names,this.iteration.names)}},Vm=class extends $n{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Lt.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=yu(super.names,this.from);return yu(e,this.to)}},_u=class extends $n{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Lo(this.iterable,e,r),this}get names(){return zn(super.names,this.iterable.names)}},ii=class extends vr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ii.kind="func";var ai=class extends si{render(e){return"return "+super.render(e)}};ai.kind="return";var Km=class extends vr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&zn(e,this.catch.names),this.finally&&zn(e,this.finally.names),e}},ci=class extends vr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ci.kind="catch";var ui=class extends vr{render(e){return"finally"+super.render(e)}};ui.kind="finally";var Gm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
10
+ `:""},this._extScope=e,this._scope=new Lt.Scope({parent:e}),this._nodes=[new Zm]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new Lm(e,i,n)),i}const(e,r,n){return this._def(Lt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Lt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Lt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new gu(e,r,n))}add(e,r){return this._leafNode(new Fm(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Q.nil&&this._leafNode(new Wm(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Q.addCodeArg)(r,o));return r.push("}"),new Q._Code(r)}if(e,r,n){if(this._blockNode(new In(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new In(e))}else(){return this._elseNode(new jo)}endIf(){return this._endBlockNode(In,jo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Bm(e),r)}forRange(e,r,n,o,i=this.opts.es5?Lt.varKinds.var:Lt.varKinds.let){let a=this._scope.toName(e);return this._for(new Vm(i,a,r,n),()=>o(a))}forOf(e,r,n,o=Lt.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let a=r instanceof Q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Q._)`${a}.length`,c=>{this.var(i,(0,Q._)`${a}[${c}]`),n(i)})}return this._for(new _u("of",o,i,r),()=>n(i))}forIn(e,r,n,o=this.opts.es5?Lt.varKinds.var:Lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Q._)`Object.keys(${r})`,n);let i=this._scope.toName(e);return this._for(new _u("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode($n)}label(e){return this._leafNode(new Hm(e))}break(e){return this._leafNode(new Um(e))}return(e){let r=new ai;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ai)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Km;if(this._blockNode(o),this.code(e),r){let i=this.name("e");this._currNode=o.catch=new ci(i),r(i)}return n&&(this._currNode=o.finally=new ui,this.code(n)),this._endBlockNode(ci,ui)}throw(e){return this._leafNode(new qm(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Q.nil,n,o){return this._blockNode(new ii(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ii)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof In))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=Gm;function zn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function yu(t,e){return e instanceof Q._CodeOrName?zn(t,e.names):t}function Lo(t,e,r){if(t instanceof Q.Name)return n(t);if(!o(t))return t;return new Q._Code(t._items.reduce((i,a)=>(a instanceof Q.Name&&(a=n(a)),a instanceof Q._Code?i.push(...a._items):i.push(a),i),[]));function n(i){let a=r[i.str];return a===void 0||e[i.str]!==1?i:(delete e[i.str],a)}function o(i){return i instanceof Q._Code&&i._items.some(a=>a instanceof Q.Name&&e[a.str]===1&&r[a.str]!==void 0)}}function eL(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ww(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Q._)`!${Jm(t)}`}K.not=Ww;var tL=Zw(K.operators.AND);function rL(...t){return t.reduce(tL)}K.and=rL;var nL=Zw(K.operators.OR);function oL(...t){return t.reduce(nL)}K.or=oL;function Zw(t){return(e,r)=>e===Q.nil?r:r===Q.nil?e:(0,Q._)`${Jm(e)} ${t} ${Jm(r)}`}function Jm(t){return t instanceof Q.Name?t:(0,Q._)`(${t})`}});var te=k(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var pe=V(),sL=oi();function iL(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=iL;function aL(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Kw(t,e),!Gw(e,t.self.RULES.all))}G.alwaysValidSchema=aL;function Kw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let i in e)o[i]||Xw(t,`unknown keyword: "${i}"`)}G.checkUnknownRules=Kw;function Gw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Gw;function cL(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=cL;function uL({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,pe._)`${r}`}return(0,pe._)`${t}${e}${(0,pe.getProperty)(n)}`}G.schemaRefOrVal=uL;function lL(t){return Jw(decodeURIComponent(t))}G.unescapeFragment=lL;function dL(t){return encodeURIComponent(Xm(t))}G.escapeFragment=dL;function Xm(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=Xm;function Jw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=Jw;function pL(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=pL;function Bw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,i,a,c)=>{let u=a===void 0?i:a instanceof pe.Name?(i instanceof pe.Name?t(o,i,a):e(o,i,a),a):i instanceof pe.Name?(e(o,a,i),i):r(i,a);return c===pe.Name&&!(u instanceof pe.Name)?n(o,u):u}}G.mergeEvaluated={props:Bw({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,pe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,pe._)`${r} || {}`).code((0,pe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,pe._)`${r} || {}`),Qm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Yw}),items:Bw({mergeNames:(t,e,r)=>t.if((0,pe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,pe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,pe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,pe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Yw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,pe._)`{}`);return e!==void 0&&Qm(t,r,e),r}G.evaluatedPropsToName=Yw;function Qm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}G.setEvaluated=Qm;var Vw={};function mL(t,e){return t.scopeValue("func",{ref:e,code:Vw[e.code]||(Vw[e.code]=new sL._Code(e.code))})}G.useFunc=mL;var Ym;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ym||(G.Type=Ym={}));function fL(t,e,r){if(t instanceof pe.Name){let n=e===Ym.Num;return r?n?(0,pe._)`"[" + ${t} + "]"`:(0,pe._)`"['" + ${t} + "']"`:n?(0,pe._)`"/" + ${t}`:(0,pe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,pe.getProperty)(t).toString():"/"+Xm(t)}G.getErrorPath=fL;function Xw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=Xw});var br=k(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var Ze=V(),hL={data:new Ze.Name("data"),valCxt:new Ze.Name("valCxt"),instancePath:new Ze.Name("instancePath"),parentData:new Ze.Name("parentData"),parentDataProperty:new Ze.Name("parentDataProperty"),rootData:new Ze.Name("rootData"),dynamicAnchors:new Ze.Name("dynamicAnchors"),vErrors:new Ze.Name("vErrors"),errors:new Ze.Name("errors"),this:new Ze.Name("this"),self:new Ze.Name("self"),scope:new Ze.Name("scope"),json:new Ze.Name("json"),jsonPos:new Ze.Name("jsonPos"),jsonLen:new Ze.Name("jsonLen"),jsonPart:new Ze.Name("jsonPart")};ef.default=hL});var li=k(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var re=V(),bu=te(),Ye=br();Be.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Be.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function gL(t,e=Be.keywordError,r,n){let{it:o}=t,{gen:i,compositeRule:a,allErrors:c}=o,u=tk(t,e,r);n??(a||c)?Qw(i,u):ek(o,(0,re._)`[${u}]`)}Be.reportError=gL;function _L(t,e=Be.keywordError,r){let{it:n}=t,{gen:o,compositeRule:i,allErrors:a}=n,c=tk(t,e,r);Qw(o,c),i||a||ek(n,Ye.default.vErrors)}Be.reportExtraError=_L;function yL(t,e){t.assign(Ye.default.errors,e),t.if((0,re._)`${Ye.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Ye.default.vErrors}.length`,e),()=>t.assign(Ye.default.vErrors,null)))}Be.resetErrorsCount=yL;function vL({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let a=t.name("err");t.forRange("i",o,Ye.default.errors,c=>{t.const(a,(0,re._)`${Ye.default.vErrors}[${c}]`),t.if((0,re._)`${a}.instancePath === undefined`,()=>t.assign((0,re._)`${a}.instancePath`,(0,re.strConcat)(Ye.default.instancePath,i.errorPath))),t.assign((0,re._)`${a}.schemaPath`,(0,re.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,re._)`${a}.schema`,r),t.assign((0,re._)`${a}.data`,n))})}Be.extendErrors=vL;function Qw(t,e){let r=t.const("err",e);t.if((0,re._)`${Ye.default.vErrors} === null`,()=>t.assign(Ye.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Ye.default.vErrors}.push(${r})`),t.code((0,re._)`${Ye.default.errors}++`)}function ek(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var On={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function tk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:bL(t,e,r)}function bL(t,e,r={}){let{gen:n,it:o}=t,i=[SL(o,r),xL(t,r)];return wL(t,e,i),n.object(...i)}function SL({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,bu.getErrorPath)(e,bu.Type.Str)}`:t;return[Ye.default.instancePath,(0,re.strConcat)(Ye.default.instancePath,r)]}function xL({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,bu.getErrorPath)(r,bu.Type.Str)}`),[On.schemaPath,o]}function wL(t,{params:e,message:r},n){let{keyword:o,data:i,schemaValue:a,it:c}=t,{opts:u,propertyName:l,topSchemaRef:d,schemaPath:p}=c;n.push([On.keyword,o],[On.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),u.messages&&n.push([On.message,typeof r=="function"?r(t):r]),u.verbose&&n.push([On.schema,a],[On.parentSchema,(0,re._)`${d}${p}`],[Ye.default.data,i]),l&&n.push([On.propertyName,l])}});var nk=k(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.boolOrEmptySchema=Fo.topBoolOrEmptySchema=void 0;var kL=li(),RL=V(),PL=br(),EL={message:"boolean schema is false"};function CL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?rk(t,!1):typeof r=="object"&&r.$async===!0?e.return(PL.default.data):(e.assign((0,RL._)`${n}.errors`,null),e.return(!0))}Fo.topBoolOrEmptySchema=CL;function TL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),rk(t)):r.var(e,!0)}Fo.boolOrEmptySchema=TL;function rk(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,kL.reportError)(o,EL,void 0,e)}});var tf=k(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.getRules=Ho.isJSONType=void 0;var AL=["string","number","integer","boolean","null","object","array"],IL=new Set(AL);function $L(t){return typeof t=="string"&&IL.has(t)}Ho.isJSONType=$L;function zL(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ho.getRules=zL});var rf=k(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.shouldUseRule=Fr.shouldUseGroup=Fr.schemaHasRulesForType=void 0;function OL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ok(t,n)}Fr.schemaHasRulesForType=OL;function ok(t,e){return e.rules.some(r=>sk(t,r))}Fr.shouldUseGroup=ok;function sk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Fr.shouldUseRule=sk});var di=k(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var DL=tf(),ML=rf(),NL=li(),Z=V(),ik=te(),Uo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Uo||(Ve.DataType=Uo={}));function jL(t){let e=ak(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ve.getSchemaTypes=jL;function ak(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(DL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ve.getJSONTypes=ak;function LL(t,e){let{gen:r,data:n,opts:o}=t,i=FL(e,o.coerceTypes),a=e.length>0&&!(i.length===0&&e.length===1&&(0,ML.schemaHasRulesForType)(t,e[0]));if(a){let c=of(e,n,o.strictNumbers,Uo.Wrong);r.if(c,()=>{i.length?HL(t,e,i):sf(t)})}return a}Ve.coerceAndCheckDataType=LL;var ck=new Set(["string","number","integer","boolean","null"]);function FL(t,e){return e?t.filter(r=>ck.has(r)||e==="array"&&r==="array"):[]}function HL(t,e,r){let{gen:n,data:o,opts:i}=t,a=n.let("dataType",(0,Z._)`typeof ${o}`),c=n.let("coerced",(0,Z._)`undefined`);i.coerceTypes==="array"&&n.if((0,Z._)`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Z._)`${o}[0]`).assign(a,(0,Z._)`typeof ${o}`).if(of(e,o,i.strictNumbers),()=>n.assign(c,o))),n.if((0,Z._)`${c} !== undefined`);for(let l of r)(ck.has(l)||l==="array"&&i.coerceTypes==="array")&&u(l);n.else(),sf(t),n.endIf(),n.if((0,Z._)`${c} !== undefined`,()=>{n.assign(o,c),UL(t,c)});function u(l){switch(l){case"string":n.elseIf((0,Z._)`${a} == "number" || ${a} == "boolean"`).assign(c,(0,Z._)`"" + ${o}`).elseIf((0,Z._)`${o} === null`).assign(c,(0,Z._)`""`);return;case"number":n.elseIf((0,Z._)`${a} == "boolean" || ${o} === null
11
11
  || (${a} == "string" && ${o} && ${o} == +${o})`).assign(c,(0,Z._)`+${o}`);return;case"integer":n.elseIf((0,Z._)`${a} === "boolean" || ${o} === null
12
12
  || (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(c,(0,Z._)`+${o}`);return;case"boolean":n.elseIf((0,Z._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(c,!1).elseIf((0,Z._)`${o} === "true" || ${o} === 1`).assign(c,!0);return;case"null":n.elseIf((0,Z._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(c,null);return;case"array":n.elseIf((0,Z._)`${a} === "string" || ${a} === "number"
13
- || ${a} === "boolean" || ${o} === null`).assign(c,(0,Z._)`[${o}]`)}}}function cL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Z._)`${e} !== undefined`,()=>t.assign((0,Z._)`${e}[${r}]`,n))}function Ym(t,e,r,n=Ho.Correct){let o=n===Ho.Correct?Z.operators.EQ:Z.operators.NEQ,i;switch(t){case"null":return(0,Z._)`${e} ${o} null`;case"array":i=(0,Z._)`Array.isArray(${e})`;break;case"object":i=(0,Z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=a((0,Z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=a();break;default:return(0,Z._)`typeof ${e} ${o} ${t}`}return n===Ho.Correct?i:(0,Z.not)(i);function a(c=Z.nil){return(0,Z.and)((0,Z._)`typeof ${e} == "number"`,c,r?(0,Z._)`isFinite(${e})`:Z.nil)}}Be.checkDataType=Ym;function Xm(t,e,r,n){if(t.length===1)return Ym(t[0],e,r,n);let o,i=(0,Kw.toHash)(t);if(i.array&&i.object){let a=(0,Z._)`typeof ${e} != "object"`;o=i.null?a:(0,Z._)`!${e} || ${a}`,delete i.null,delete i.array,delete i.object}else o=Z.nil;i.number&&delete i.integer;for(let a in i)o=(0,Z.and)(o,Ym(a,e,r,n));return o}Be.checkDataTypes=Xm;var uL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Z._)`{type: ${t}}`:(0,Z._)`{type: ${e}}`};function Qm(t){let e=lL(t);(0,nL.reportError)(e,uL)}Be.reportTypeError=Qm;function lL(t){let{gen:e,data:r,schema:n}=t,o=(0,Kw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Xw=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.assignDefaults=void 0;var Uo=V(),dL=te();function pL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Yw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Yw(t,i,o.default))}_u.assignDefaults=pL;function Yw(t,e,r){let{gen:n,compositeRule:o,data:i,opts:a}=t;if(r===void 0)return;let c=(0,Uo._)`${i}${(0,Uo.getProperty)(e)}`;if(o){(0,dL.checkStrictMode)(t,`default is ignored for: ${c}`);return}let u=(0,Uo._)`${c} === undefined`;a.useDefaults==="empty"&&(u=(0,Uo._)`${u} || ${c} === null || ${c} === ""`),n.if(u,(0,Uo._)`${c} = ${(0,Uo.stringify)(r)}`)}});var Rt=k(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ye=V(),ef=te(),Fr=vr(),mL=te();function fL(t,e){let{gen:r,data:n,it:o}=t;r.if(rf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ye._)`${e}`},!0),t.error()})}le.checkReportMissingProp=fL;function hL({gen:t,data:e,it:{opts:r}},n,o){return(0,ye.or)(...n.map(i=>(0,ye.and)(rf(t,e,i,r.ownProperties),(0,ye._)`${o} = ${i}`)))}le.checkMissingProp=hL;function gL(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=gL;function Qw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Qw;function tf(t,e,r){return(0,ye._)`${Qw(t)}.call(${e}, ${r})`}le.isOwnProperty=tf;function _L(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} !== undefined`;return n?(0,ye._)`${o} && ${tf(t,e,r)}`:o}le.propertyInData=_L;function rf(t,e,r,n){let o=(0,ye._)`${e}${(0,ye.getProperty)(r)} === undefined`;return n?(0,ye.or)(o,(0,ye.not)(tf(t,e,r))):o}le.noPropertyInData=rf;function ek(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=ek;function yL(t,e){return ek(e).filter(r=>!(0,ef.alwaysValidSchema)(t,e[r]))}le.schemaProperties=yL;function vL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:a},c,u,l){let d=l?(0,ye._)`${t}, ${e}, ${n}${o}`:e,p=[[Fr.default.instancePath,(0,ye.strConcat)(Fr.default.instancePath,i)],[Fr.default.parentData,a.parentData],[Fr.default.parentDataProperty,a.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];a.opts.dynamicRef&&p.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let m=(0,ye._)`${d}, ${r.object(...p)}`;return u!==ye.nil?(0,ye._)`${c}.call(${u}, ${m})`:(0,ye._)`${c}(${m})`}le.callValidateCode=vL;var bL=(0,ye._)`new RegExp`;function SL({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,ye._)`${o.code==="new RegExp"?bL:(0,mL.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=SL;function xL(t){let{gen:e,data:r,keyword:n,it:o}=t,i=e.name("valid");if(o.allErrors){let c=e.let("valid",!0);return a(()=>e.assign(c,!1)),c}return e.var(i,!0),a(()=>e.break()),i;function a(c){let u=e.const("len",(0,ye._)`${r}.length`);e.forRange("i",0,u,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ef.Type.Num},i),e.if((0,ye.not)(i),c)})}}le.validateArray=xL;function wL(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(u=>(0,ef.alwaysValidSchema)(o,u))&&!o.opts.unevaluated)return;let a=e.let("valid",!1),c=e.name("_valid");e.block(()=>r.forEach((u,l)=>{let d=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},c);e.assign(a,(0,ye._)`${a} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,ye.not)(a))})),t.result(a,()=>t.reset(),()=>t.error(!0))}le.validateUnion=wL});var nk=k(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.validateKeywordUsage=Qt.validSchemaType=Qt.funcKeywordCode=Qt.macroKeywordCode=void 0;var Ye=V(),On=vr(),kL=Rt(),RL=ui();function PL(t,e){let{gen:r,keyword:n,schema:o,parentSchema:i,it:a}=t,c=e.macro.call(a.self,o,i,a),u=rk(r,n,c);a.opts.validateSchema!==!1&&a.self.validateSchema(c,!0);let l=r.name("valid");t.subschema({schema:c,schemaPath:Ye.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:u,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Qt.macroKeywordCode=PL;function EL(t,e){var r;let{gen:n,keyword:o,schema:i,parentSchema:a,$data:c,it:u}=t;TL(u,e);let l=!c&&e.compile?e.compile.call(u.self,i,a,u):e.validate,d=rk(n,o,l),p=n.let("valid");t.block$data(p,m),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function m(){if(e.errors===!1)g(),e.modifying&&tk(t),y(()=>t.error());else{let S=e.async?f():_();e.modifying&&tk(t),y(()=>CL(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>g((0,Ye._)`await `),x=>n.assign(p,!1).if((0,Ye._)`${x} instanceof ${u.ValidationError}`,()=>n.assign(S,(0,Ye._)`${x}.errors`),()=>n.throw(x))),S}function _(){let S=(0,Ye._)`${d}.errors`;return n.assign(S,null),g(Ye.nil),S}function g(S=e.async?(0,Ye._)`await `:Ye.nil){let x=u.opts.passContext?On.default.this:On.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(p,(0,Ye._)`${S}${(0,kL.callValidateCode)(t,d,x,w)}`,e.modifying)}function y(S){var x;n.if((0,Ye.not)((x=e.valid)!==null&&x!==void 0?x:p),S)}}Qt.funcKeywordCode=EL;function tk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ye._)`${n.parentData}[${n.parentDataProperty}]`))}function CL(t,e){let{gen:r}=t;r.if((0,Ye._)`Array.isArray(${e})`,()=>{r.assign(On.default.vErrors,(0,Ye._)`${On.default.vErrors} === null ? ${e} : ${On.default.vErrors}.concat(${e})`).assign(On.default.errors,(0,Ye._)`${On.default.vErrors}.length`),(0,RL.extendErrors)(t)},()=>t.error())}function TL({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function rk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ye.stringify)(r)})}function AL(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Qt.validSchemaType=AL;function IL({schema:t,opts:e,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let a=o.dependencies;if(a?.some(c=>!Object.prototype.hasOwnProperty.call(t,c)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let u=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(u);else throw new Error(u)}}Qt.validateKeywordUsage=IL});var sk=k(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.extendSubschemaMode=Hr.extendSubschemaData=Hr.getSubschema=void 0;var er=V(),ok=te();function $L(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:a}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let c=t.schema[e];return r===void 0?{schema:c,schemaPath:(0,er._)`${t.schemaPath}${(0,er.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,er._)`${t.schemaPath}${(0,er.getProperty)(e)}${(0,er.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ok.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:a,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Hr.getSubschema=$L;function zL(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:a}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=e;if(r!==void 0){let{errorPath:l,dataPathArr:d,opts:p}=e,m=c.let("data",(0,er._)`${e.data}${(0,er.getProperty)(r)}`,!0);u(m),t.errorPath=(0,er.str)`${l}${(0,ok.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,er._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let l=o instanceof er.Name?o:c.let("data",o,!0);u(l),a!==void 0&&(t.propertyName=a)}i&&(t.dataTypes=i);function u(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Hr.extendSubschemaData=zL;function OL(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}Hr.extendSubschemaMode=OL});var nf=k((Ree,ik)=>{"use strict";ik.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var a=i[o];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}});var ck=k((Pee,ak)=>{"use strict";var Ur=ak.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};yu(e,n,o,t,"",t)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function yu(t,e,r,n,o,i,a,c,u,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,a,c,u,l);for(var d in n){var p=n[d];if(Array.isArray(p)){if(d in Ur.arrayKeywords)for(var m=0;m<p.length;m++)yu(t,e,r,p[m],o+"/"+d+"/"+m,i,o,d,n,m)}else if(d in Ur.propsKeywords){if(p&&typeof p=="object")for(var f in p)yu(t,e,r,p[f],o+"/"+d+"/"+DL(f),i,o,d,n,f)}else(d in Ur.keywords||t.allKeys&&!(d in Ur.skipKeywords))&&yu(t,e,r,p,o+"/"+d,i,o,d,n)}r(n,o,i,a,c,u,l)}}function DL(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var di=k(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;var ML=te(),NL=nf(),jL=ck(),LL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function FL(t,e=!0){return typeof t=="boolean"?!0:e===!0?!of(t):e?uk(t)<=e:!1}ot.inlineRef=FL;var HL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function of(t){for(let e in t){if(HL.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(of)||typeof r=="object"&&of(r))return!0}return!1}function uk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!LL.has(r)&&(typeof t[r]=="object"&&(0,ML.eachItem)(t[r],n=>e+=uk(n)),e===1/0))return 1/0}return e}function lk(t,e="",r){r!==!1&&(e=qo(e));let n=t.parse(e);return dk(t,n)}ot.getFullPath=lk;function dk(t,e){return t.serialize(e).split("#")[0]+"#"}ot._getFullPath=dk;var UL=/#\/?$/;function qo(t){return t?t.replace(UL,""):""}ot.normalizeId=qo;function qL(t,e,r){return r=qo(r),t.resolve(e,r)}ot.resolveUrl=qL;var WL=/^[a-z_][-a-z0-9._]*$/i;function ZL(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=qo(t[r]||e),i={"":o},a=lk(n,o,!1),c={},u=new Set;return jL(t,{allKeys:!0},(p,m,f,_)=>{if(_===void 0)return;let g=a+m,y=i[_];typeof p[r]=="string"&&(y=S.call(this,p[r])),x.call(this,p.$anchor),x.call(this,p.$dynamicAnchor),i[m]=y;function S(w){let T=this.opts.uriResolver.resolve;if(w=qo(y?T(y,w):w),u.has(w))throw d(w);u.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(p,v.schema,w):w!==qo(g)&&(w[0]==="#"?(l(p,c[w],w),c[w]=p):this.refs[w]=g),w}function x(w){if(typeof w=="string"){if(!WL.test(w))throw new Error(`invalid anchor "${w}"`);S.call(this,`#${w}`)}}}),c;function l(p,m,f){if(m!==void 0&&!NL(p,m))throw d(f)}function d(p){return new Error(`reference "${p}" resolves to more than one schema`)}}ot.getSchemaRefs=ZL});var fi=k(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getData=qr.KeywordCxt=qr.validateFunctionCode=void 0;var gk=Zw(),pk=li(),af=Jm(),vu=li(),BL=Xw(),mi=nk(),sf=sk(),M=V(),q=vr(),VL=di(),br=te(),pi=ui();function KL(t){if(vk(t)&&(bk(t),yk(t))){YL(t);return}_k(t,()=>(0,gk.topBoolOrEmptySchema)(t))}qr.validateFunctionCode=KL;function _k({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},i){o.code.es5?t.func(e,(0,M._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,M._)`"use strict"; ${mk(r,o)}`),JL(t,o),t.code(i)}):t.func(e,(0,M._)`${q.default.data}, ${GL(o)}`,n.$async,()=>t.code(mk(r,o)).code(i))}function GL(t){return(0,M._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,M._)`, ${q.default.dynamicAnchors}={}`:M.nil}}={}`}function JL(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,M._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,M._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,M._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,M._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,M._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,M._)`""`),t.var(q.default.parentData,(0,M._)`undefined`),t.var(q.default.parentDataProperty,(0,M._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,M._)`{}`)})}function YL(t){let{schema:e,opts:r,gen:n}=t;_k(t,()=>{r.$comment&&e.$comment&&xk(t),rF(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&XL(t),Sk(t),sF(t)})}function XL(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,M._)`${r}.evaluated`),e.if((0,M._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,M._)`${t.evaluated}.props`,(0,M._)`undefined`)),e.if((0,M._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,M._)`${t.evaluated}.items`,(0,M._)`undefined`))}function mk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}function QL(t,e){if(vk(t)&&(bk(t),yk(t))){eF(t,e);return}(0,gk.boolOrEmptySchema)(t,e)}function yk({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function vk(t){return typeof t.schema!="boolean"}function eF(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&xk(t),nF(t),oF(t);let i=n.const("_errs",q.default.errors);Sk(t,i),n.var(e,(0,M._)`${i} === ${q.default.errors}`)}function bk(t){(0,br.checkUnknownRules)(t),tF(t)}function Sk(t,e){if(t.opts.jtd)return fk(t,[],!1,e);let r=(0,pk.getSchemaTypes)(t.schema),n=(0,pk.coerceAndCheckDataType)(t,r);fk(t,r,!n,e)}function tF(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,br.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function rF(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,br.checkStrictMode)(t,"default is ignored in the schema root")}function nF(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,VL.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function oF(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function xk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)t.code((0,M._)`${q.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let a=(0,M.str)`${n}/$comment`,c=t.scopeValue("root",{ref:e.root});t.code((0,M._)`${q.default.self}.opts.$comment(${i}, ${a}, ${c}.schema)`)}}function sF(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=t;r.$async?e.if((0,M._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,M._)`new ${o}(${q.default.vErrors})`)):(e.assign((0,M._)`${n}.errors`,q.default.vErrors),i.unevaluated&&iF(t),e.return((0,M._)`${q.default.errors} === 0`))}function iF({gen:t,evaluated:e,props:r,items:n}){r instanceof M.Name&&t.assign((0,M._)`${e}.props`,r),n instanceof M.Name&&t.assign((0,M._)`${e}.items`,n)}function fk(t,e,r,n){let{gen:o,schema:i,data:a,allErrors:c,opts:u,self:l}=t,{RULES:d}=l;if(i.$ref&&(u.ignoreKeywordsWithRef||!(0,br.schemaHasRulesButRef)(i,d))){o.block(()=>kk(t,"$ref",d.all.$ref.definition));return}u.jtd||aF(t,e),o.block(()=>{for(let m of d.rules)p(m);p(d.post)});function p(m){(0,af.shouldUseGroup)(i,m)&&(m.type?(o.if((0,vu.checkDataType)(m.type,a,u.strictNumbers)),hk(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,vu.reportTypeError)(t)),o.endIf()):hk(t,m),c||o.if((0,M._)`${q.default.errors} === ${n||0}`))}}function hk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,BL.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,af.shouldUseRule)(n,i)&&kk(t,i.keyword,i.definition,e.type)})}function aF(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(cF(t,e),t.opts.allowUnionTypes||uF(t,e),lF(t,t.dataTypes))}function cF(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{wk(t.dataTypes,r)||cf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),pF(t,e)}}function uF(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&cf(t,"use allowUnionTypes to allow union type keyword")}function lF(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,af.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(a=>dF(e,a))&&cf(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function dF(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function wk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function pF(t,e){let r=[];for(let n of t.dataTypes)wk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function cf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,br.checkStrictMode)(t,e,t.opts.strictTypes)}var bu=class{constructor(e,r,n){if((0,mi.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,br.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Rk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,mi.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,M.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,M.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,M._)`${r} !== undefined && (${(0,M.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?pi.reportExtraError:pi.reportError)(this,this.def.error,r)}$dataError(){(0,pi.reportError)(this,this.def.$dataError||pi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,pi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=M.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:a}=this;n.if((0,M.or)((0,M._)`${o} === undefined`,r)),e!==M.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==M.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,M.or)(a(),c());function a(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let u=Array.isArray(n)?n:[n];return(0,M._)`${(0,vu.checkDataTypes)(u,r,i.opts.strictNumbers,vu.DataType.Wrong)}`}return M.nil}function c(){if(o.validateSchema){let u=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,M._)`!${u}(${r})`}return M.nil}}subschema(e,r){let n=(0,sf.getSubschema)(this.it,e);(0,sf.extendSubschemaData)(n,this.it,e),(0,sf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return QL(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=br.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=br.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,M.Name)),!0}};qr.KeywordCxt=bu;function kk(t,e,r,n){let o=new bu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,mi.funcKeywordCode)(o,r):"macro"in r?(0,mi.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,mi.funcKeywordCode)(o,r)}var mF=/^\/(?:[^~]|~0|~1)*$/,fF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Rk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,i;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!mF.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=q.default.rootData}else{let l=fF.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+l[1];if(o=l[2],o==="#"){if(d>=e)throw new Error(u("property/index",d));return n[e-d]}if(d>e)throw new Error(u("data",d));if(i=r[e-d],!o)return i}let a=i,c=o.split("/");for(let l of c)l&&(i=(0,M._)`${i}${(0,M.getProperty)((0,br.unescapeJsonPointer)(l))}`,a=(0,M._)`${a} && ${i}`);return a;function u(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}qr.getData=Rk});var Su=k(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var uf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};lf.default=uf});var hi=k(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var df=di(),pf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,df.resolveUrl)(e,r,n),this.missingSchema=(0,df.normalizeId)((0,df.getFullPath)(e,this.missingRef))}};mf.default=pf});var wu=k(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.resolveSchema=Pt.getCompilingSchema=Pt.resolveRef=Pt.compileSchema=Pt.SchemaEnv=void 0;var Lt=V(),hF=Su(),Dn=vr(),Ft=di(),Pk=te(),gF=fi(),Wo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Ft.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Pt.SchemaEnv=Wo;function hf(t){let e=Ek.call(this,t);if(e)return e;let r=(0,Ft.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,a=new Lt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),c;t.$async&&(c=a.scopeValue("Error",{ref:hF.default,code:(0,Lt._)`require("ajv/dist/runtime/validation_error").default`}));let u=a.scopeName("validate");t.validateName=u;let l={gen:a,allErrors:this.opts.allErrors,data:Dn.default.data,parentData:Dn.default.parentData,parentDataProperty:Dn.default.parentDataProperty,dataNames:[Dn.default.data],dataPathArr:[Lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Lt.stringify)(t.schema)}:{ref:t.schema}),validateName:u,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Lt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Lt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,gF.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let p=a.toString();d=`${a.scopeRefs(Dn.default.scope)}return ${p}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${Dn.default.self}`,`${Dn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(u,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:u,validateCode:p,scopeValues:a._values}),this.opts.unevaluated){let{props:_,items:g}=l;f.evaluated={props:_ instanceof Lt.Name?void 0:_,items:g instanceof Lt.Name?void 0:g,dynamicProps:_ instanceof Lt.Name,dynamicItems:g instanceof Lt.Name},f.source&&(f.source.evaluated=(0,Lt.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),p}finally{this._compilations.delete(t)}}Pt.compileSchema=hf;function _F(t,e,r){var n;r=(0,Ft.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let i=bF.call(this,t,r);if(i===void 0){let a=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;a&&(i=new Wo({schema:a,schemaId:c,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=yF.call(this,i)}Pt.resolveRef=_F;function yF(t){return(0,Ft.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:hf.call(this,t)}function Ek(t){for(let e of this._compilations)if(vF(e,t))return e}Pt.getCompilingSchema=Ek;function vF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function bF(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||xu.call(this,t,e)}function xu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Ft._getFullPath)(this.opts.uriResolver,r),o=(0,Ft.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ff.call(this,r,t);let i=(0,Ft.normalizeId)(n),a=this.refs[i]||this.schemas[i];if(typeof a=="string"){let c=xu.call(this,t,a);return typeof c?.schema!="object"?void 0:ff.call(this,r,c)}if(typeof a?.schema=="object"){if(a.validate||hf.call(this,a),i===(0,Ft.normalizeId)(e)){let{schema:c}=a,{schemaId:u}=this.opts,l=c[u];return l&&(o=(0,Ft.resolveUrl)(this.opts.uriResolver,o,l)),new Wo({schema:c,schemaId:u,root:t,baseId:o})}return ff.call(this,r,a)}}Pt.resolveSchema=xu;var SF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ff(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let c of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let u=r[(0,Pk.unescapeFragment)(c)];if(u===void 0)return;r=u;let l=typeof r=="object"&&r[this.opts.schemaId];!SF.has(c)&&l&&(e=(0,Ft.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Pk.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Ft.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=xu.call(this,n,c)}let{schemaId:a}=this.opts;if(i=i||new Wo({schema:r,schemaId:a,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var Ck=k(($ee,xF)=>{xF.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var yf=k((zee,Ok)=>{"use strict";var wF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ak=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),gf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ik=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),kF=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function _f(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var RF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Tk(t){return t.length=0,!0}function PF(t,e,r){if(t.length){let n=_f(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function EF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,a=!1,c=PF;for(let u=0;u<t.length;u++){let l=t[u];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(a=!0),!c(o,n,r))break;if(++e>7){r.error=!0;break}u>0&&t[u-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!c(o,n,r))break;c=Tk}else{o.push(l);continue}}return o.length&&(c===Tk?r.zone=o.join(""):a?n.push(o.join("")):n.push(_f(o))),r.address=n.join(""),r}function $k(t){if(CF(t,":")<2)return{host:t,isIPV6:!1};let e=EF(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function CF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function TF(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var AF={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},IF=/[@/?#:]/g,$F=/[@/?#]/g;function zk(t,e){let r=e?$F:IF;return r.lastIndex=0,t.replace(r,n=>AF[n])}function zF(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(gf(o)){let i=o.toUpperCase(),a=String.fromCharCode(parseInt(i,16));e&&Ik(a)?r+=a:r+="%"+i,n+=2;continue}}r+=t[n]}return r}function OF(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(gf(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Ik(i)?e+=i:e+="%"+o,r+=2;continue}}kF(t[r])?e+=t[r]:e+=escape(t[r])}return e}function DF(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(gf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function MF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ak(r)){let n=$k(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=zk(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Ok.exports={nonSimpleDomain:RF,recomposeAuthority:MF,reescapeHostDelimiters:zk,normalizePercentEncoding:zF,normalizePathEncoding:OF,escapePreservingEscapes:DF,removeDotSegments:TF,isIPv4:Ak,isUUID:wF,normalizeIPv6:$k,stringArrayToHexStripped:_f}});var Lk=k((Oee,jk)=>{"use strict";var{isUUID:NF}=yf(),jF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,LF=["http","https","ws","wss","urn","urn:uuid"];function FF(t){return LF.indexOf(t)!==-1}function vf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Dk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Mk(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function HF(t){return t.secure=vf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function UF(t){if((t.port===(vf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function qF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jF);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,i=bf(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function WF(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,i=bf(o);i&&(t=i.serialize(t,e));let a=t,c=t.nss;return a.path=`${n||e.nid}:${c}`,e.skipEscape=!0,a}function ZF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!NF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Nk={scheme:"http",domainHost:!0,parse:Dk,serialize:Mk},VF={scheme:"https",domainHost:Nk.domainHost,parse:Dk,serialize:Mk},ku={scheme:"ws",domainHost:!0,parse:HF,serialize:UF},KF={scheme:"wss",domainHost:ku.domainHost,parse:ku.parse,serialize:ku.serialize},GF={scheme:"urn",parse:qF,serialize:WF,skipNormalize:!0},JF={scheme:"urn:uuid",parse:ZF,serialize:BF,skipNormalize:!0},Ru={http:Nk,https:VF,ws:ku,wss:KF,urn:GF,"urn:uuid":JF};Object.setPrototypeOf(Ru,null);function bf(t){return t&&(Ru[t]||Ru[t.toLowerCase()])||void 0}jk.exports={wsIsSecure:vf,SCHEMES:Ru,isValidSchemeName:FF,getSchemeHandler:bf}});var Zk=k((Dee,Pu)=>{"use strict";var{normalizeIPv6:YF,removeDotSegments:gi,recomposeAuthority:XF,normalizePercentEncoding:QF,normalizePathEncoding:eH,escapePreservingEscapes:tH,reescapeHostDelimiters:rH,isIPv4:nH,nonSimpleDomain:oH}=yf(),{SCHEMES:sH,getSchemeHandler:Hk}=Lk();function iH(t,e){return typeof t=="string"?t=dH(t,e):typeof t=="object"&&(t=Zo(Mn(t,e),e)),t}function aH(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Uk(Zo(t,n),Zo(e,n),n,!0);return n.skipEscape=!0,Mn(o,n)}function Uk(t,e,r,n){let o={};return n||(t=Zo(Mn(t,r),r),e=Zo(Mn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=gi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=gi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=gi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=gi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function cH(t,e,r){let n=Fk(t,r),o=Fk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Mn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],i=Hk(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=QF(r.path):(r.path=tH(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let a=XF(r);if(a!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(a),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=gi(c)),a===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),o.push(c)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var uH=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function lH(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function qk(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let a=t.match(uH);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=lH(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(nH(n.host)===!1){let d=YF(n.host);n.host=d.host.toLowerCase(),i=d.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Hk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&i===!1&&oH(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=rH(unescape(n.host),i))),n.path&&(n.path=eH(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Zo(t,e){return qk(t,e).parsed}function dH(t,e){return Wk(t,e).normalized}function Wk(t,e){let{parsed:r,malformedAuthorityOrPort:n}=qk(t,e);return{normalized:n?t:Mn(r,e),malformedAuthorityOrPort:n}}function Fk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Wk(t,e);return n?void 0:r}if(typeof t=="object")return Mn(t,e)}var Sf={SCHEMES:sH,normalize:iH,resolve:aH,resolveComponent:Uk,equal:cH,serialize:Mn,parse:Zo};Pu.exports=Sf;Pu.exports.default=Sf;Pu.exports.fastUri=Sf});var Vk=k(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var Bk=Zk();Bk.code='require("ajv/dist/runtime/uri").default';xf.default=Bk});var tR=k(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var pH=fi();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return pH.KeywordCxt}});var Bo=V();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Bo._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Bo.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Bo.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Bo.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Bo.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Bo.CodeGen}});var mH=Su(),Xk=hi(),fH=Gm(),_i=wu(),hH=V(),yi=di(),Eu=li(),kf=te(),Kk=Ck(),gH=Vk(),Qk=(t,e)=>new RegExp(t,e);Qk.code="new RegExp";var _H=["removeAdditional","useDefaults","coerceTypes"],yH=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vH={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},bH={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gk=200;function SH(t){var e,r,n,o,i,a,c,u,l,d,p,m,f,_,g,y,S,x,w,T,v,P,O,J,F;let ie=t.strict,pt=(e=t.code)===null||e===void 0?void 0:e.optimize,mt=pt===!0||pt===void 0?1:pt||0,Kr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Qk,Ct=(o=t.uriResolver)!==null&&o!==void 0?o:gH.default;return{strictSchema:(a=(i=t.strictSchema)!==null&&i!==void 0?i:ie)!==null&&a!==void 0?a:!0,strictNumbers:(u=(c=t.strictNumbers)!==null&&c!==void 0?c:ie)!==null&&u!==void 0?u:!0,strictTypes:(d=(l=t.strictTypes)!==null&&l!==void 0?l:ie)!==null&&d!==void 0?d:"log",strictTuples:(m=(p=t.strictTuples)!==null&&p!==void 0?p:ie)!==null&&m!==void 0?m:"log",strictRequired:(_=(f=t.strictRequired)!==null&&f!==void 0?f:ie)!==null&&_!==void 0?_:!1,code:t.code?{...t.code,optimize:mt,regExp:Kr}:{optimize:mt,regExp:Kr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Gk,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Gk,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(T=t.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(J=t.unicodeRegExp)!==null&&J!==void 0?J:!0,int32range:(F=t.int32range)!==null&&F!==void 0?F:!0,uriResolver:Ct}}var vi=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...SH(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new hH.ValueScope({scope:{},prefixes:yH,es5:r,lines:n}),this.logger=EH(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,fH.getRules)(),Jk.call(this,vH,e,"NOT SUPPORTED"),Jk.call(this,bH,e,"DEPRECATED","warn"),this._metaOpts=RH.call(this),e.formats&&wH.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&kH.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xH.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Kk;n==="id"&&(o={...Kk},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,p){await i.call(this,d.$schema);let m=this._addSchema(d,p);return m.validate||a.call(this,m)}async function i(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function a(d){try{return this._compileSchemaEnv(d)}catch(p){if(!(p instanceof Xk.default))throw p;return c.call(this,p),await u.call(this,p.missingSchema),a.call(this,d)}}function c({missingSchema:d,missingRef:p}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${p} cannot be resolved`)}async function u(d){let p=await l.call(this,d);this.refs[d]||await i.call(this,p.$schema),this.refs[d]||this.addSchema(p,d,r)}async function l(d){let p=this._loading[d];if(p)return p;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let a of e)this.addSchema(a,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:a}=this.opts;if(i=e[a],i!==void 0&&typeof i!="string")throw new Error(`schema ${a} must be string`)}return r=(0,yi.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let r;for(;typeof(r=Yk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new _i.SchemaEnv({schema:{},schemaId:n});if(r=_i.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Yk.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,yi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(TH.call(this,n,r),!r)return(0,kf.eachItem)(n,i=>wf.call(this,i)),this;IH.call(this,r);let o={...r,type:(0,Eu.getJSONTypes)(r.type),schemaType:(0,Eu.getJSONTypes)(r.schemaType)};return(0,kf.eachItem)(n,o.type.length===0?i=>wf.call(this,i,o):i=>o.type.forEach(a=>wf.call(this,i,o,a))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let i=o.split("/").slice(1),a=e;for(let c of i)a=a[c];for(let c in n){let u=n[c];if(typeof u!="object")continue;let{$data:l}=u.definition,d=a[c];l&&d&&(a[c]=eR(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:c}=this.opts;if(typeof e=="object")a=e[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(u!==void 0)return u;n=(0,yi.normalizeId)(a||n);let l=yi.getSchemaRefs.call(this,e,n);return u=new _i.SchemaEnv({schema:e,schemaId:c,meta:r,baseId:n,localRefs:l}),this._cache.set(u.schema,u),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),o&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):_i.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{_i.compileSchema.call(this,e)}finally{this.opts=r}}};vi.ValidationError=mH.default;vi.MissingRefError=Xk.default;Le.default=vi;function Jk(t,e,r,n="error"){for(let o in t){let i=o;i in e&&this.logger[n](`${r}: option ${o}. ${t[i]}`)}}function Yk(t){return t=(0,yi.normalizeId)(t),this.schemas[t]||this.refs[t]}function xH(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function wH(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function kH(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function RH(){let t={...this.opts};for(let e of _H)delete t[e];return t}var PH={log(){},warn(){},error(){}};function EH(t){if(t===!1)return PH;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var CH=/^[a-z_$][a-z0-9_$:-]*$/i;function TH(t,e){let{RULES:r}=this;if((0,kf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!CH.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function wf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,a=o?i.post:i.rules.find(({type:u})=>u===r);if(a||(a={type:r,rules:[]},i.rules.push(a)),i.keywords[t]=!0,!e)return;let c={keyword:t,definition:{...e,type:(0,Eu.getJSONTypes)(e.type),schemaType:(0,Eu.getJSONTypes)(e.schemaType)}};e.before?AH.call(this,a,c,e.before):a.rules.push(c),i.all[t]=c,(n=e.implements)===null||n===void 0||n.forEach(u=>this.addKeyword(u))}function AH(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function IH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=eR(e)),t.validateSchema=this.compile(e,!0))}var $H={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function eR(t){return{anyOf:[t,$H]}}});var rR=k(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var zH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Rf.default=zH});var iR=k(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.callRef=Nn.getValidate=void 0;var OH=hi(),nR=Rt(),st=V(),Vo=vr(),oR=wu(),Cu=te(),DH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:i,validateName:a,opts:c,self:u}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return p();let d=oR.resolveRef.call(u,l,o,r);if(d===void 0)throw new OH.default(n.opts.uriResolver,o,r);if(d instanceof oR.SchemaEnv)return m(d);return f(d);function p(){if(i===l)return Tu(t,a,i,i.$async);let _=e.scopeValue("root",{ref:l});return Tu(t,(0,st._)`${_}.validate`,l,l.$async)}function m(_){let g=sR(t,_);Tu(t,g,_,_.$async)}function f(_){let g=e.scopeValue("schema",c.code.source===!0?{ref:_,code:(0,st.stringify)(_)}:{ref:_}),y=e.name("valid"),S=t.subschema({schema:_,dataTypes:[],schemaPath:st.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function sR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Nn.getValidate=sR;function Tu(t,e,r,n){let{gen:o,it:i}=t,{allErrors:a,schemaEnv:c,opts:u}=i,l=u.passContext?Vo.default.this:st.nil;n?d():p();function d(){if(!c.$async)throw new Error("async schema referenced by sync schema");let _=o.let("valid");o.try(()=>{o.code((0,st._)`await ${(0,nR.callValidateCode)(t,e,l)}`),f(e),a||o.assign(_,!0)},g=>{o.if((0,st._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),m(g),a||o.assign(_,!1)}),t.ok(_)}function p(){t.result((0,nR.callValidateCode)(t,e,l),()=>f(e),()=>m(e))}function m(_){let g=(0,st._)`${_}.errors`;o.assign(Vo.default.vErrors,(0,st._)`${Vo.default.vErrors} === null ? ${g} : ${Vo.default.vErrors}.concat(${g})`),o.assign(Vo.default.errors,(0,st._)`${Vo.default.vErrors}.length`)}function f(_){var g;if(!i.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(i.props=Cu.mergeEvaluated.props(o,y.props,i.props));else{let S=o.var("props",(0,st._)`${_}.evaluated.props`);i.props=Cu.mergeEvaluated.props(o,S,i.props,st.Name)}if(i.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(i.items=Cu.mergeEvaluated.items(o,y.items,i.items));else{let S=o.var("items",(0,st._)`${_}.evaluated.items`);i.items=Cu.mergeEvaluated.items(o,S,i.items,st.Name)}}}Nn.callRef=Tu;Nn.default=DH});var aR=k(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var MH=rR(),NH=iR(),jH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",MH.default,NH.default];Pf.default=jH});var cR=k(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var Au=V(),Wr=Au.operators,Iu={maximum:{okStr:"<=",ok:Wr.LTE,fail:Wr.GT},minimum:{okStr:">=",ok:Wr.GTE,fail:Wr.LT},exclusiveMaximum:{okStr:"<",ok:Wr.LT,fail:Wr.GTE},exclusiveMinimum:{okStr:">",ok:Wr.GT,fail:Wr.LTE}},LH={message:({keyword:t,schemaCode:e})=>(0,Au.str)`must be ${Iu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Au._)`{comparison: ${Iu[t].okStr}, limit: ${e}}`},FH={keyword:Object.keys(Iu),type:"number",schemaType:"number",$data:!0,error:LH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Au._)`${r} ${Iu[e].fail} ${n} || isNaN(${r})`)}};Ef.default=FH});var uR=k(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var bi=V(),HH={message:({schemaCode:t})=>(0,bi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bi._)`{multipleOf: ${t}}`},UH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:HH,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,i=o.opts.multipleOfPrecision,a=e.let("res"),c=i?(0,bi._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${i}`:(0,bi._)`${a} !== parseInt(${a})`;t.fail$data((0,bi._)`(${n} === 0 || (${a} = ${r}/${n}, ${c}))`)}};Cf.default=UH});var dR=k(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});function lR(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Tf.default=lR;lR.code='require("ajv/dist/runtime/ucs2length").default'});var pR=k(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var jn=V(),qH=te(),WH=dR(),ZH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,jn._)`{limit: ${t}}`},BH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZH,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,i=e==="maxLength"?jn.operators.GT:jn.operators.LT,a=o.opts.unicode===!1?(0,jn._)`${r}.length`:(0,jn._)`${(0,qH.useFunc)(t.gen,WH.default)}(${r})`;t.fail$data((0,jn._)`${a} ${i} ${n}`)}};Af.default=BH});var mR=k(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var VH=Rt(),KH=te(),Ko=V(),GH={message:({schemaCode:t})=>(0,Ko.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ko._)`{pattern: ${t}}`},JH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GH,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:a}=t,c=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:u}=a.opts.code,l=u.code==="new RegExp"?(0,Ko._)`new RegExp`:(0,KH.useFunc)(e,u),d=e.let("valid");e.try(()=>e.assign(d,(0,Ko._)`${l}(${i}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ko._)`!${d}`)}else{let u=(0,VH.usePattern)(t,o);t.fail$data((0,Ko._)`!${u}.test(${r})`)}}};If.default=JH});var fR=k($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var Si=V(),YH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Si.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Si._)`{limit: ${t}}`},XH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YH,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Si.operators.GT:Si.operators.LT;t.fail$data((0,Si._)`Object.keys(${r}).length ${o} ${n}`)}};$f.default=XH});var hR=k(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var xi=Rt(),wi=V(),QH=te(),eU={message:({params:{missingProperty:t}})=>(0,wi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,wi._)`{missingProperty: ${t}}`},tU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eU,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:i,it:a}=t,{opts:c}=a;if(!i&&r.length===0)return;let u=r.length>=c.loopRequired;if(a.allErrors?l():d(),c.strictRequired){let f=t.parentSchema.properties,{definedProperties:_}=t.it;for(let g of r)if(f?.[g]===void 0&&!_.has(g)){let y=a.schemaEnv.baseId+a.errSchemaPath,S=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,QH.checkStrictMode)(a,S,a.opts.strictRequired)}}function l(){if(u||i)t.block$data(wi.nil,p);else for(let f of r)(0,xi.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(u||i){let _=e.let("valid",!0);t.block$data(_,()=>m(f,_)),t.ok(_)}else e.if((0,xi.checkMissingProp)(t,r,f)),(0,xi.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,xi.noPropertyInData)(e,o,f,c.ownProperties),()=>t.error())})}function m(f,_){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(_,(0,xi.propertyInData)(e,o,f,c.ownProperties)),e.if((0,wi.not)(_),()=>{t.error(),e.break()})},wi.nil)}}};zf.default=tU});var gR=k(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var ki=V(),rU={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ki.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ki._)`{limit: ${t}}`},nU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rU,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ki.operators.GT:ki.operators.LT;t.fail$data((0,ki._)`${r}.length ${o} ${n}`)}};Of.default=nU});var $u=k(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var _R=nf();_R.code='require("ajv/dist/runtime/equal").default';Df.default=_R});var yR=k(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var Mf=li(),Fe=V(),oU=te(),sU=$u(),iU={message:({params:{i:t,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Fe._)`{i: ${t}, j: ${e}}`},aU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iU,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:i,schemaCode:a,it:c}=t;if(!n&&!o)return;let u=e.let("valid"),l=i.items?(0,Mf.getSchemaTypes)(i.items):[];t.block$data(u,d,(0,Fe._)`${a} === false`),t.ok(u);function d(){let _=e.let("i",(0,Fe._)`${r}.length`),g=e.let("j");t.setParams({i:_,j:g}),e.assign(u,!0),e.if((0,Fe._)`${_} > 1`,()=>(p()?m:f)(_,g))}function p(){return l.length>0&&!l.some(_=>_==="object"||_==="array")}function m(_,g){let y=e.name("item"),S=(0,Mf.checkDataTypes)(l,y,c.opts.strictNumbers,Mf.DataType.Wrong),x=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${_}--;`,()=>{e.let(y,(0,Fe._)`${r}[${_}]`),e.if(S,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${x}[${y}] == "number"`,()=>{e.assign(g,(0,Fe._)`${x}[${y}]`),t.error(),e.assign(u,!1).break()}).code((0,Fe._)`${x}[${y}] = ${_}`)})}function f(_,g){let y=(0,oU.useFunc)(e,sU.default),S=e.name("outer");e.label(S).for((0,Fe._)`;${_}--;`,()=>e.for((0,Fe._)`${g} = ${_}; ${g}--;`,()=>e.if((0,Fe._)`${y}(${r}[${_}], ${r}[${g}])`,()=>{t.error(),e.assign(u,!1).break(S)})))}}};Nf.default=aU});var vR=k(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var jf=V(),cU=te(),uU=$u(),lU={message:"must be equal to constant",params:({schemaCode:t})=>(0,jf._)`{allowedValue: ${t}}`},dU={keyword:"const",$data:!0,error:lU,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,jf._)`!${(0,cU.useFunc)(e,uU.default)}(${r}, ${o})`):t.fail((0,jf._)`${i} !== ${r}`)}};Lf.default=dU});var bR=k(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Ri=V(),pU=te(),mU=$u(),fU={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ri._)`{allowedValues: ${t}}`},hU={keyword:"enum",schemaType:"array",$data:!0,error:fU,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:a}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let c=o.length>=a.opts.loopEnum,u,l=()=>u??(u=(0,pU.useFunc)(e,mU.default)),d;if(c||n)d=e.let("valid"),t.block$data(d,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",i);d=(0,Ri.or)(...o.map((_,g)=>m(f,g)))}t.pass(d);function p(){e.assign(d,!1),e.forOf("v",i,f=>e.if((0,Ri._)`${l()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,_){let g=o[_];return typeof g=="object"&&g!==null?(0,Ri._)`${l()}(${r}, ${f}[${_}])`:(0,Ri._)`${r} === ${g}`}}};Ff.default=hU});var SR=k(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var gU=cR(),_U=uR(),yU=pR(),vU=mR(),bU=fR(),SU=hR(),xU=gR(),wU=yR(),kU=vR(),RU=bR(),PU=[gU.default,_U.default,yU.default,vU.default,bU.default,SU.default,xU.default,wU.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},kU.default,RU.default];Hf.default=PU});var qf=k(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.validateAdditionalItems=void 0;var Ln=V(),Uf=te(),EU={message:({params:{len:t}})=>(0,Ln.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ln._)`{limit: ${t}}`},CU={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:EU,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Uf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}xR(t,n)}};function xR(t,e){let{gen:r,schema:n,data:o,keyword:i,it:a}=t;a.items=!0;let c=r.const("len",(0,Ln._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ln._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Uf.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,Ln._)`${c} <= ${e.length}`);r.if((0,Ln.not)(l),()=>u(l)),t.ok(l)}function u(l){r.forRange("i",e.length,c,d=>{t.subschema({keyword:i,dataProp:d,dataPropType:Uf.Type.Num},l),a.allErrors||r.if((0,Ln.not)(l),()=>r.break())})}}Pi.validateAdditionalItems=xR;Pi.default=CU});var Wf=k(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.validateTuple=void 0;var wR=V(),zu=te(),TU=Rt(),AU={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return kR(t,"additionalItems",e);r.items=!0,!(0,zu.alwaysValidSchema)(r,e)&&t.ok((0,TU.validateArray)(t))}};function kR(t,e,r=t.schema){let{gen:n,parentSchema:o,data:i,keyword:a,it:c}=t;d(o),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=zu.mergeEvaluated.items(n,r.length,c.items));let u=n.name("valid"),l=n.const("len",(0,wR._)`${i}.length`);r.forEach((p,m)=>{(0,zu.alwaysValidSchema)(c,p)||(n.if((0,wR._)`${l} > ${m}`,()=>t.subschema({keyword:a,schemaProp:m,dataProp:m},u)),t.ok(u))});function d(p){let{opts:m,errSchemaPath:f}=c,_=r.length,g=_===p.minItems&&(_===p.maxItems||p[e]===!1);if(m.strictTuples&&!g){let y=`"${a}" is ${_}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,zu.checkStrictMode)(c,y,m.strictTuples)}}}Ei.validateTuple=kR;Ei.default=AU});var RR=k(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var IU=Wf(),$U={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,IU.validateTuple)(t,"items")};Zf.default=$U});var ER=k(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var PR=V(),zU=te(),OU=Rt(),DU=qf(),MU={message:({params:{len:t}})=>(0,PR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,PR._)`{limit: ${t}}`},NU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:MU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,zU.alwaysValidSchema)(n,e)&&(o?(0,DU.validateAdditionalItems)(t,o):t.ok((0,OU.validateArray)(t)))}};Bf.default=NU});var CR=k(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var Et=V(),Ou=te(),jU={message:({params:{min:t,max:e}})=>e===void 0?(0,Et.str)`must contain at least ${t} valid item(s)`:(0,Et.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Et._)`{minContains: ${t}}`:(0,Et._)`{minContains: ${t}, maxContains: ${e}}`},LU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t,a,c,{minContains:u,maxContains:l}=n;i.opts.next?(a=u===void 0?1:u,c=l):a=1;let d=e.const("len",(0,Et._)`${o}.length`);if(t.setParams({min:a,max:c}),c===void 0&&a===0){(0,Ou.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&a>c){(0,Ou.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ou.alwaysValidSchema)(i,r)){let g=(0,Et._)`${d} >= ${a}`;c!==void 0&&(g=(0,Et._)`${g} && ${d} <= ${c}`),t.pass(g);return}i.items=!0;let p=e.name("valid");c===void 0&&a===1?f(p,()=>e.if(p,()=>e.break())):a===0?(e.let(p,!0),c!==void 0&&e.if((0,Et._)`${o}.length > 0`,m)):(e.let(p,!1),m()),t.result(p,()=>t.reset());function m(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>_(y)))}function f(g,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:Ou.Type.Num,compositeRule:!0},g),y()})}function _(g){e.code((0,Et._)`${g}++`),c===void 0?e.if((0,Et._)`${g} >= ${a}`,()=>e.assign(p,!0).break()):(e.if((0,Et._)`${g} > ${c}`,()=>e.assign(p,!1).break()),a===1?e.assign(p,!0):e.if((0,Et._)`${g} >= ${a}`,()=>e.assign(p,!0)))}}};Vf.default=LU});var IR=k(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.validateSchemaDeps=tr.validatePropertyDeps=tr.error=void 0;var Kf=V(),FU=te(),Ci=Rt();tr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Kf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Kf._)`{property: ${t},
13
+ || ${a} === "boolean" || ${o} === null`).assign(c,(0,Z._)`[${o}]`)}}}function UL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Z._)`${e} !== undefined`,()=>t.assign((0,Z._)`${e}[${r}]`,n))}function nf(t,e,r,n=Uo.Correct){let o=n===Uo.Correct?Z.operators.EQ:Z.operators.NEQ,i;switch(t){case"null":return(0,Z._)`${e} ${o} null`;case"array":i=(0,Z._)`Array.isArray(${e})`;break;case"object":i=(0,Z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=a((0,Z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=a();break;default:return(0,Z._)`typeof ${e} ${o} ${t}`}return n===Uo.Correct?i:(0,Z.not)(i);function a(c=Z.nil){return(0,Z.and)((0,Z._)`typeof ${e} == "number"`,c,r?(0,Z._)`isFinite(${e})`:Z.nil)}}Ve.checkDataType=nf;function of(t,e,r,n){if(t.length===1)return nf(t[0],e,r,n);let o,i=(0,ik.toHash)(t);if(i.array&&i.object){let a=(0,Z._)`typeof ${e} != "object"`;o=i.null?a:(0,Z._)`!${e} || ${a}`,delete i.null,delete i.array,delete i.object}else o=Z.nil;i.number&&delete i.integer;for(let a in i)o=(0,Z.and)(o,nf(a,e,r,n));return o}Ve.checkDataTypes=of;var qL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Z._)`{type: ${t}}`:(0,Z._)`{type: ${e}}`};function sf(t){let e=WL(t);(0,NL.reportError)(e,qL)}Ve.reportTypeError=sf;function WL(t){let{gen:e,data:r,schema:n}=t,o=(0,ik.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var lk=k(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.assignDefaults=void 0;var qo=V(),ZL=te();function BL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)uk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>uk(t,i,o.default))}Su.assignDefaults=BL;function uk(t,e,r){let{gen:n,compositeRule:o,data:i,opts:a}=t;if(r===void 0)return;let c=(0,qo._)`${i}${(0,qo.getProperty)(e)}`;if(o){(0,ZL.checkStrictMode)(t,`default is ignored for: ${c}`);return}let u=(0,qo._)`${c} === undefined`;a.useDefaults==="empty"&&(u=(0,qo._)`${u} || ${c} === null || ${c} === ""`),n.if(u,(0,qo._)`${c} = ${(0,qo.stringify)(r)}`)}});var Pt=k(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var ve=V(),af=te(),Hr=br(),VL=te();function KL(t,e){let{gen:r,data:n,it:o}=t;r.if(uf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}le.checkReportMissingProp=KL;function GL({gen:t,data:e,it:{opts:r}},n,o){return(0,ve.or)(...n.map(i=>(0,ve.and)(uf(t,e,i,r.ownProperties),(0,ve._)`${o} = ${i}`)))}le.checkMissingProp=GL;function JL(t,e){t.setParams({missingProperty:e},!0),t.error()}le.reportMissingProp=JL;function dk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=dk;function cf(t,e,r){return(0,ve._)`${dk(t)}.call(${e}, ${r})`}le.isOwnProperty=cf;function YL(t,e,r,n){let o=(0,ve._)`${e}${(0,ve.getProperty)(r)} !== undefined`;return n?(0,ve._)`${o} && ${cf(t,e,r)}`:o}le.propertyInData=YL;function uf(t,e,r,n){let o=(0,ve._)`${e}${(0,ve.getProperty)(r)} === undefined`;return n?(0,ve.or)(o,(0,ve.not)(cf(t,e,r))):o}le.noPropertyInData=uf;function pk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=pk;function XL(t,e){return pk(e).filter(r=>!(0,af.alwaysValidSchema)(t,e[r]))}le.schemaProperties=XL;function QL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:a},c,u,l){let d=l?(0,ve._)`${t}, ${e}, ${n}${o}`:e,p=[[Hr.default.instancePath,(0,ve.strConcat)(Hr.default.instancePath,i)],[Hr.default.parentData,a.parentData],[Hr.default.parentDataProperty,a.parentDataProperty],[Hr.default.rootData,Hr.default.rootData]];a.opts.dynamicRef&&p.push([Hr.default.dynamicAnchors,Hr.default.dynamicAnchors]);let m=(0,ve._)`${d}, ${r.object(...p)}`;return u!==ve.nil?(0,ve._)`${c}.call(${u}, ${m})`:(0,ve._)`${c}(${m})`}le.callValidateCode=QL;var eF=(0,ve._)`new RegExp`;function tF({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,ve._)`${o.code==="new RegExp"?eF:(0,VL.useFunc)(t,o)}(${r}, ${n})`})}le.usePattern=tF;function rF(t){let{gen:e,data:r,keyword:n,it:o}=t,i=e.name("valid");if(o.allErrors){let c=e.let("valid",!0);return a(()=>e.assign(c,!1)),c}return e.var(i,!0),a(()=>e.break()),i;function a(c){let u=e.const("len",(0,ve._)`${r}.length`);e.forRange("i",0,u,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:af.Type.Num},i),e.if((0,ve.not)(i),c)})}}le.validateArray=rF;function nF(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(u=>(0,af.alwaysValidSchema)(o,u))&&!o.opts.unevaluated)return;let a=e.let("valid",!1),c=e.name("_valid");e.block(()=>r.forEach((u,l)=>{let d=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},c);e.assign(a,(0,ve._)`${a} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,ve.not)(a))})),t.result(a,()=>t.reset(),()=>t.error(!0))}le.validateUnion=nF});var hk=k(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateKeywordUsage=er.validSchemaType=er.funcKeywordCode=er.macroKeywordCode=void 0;var Xe=V(),Dn=br(),oF=Pt(),sF=li();function iF(t,e){let{gen:r,keyword:n,schema:o,parentSchema:i,it:a}=t,c=e.macro.call(a.self,o,i,a),u=fk(r,n,c);a.opts.validateSchema!==!1&&a.self.validateSchema(c,!0);let l=r.name("valid");t.subschema({schema:c,schemaPath:Xe.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:u,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}er.macroKeywordCode=iF;function aF(t,e){var r;let{gen:n,keyword:o,schema:i,parentSchema:a,$data:c,it:u}=t;uF(u,e);let l=!c&&e.compile?e.compile.call(u.self,i,a,u):e.validate,d=fk(n,o,l),p=n.let("valid");t.block$data(p,m),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function m(){if(e.errors===!1)g(),e.modifying&&mk(t),y(()=>t.error());else{let S=e.async?f():_();e.modifying&&mk(t),y(()=>cF(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>g((0,Xe._)`await `),x=>n.assign(p,!1).if((0,Xe._)`${x} instanceof ${u.ValidationError}`,()=>n.assign(S,(0,Xe._)`${x}.errors`),()=>n.throw(x))),S}function _(){let S=(0,Xe._)`${d}.errors`;return n.assign(S,null),g(Xe.nil),S}function g(S=e.async?(0,Xe._)`await `:Xe.nil){let x=u.opts.passContext?Dn.default.this:Dn.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(p,(0,Xe._)`${S}${(0,oF.callValidateCode)(t,d,x,w)}`,e.modifying)}function y(S){var x;n.if((0,Xe.not)((x=e.valid)!==null&&x!==void 0?x:p),S)}}er.funcKeywordCode=aF;function mk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Xe._)`${n.parentData}[${n.parentDataProperty}]`))}function cF(t,e){let{gen:r}=t;r.if((0,Xe._)`Array.isArray(${e})`,()=>{r.assign(Dn.default.vErrors,(0,Xe._)`${Dn.default.vErrors} === null ? ${e} : ${Dn.default.vErrors}.concat(${e})`).assign(Dn.default.errors,(0,Xe._)`${Dn.default.vErrors}.length`),(0,sF.extendErrors)(t)},()=>t.error())}function uF({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Xe.stringify)(r)})}function lF(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}er.validSchemaType=lF;function dF({schema:t,opts:e,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let a=o.dependencies;if(a?.some(c=>!Object.prototype.hasOwnProperty.call(t,c)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let u=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(u);else throw new Error(u)}}er.validateKeywordUsage=dF});var _k=k(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendSubschemaMode=Ur.extendSubschemaData=Ur.getSubschema=void 0;var tr=V(),gk=te();function pF(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:a}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let c=t.schema[e];return r===void 0?{schema:c,schemaPath:(0,tr._)`${t.schemaPath}${(0,tr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,tr._)`${t.schemaPath}${(0,tr.getProperty)(e)}${(0,tr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,gk.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:a,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Ur.getSubschema=pF;function mF(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:a}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=e;if(r!==void 0){let{errorPath:l,dataPathArr:d,opts:p}=e,m=c.let("data",(0,tr._)`${e.data}${(0,tr.getProperty)(r)}`,!0);u(m),t.errorPath=(0,tr.str)`${l}${(0,gk.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,tr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let l=o instanceof tr.Name?o:c.let("data",o,!0);u(l),a!==void 0&&(t.propertyName=a)}i&&(t.dataTypes=i);function u(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Ur.extendSubschemaData=mF;function fF(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}Ur.extendSubschemaMode=fF});var lf=k((ste,yk)=>{"use strict";yk.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var a=i[o];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}});var bk=k((ite,vk)=>{"use strict";var qr=vk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};xu(e,n,o,t,"",t)};qr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};qr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};qr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};qr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function xu(t,e,r,n,o,i,a,c,u,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,a,c,u,l);for(var d in n){var p=n[d];if(Array.isArray(p)){if(d in qr.arrayKeywords)for(var m=0;m<p.length;m++)xu(t,e,r,p[m],o+"/"+d+"/"+m,i,o,d,n,m)}else if(d in qr.propsKeywords){if(p&&typeof p=="object")for(var f in p)xu(t,e,r,p[f],o+"/"+d+"/"+hF(f),i,o,d,n,f)}else(d in qr.keywords||t.allKeys&&!(d in qr.skipKeywords))&&xu(t,e,r,p,o+"/"+d,i,o,d,n)}r(n,o,i,a,c,u,l)}}function hF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var pi=k(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.getSchemaRefs=st.resolveUrl=st.normalizeId=st._getFullPath=st.getFullPath=st.inlineRef=void 0;var gF=te(),_F=lf(),yF=bk(),vF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function bF(t,e=!0){return typeof t=="boolean"?!0:e===!0?!df(t):e?Sk(t)<=e:!1}st.inlineRef=bF;var SF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function df(t){for(let e in t){if(SF.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(df)||typeof r=="object"&&df(r))return!0}return!1}function Sk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!vF.has(r)&&(typeof t[r]=="object"&&(0,gF.eachItem)(t[r],n=>e+=Sk(n)),e===1/0))return 1/0}return e}function xk(t,e="",r){r!==!1&&(e=Wo(e));let n=t.parse(e);return wk(t,n)}st.getFullPath=xk;function wk(t,e){return t.serialize(e).split("#")[0]+"#"}st._getFullPath=wk;var xF=/#\/?$/;function Wo(t){return t?t.replace(xF,""):""}st.normalizeId=Wo;function wF(t,e,r){return r=Wo(r),t.resolve(e,r)}st.resolveUrl=wF;var kF=/^[a-z_][-a-z0-9._]*$/i;function RF(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Wo(t[r]||e),i={"":o},a=xk(n,o,!1),c={},u=new Set;return yF(t,{allKeys:!0},(p,m,f,_)=>{if(_===void 0)return;let g=a+m,y=i[_];typeof p[r]=="string"&&(y=S.call(this,p[r])),x.call(this,p.$anchor),x.call(this,p.$dynamicAnchor),i[m]=y;function S(w){let T=this.opts.uriResolver.resolve;if(w=Wo(y?T(y,w):w),u.has(w))throw d(w);u.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(p,v.schema,w):w!==Wo(g)&&(w[0]==="#"?(l(p,c[w],w),c[w]=p):this.refs[w]=g),w}function x(w){if(typeof w=="string"){if(!kF.test(w))throw new Error(`invalid anchor "${w}"`);S.call(this,`#${w}`)}}}),c;function l(p,m,f){if(m!==void 0&&!_F(p,m))throw d(f)}function d(p){return new Error(`reference "${p}" resolves to more than one schema`)}}st.getSchemaRefs=RF});var hi=k(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.getData=Wr.KeywordCxt=Wr.validateFunctionCode=void 0;var Ck=nk(),kk=di(),mf=rf(),wu=di(),PF=lk(),fi=hk(),pf=_k(),M=V(),q=br(),EF=pi(),Sr=te(),mi=li();function CF(t){if(Ik(t)&&($k(t),Ak(t))){IF(t);return}Tk(t,()=>(0,Ck.topBoolOrEmptySchema)(t))}Wr.validateFunctionCode=CF;function Tk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},i){o.code.es5?t.func(e,(0,M._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,M._)`"use strict"; ${Rk(r,o)}`),AF(t,o),t.code(i)}):t.func(e,(0,M._)`${q.default.data}, ${TF(o)}`,n.$async,()=>t.code(Rk(r,o)).code(i))}function TF(t){return(0,M._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,M._)`, ${q.default.dynamicAnchors}={}`:M.nil}}={}`}function AF(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,M._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,M._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,M._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,M._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,M._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,M._)`""`),t.var(q.default.parentData,(0,M._)`undefined`),t.var(q.default.parentDataProperty,(0,M._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,M._)`{}`)})}function IF(t){let{schema:e,opts:r,gen:n}=t;Tk(t,()=>{r.$comment&&e.$comment&&Ok(t),MF(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&$F(t),zk(t),LF(t)})}function $F(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,M._)`${r}.evaluated`),e.if((0,M._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,M._)`${t.evaluated}.props`,(0,M._)`undefined`)),e.if((0,M._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,M._)`${t.evaluated}.items`,(0,M._)`undefined`))}function Rk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}function zF(t,e){if(Ik(t)&&($k(t),Ak(t))){OF(t,e);return}(0,Ck.boolOrEmptySchema)(t,e)}function Ak({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Ik(t){return typeof t.schema!="boolean"}function OF(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Ok(t),NF(t),jF(t);let i=n.const("_errs",q.default.errors);zk(t,i),n.var(e,(0,M._)`${i} === ${q.default.errors}`)}function $k(t){(0,Sr.checkUnknownRules)(t),DF(t)}function zk(t,e){if(t.opts.jtd)return Pk(t,[],!1,e);let r=(0,kk.getSchemaTypes)(t.schema),n=(0,kk.coerceAndCheckDataType)(t,r);Pk(t,r,!n,e)}function DF(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Sr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function MF(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Sr.checkStrictMode)(t,"default is ignored in the schema root")}function NF(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,EF.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function jF(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ok({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)t.code((0,M._)`${q.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let a=(0,M.str)`${n}/$comment`,c=t.scopeValue("root",{ref:e.root});t.code((0,M._)`${q.default.self}.opts.$comment(${i}, ${a}, ${c}.schema)`)}}function LF(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=t;r.$async?e.if((0,M._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,M._)`new ${o}(${q.default.vErrors})`)):(e.assign((0,M._)`${n}.errors`,q.default.vErrors),i.unevaluated&&FF(t),e.return((0,M._)`${q.default.errors} === 0`))}function FF({gen:t,evaluated:e,props:r,items:n}){r instanceof M.Name&&t.assign((0,M._)`${e}.props`,r),n instanceof M.Name&&t.assign((0,M._)`${e}.items`,n)}function Pk(t,e,r,n){let{gen:o,schema:i,data:a,allErrors:c,opts:u,self:l}=t,{RULES:d}=l;if(i.$ref&&(u.ignoreKeywordsWithRef||!(0,Sr.schemaHasRulesButRef)(i,d))){o.block(()=>Mk(t,"$ref",d.all.$ref.definition));return}u.jtd||HF(t,e),o.block(()=>{for(let m of d.rules)p(m);p(d.post)});function p(m){(0,mf.shouldUseGroup)(i,m)&&(m.type?(o.if((0,wu.checkDataType)(m.type,a,u.strictNumbers)),Ek(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,wu.reportTypeError)(t)),o.endIf()):Ek(t,m),c||o.if((0,M._)`${q.default.errors} === ${n||0}`))}}function Ek(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,PF.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,mf.shouldUseRule)(n,i)&&Mk(t,i.keyword,i.definition,e.type)})}function HF(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(UF(t,e),t.opts.allowUnionTypes||qF(t,e),WF(t,t.dataTypes))}function UF(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Dk(t.dataTypes,r)||ff(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),BF(t,e)}}function qF(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ff(t,"use allowUnionTypes to allow union type keyword")}function WF(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,mf.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(a=>ZF(e,a))&&ff(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function ZF(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Dk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function BF(t,e){let r=[];for(let n of t.dataTypes)Dk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ff(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Sr.checkStrictMode)(t,e,t.opts.strictTypes)}var ku=class{constructor(e,r,n){if((0,fi.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Sr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Nk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,fi.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,M.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,M.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,M._)`${r} !== undefined && (${(0,M.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?mi.reportExtraError:mi.reportError)(this,this.def.error,r)}$dataError(){(0,mi.reportError)(this,this.def.$dataError||mi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,mi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=M.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:a}=this;n.if((0,M.or)((0,M._)`${o} === undefined`,r)),e!==M.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==M.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,M.or)(a(),c());function a(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let u=Array.isArray(n)?n:[n];return(0,M._)`${(0,wu.checkDataTypes)(u,r,i.opts.strictNumbers,wu.DataType.Wrong)}`}return M.nil}function c(){if(o.validateSchema){let u=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,M._)`!${u}(${r})`}return M.nil}}subschema(e,r){let n=(0,pf.getSubschema)(this.it,e);(0,pf.extendSubschemaData)(n,this.it,e),(0,pf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return zF(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Sr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Sr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,M.Name)),!0}};Wr.KeywordCxt=ku;function Mk(t,e,r,n){let o=new ku(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,fi.funcKeywordCode)(o,r):"macro"in r?(0,fi.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,fi.funcKeywordCode)(o,r)}var VF=/^\/(?:[^~]|~0|~1)*$/,KF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Nk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,i;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!VF.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=q.default.rootData}else{let l=KF.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+l[1];if(o=l[2],o==="#"){if(d>=e)throw new Error(u("property/index",d));return n[e-d]}if(d>e)throw new Error(u("data",d));if(i=r[e-d],!o)return i}let a=i,c=o.split("/");for(let l of c)l&&(i=(0,M._)`${i}${(0,M.getProperty)((0,Sr.unescapeJsonPointer)(l))}`,a=(0,M._)`${a} && ${i}`);return a;function u(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Wr.getData=Nk});var Ru=k(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var hf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};gf.default=hf});var gi=k(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var _f=pi(),yf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,_f.resolveUrl)(e,r,n),this.missingSchema=(0,_f.normalizeId)((0,_f.getFullPath)(e,this.missingRef))}};vf.default=yf});var Eu=k(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.resolveSchema=Et.getCompilingSchema=Et.resolveRef=Et.compileSchema=Et.SchemaEnv=void 0;var Ft=V(),GF=Ru(),Mn=br(),Ht=pi(),jk=te(),JF=hi(),Zo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Ht.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Et.SchemaEnv=Zo;function Sf(t){let e=Lk.call(this,t);if(e)return e;let r=(0,Ht.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,a=new Ft.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),c;t.$async&&(c=a.scopeValue("Error",{ref:GF.default,code:(0,Ft._)`require("ajv/dist/runtime/validation_error").default`}));let u=a.scopeName("validate");t.validateName=u;let l={gen:a,allErrors:this.opts.allErrors,data:Mn.default.data,parentData:Mn.default.parentData,parentDataProperty:Mn.default.parentDataProperty,dataNames:[Mn.default.data],dataPathArr:[Ft.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ft.stringify)(t.schema)}:{ref:t.schema}),validateName:u,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ft.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ft._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,JF.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let p=a.toString();d=`${a.scopeRefs(Mn.default.scope)}return ${p}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${Mn.default.self}`,`${Mn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(u,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:u,validateCode:p,scopeValues:a._values}),this.opts.unevaluated){let{props:_,items:g}=l;f.evaluated={props:_ instanceof Ft.Name?void 0:_,items:g instanceof Ft.Name?void 0:g,dynamicProps:_ instanceof Ft.Name,dynamicItems:g instanceof Ft.Name},f.source&&(f.source.evaluated=(0,Ft.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),p}finally{this._compilations.delete(t)}}Et.compileSchema=Sf;function YF(t,e,r){var n;r=(0,Ht.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let i=eH.call(this,t,r);if(i===void 0){let a=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;a&&(i=new Zo({schema:a,schemaId:c,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=XF.call(this,i)}Et.resolveRef=YF;function XF(t){return(0,Ht.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sf.call(this,t)}function Lk(t){for(let e of this._compilations)if(QF(e,t))return e}Et.getCompilingSchema=Lk;function QF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function eH(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Pu.call(this,t,e)}function Pu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Ht._getFullPath)(this.opts.uriResolver,r),o=(0,Ht.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return bf.call(this,r,t);let i=(0,Ht.normalizeId)(n),a=this.refs[i]||this.schemas[i];if(typeof a=="string"){let c=Pu.call(this,t,a);return typeof c?.schema!="object"?void 0:bf.call(this,r,c)}if(typeof a?.schema=="object"){if(a.validate||Sf.call(this,a),i===(0,Ht.normalizeId)(e)){let{schema:c}=a,{schemaId:u}=this.opts,l=c[u];return l&&(o=(0,Ht.resolveUrl)(this.opts.uriResolver,o,l)),new Zo({schema:c,schemaId:u,root:t,baseId:o})}return bf.call(this,r,a)}}Et.resolveSchema=Pu;var tH=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bf(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let c of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let u=r[(0,jk.unescapeFragment)(c)];if(u===void 0)return;r=u;let l=typeof r=="object"&&r[this.opts.schemaId];!tH.has(c)&&l&&(e=(0,Ht.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,jk.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Ht.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=Pu.call(this,n,c)}let{schemaId:a}=this.opts;if(i=i||new Zo({schema:r,schemaId:a,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var Fk=k((pte,rH)=>{rH.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var kf=k((mte,Bk)=>{"use strict";var nH=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Uk=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),xf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),qk=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),oH=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var sH=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hk(t){return t.length=0,!0}function iH(t,e,r){if(t.length){let n=wf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function aH(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,a=!1,c=iH;for(let u=0;u<t.length;u++){let l=t[u];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(a=!0),!c(o,n,r))break;if(++e>7){r.error=!0;break}u>0&&t[u-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!c(o,n,r))break;c=Hk}else{o.push(l);continue}}return o.length&&(c===Hk?r.zone=o.join(""):a?n.push(o.join("")):n.push(wf(o))),r.address=n.join(""),r}function Wk(t){if(cH(t,":")<2)return{host:t,isIPV6:!1};let e=aH(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function cH(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function uH(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var lH={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},dH=/[@/?#:]/g,pH=/[@/?#]/g;function Zk(t,e){let r=e?pH:dH;return r.lastIndex=0,t.replace(r,n=>lH[n])}function mH(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(xf(o)){let i=o.toUpperCase(),a=String.fromCharCode(parseInt(i,16));e&&qk(a)?r+=a:r+="%"+i,n+=2;continue}}r+=t[n]}return r}function fH(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(xf(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&qk(i)?e+=i:e+="%"+o,r+=2;continue}}oH(t[r])?e+=t[r]:e+=escape(t[r])}return e}function hH(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(xf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function gH(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Uk(r)){let n=Wk(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Zk(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Bk.exports={nonSimpleDomain:sH,recomposeAuthority:gH,reescapeHostDelimiters:Zk,normalizePercentEncoding:mH,normalizePathEncoding:fH,escapePreservingEscapes:hH,removeDotSegments:uH,isIPv4:Uk,isUUID:nH,normalizeIPv6:Wk,stringArrayToHexStripped:wf}});var Yk=k((fte,Jk)=>{"use strict";var{isUUID:_H}=kf(),yH=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,vH=["http","https","ws","wss","urn","urn:uuid"];function bH(t){return vH.indexOf(t)!==-1}function Rf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Vk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Kk(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function SH(t){return t.secure=Rf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function xH(t){if((t.port===(Rf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function wH(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(yH);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,i=Pf(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function kH(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,i=Pf(o);i&&(t=i.serialize(t,e));let a=t,c=t.nss;return a.path=`${n||e.nid}:${c}`,e.skipEscape=!0,a}function RH(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!_H(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function PH(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Gk={scheme:"http",domainHost:!0,parse:Vk,serialize:Kk},EH={scheme:"https",domainHost:Gk.domainHost,parse:Vk,serialize:Kk},Cu={scheme:"ws",domainHost:!0,parse:SH,serialize:xH},CH={scheme:"wss",domainHost:Cu.domainHost,parse:Cu.parse,serialize:Cu.serialize},TH={scheme:"urn",parse:wH,serialize:kH,skipNormalize:!0},AH={scheme:"urn:uuid",parse:RH,serialize:PH,skipNormalize:!0},Tu={http:Gk,https:EH,ws:Cu,wss:CH,urn:TH,"urn:uuid":AH};Object.setPrototypeOf(Tu,null);function Pf(t){return t&&(Tu[t]||Tu[t.toLowerCase()])||void 0}Jk.exports={wsIsSecure:Rf,SCHEMES:Tu,isValidSchemeName:bH,getSchemeHandler:Pf}});var nR=k((hte,Au)=>{"use strict";var{normalizeIPv6:IH,removeDotSegments:_i,recomposeAuthority:$H,normalizePercentEncoding:zH,normalizePathEncoding:OH,escapePreservingEscapes:DH,reescapeHostDelimiters:MH,isIPv4:NH,nonSimpleDomain:jH}=kf(),{SCHEMES:LH,getSchemeHandler:Qk}=Yk();function FH(t,e){return typeof t=="string"?t=ZH(t,e):typeof t=="object"&&(t=Bo(Nn(t,e),e)),t}function HH(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=eR(Bo(t,n),Bo(e,n),n,!0);return n.skipEscape=!0,Nn(o,n)}function eR(t,e,r,n){let o={};return n||(t=Bo(Nn(t,r),r),e=Bo(Nn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=_i(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=_i(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=_i(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=_i(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function UH(t,e,r){let n=Xk(t,r),o=Xk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Nn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],i=Qk(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=zH(r.path):(r.path=DH(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let a=$H(r);if(a!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(a),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=_i(c)),a===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),o.push(c)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var qH=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function WH(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function tR(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let a=t.match(qH);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=WH(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(NH(n.host)===!1){let d=IH(n.host);n.host=d.host.toLowerCase(),i=d.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Qk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&i===!1&&jH(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=MH(unescape(n.host),i))),n.path&&(n.path=OH(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Bo(t,e){return tR(t,e).parsed}function ZH(t,e){return rR(t,e).normalized}function rR(t,e){let{parsed:r,malformedAuthorityOrPort:n}=tR(t,e);return{normalized:n?t:Nn(r,e),malformedAuthorityOrPort:n}}function Xk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=rR(t,e);return n?void 0:r}if(typeof t=="object")return Nn(t,e)}var Ef={SCHEMES:LH,normalize:FH,resolve:HH,resolveComponent:eR,equal:UH,serialize:Nn,parse:Bo};Au.exports=Ef;Au.exports.default=Ef;Au.exports.fastUri=Ef});var sR=k(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var oR=nR();oR.code='require("ajv/dist/runtime/uri").default';Cf.default=oR});var mR=k(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var BH=hi();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return BH.KeywordCxt}});var Vo=V();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var VH=Ru(),lR=gi(),KH=tf(),yi=Eu(),GH=V(),vi=pi(),Iu=di(),Af=te(),iR=Fk(),JH=sR(),dR=(t,e)=>new RegExp(t,e);dR.code="new RegExp";var YH=["removeAdditional","useDefaults","coerceTypes"],XH=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),QH={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},eU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},aR=200;function tU(t){var e,r,n,o,i,a,c,u,l,d,p,m,f,_,g,y,S,x,w,T,v,P,O,J,F;let ie=t.strict,mt=(e=t.code)===null||e===void 0?void 0:e.optimize,ft=mt===!0||mt===void 0?1:mt||0,Gr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:dR,Tt=(o=t.uriResolver)!==null&&o!==void 0?o:JH.default;return{strictSchema:(a=(i=t.strictSchema)!==null&&i!==void 0?i:ie)!==null&&a!==void 0?a:!0,strictNumbers:(u=(c=t.strictNumbers)!==null&&c!==void 0?c:ie)!==null&&u!==void 0?u:!0,strictTypes:(d=(l=t.strictTypes)!==null&&l!==void 0?l:ie)!==null&&d!==void 0?d:"log",strictTuples:(m=(p=t.strictTuples)!==null&&p!==void 0?p:ie)!==null&&m!==void 0?m:"log",strictRequired:(_=(f=t.strictRequired)!==null&&f!==void 0?f:ie)!==null&&_!==void 0?_:!1,code:t.code?{...t.code,optimize:ft,regExp:Gr}:{optimize:ft,regExp:Gr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:aR,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:aR,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(T=t.schemaId)!==null&&T!==void 0?T:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(J=t.unicodeRegExp)!==null&&J!==void 0?J:!0,int32range:(F=t.int32range)!==null&&F!==void 0?F:!0,uriResolver:Tt}}var bi=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...tU(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new GH.ValueScope({scope:{},prefixes:XH,es5:r,lines:n}),this.logger=aU(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,KH.getRules)(),cR.call(this,QH,e,"NOT SUPPORTED"),cR.call(this,eU,e,"DEPRECATED","warn"),this._metaOpts=sU.call(this),e.formats&&nU.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&oU.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),rU.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=iR;n==="id"&&(o={...iR},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,p){await i.call(this,d.$schema);let m=this._addSchema(d,p);return m.validate||a.call(this,m)}async function i(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function a(d){try{return this._compileSchemaEnv(d)}catch(p){if(!(p instanceof lR.default))throw p;return c.call(this,p),await u.call(this,p.missingSchema),a.call(this,d)}}function c({missingSchema:d,missingRef:p}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${p} cannot be resolved`)}async function u(d){let p=await l.call(this,d);this.refs[d]||await i.call(this,p.$schema),this.refs[d]||this.addSchema(p,d,r)}async function l(d){let p=this._loading[d];if(p)return p;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let a of e)this.addSchema(a,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:a}=this.opts;if(i=e[a],i!==void 0&&typeof i!="string")throw new Error(`schema ${a} must be string`)}return r=(0,vi.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let r;for(;typeof(r=uR.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new yi.SchemaEnv({schema:{},schemaId:n});if(r=yi.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=uR.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,vi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(uU.call(this,n,r),!r)return(0,Af.eachItem)(n,i=>Tf.call(this,i)),this;dU.call(this,r);let o={...r,type:(0,Iu.getJSONTypes)(r.type),schemaType:(0,Iu.getJSONTypes)(r.schemaType)};return(0,Af.eachItem)(n,o.type.length===0?i=>Tf.call(this,i,o):i=>o.type.forEach(a=>Tf.call(this,i,o,a))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let i=o.split("/").slice(1),a=e;for(let c of i)a=a[c];for(let c in n){let u=n[c];if(typeof u!="object")continue;let{$data:l}=u.definition,d=a[c];l&&d&&(a[c]=pR(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:c}=this.opts;if(typeof e=="object")a=e[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(u!==void 0)return u;n=(0,vi.normalizeId)(a||n);let l=vi.getSchemaRefs.call(this,e,n);return u=new yi.SchemaEnv({schema:e,schemaId:c,meta:r,baseId:n,localRefs:l}),this._cache.set(u.schema,u),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),o&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):yi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{yi.compileSchema.call(this,e)}finally{this.opts=r}}};bi.ValidationError=VH.default;bi.MissingRefError=lR.default;Le.default=bi;function cR(t,e,r,n="error"){for(let o in t){let i=o;i in e&&this.logger[n](`${r}: option ${o}. ${t[i]}`)}}function uR(t){return t=(0,vi.normalizeId)(t),this.schemas[t]||this.refs[t]}function rU(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function nU(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function oU(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function sU(){let t={...this.opts};for(let e of YH)delete t[e];return t}var iU={log(){},warn(){},error(){}};function aU(t){if(t===!1)return iU;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var cU=/^[a-z_$][a-z0-9_$:-]*$/i;function uU(t,e){let{RULES:r}=this;if((0,Af.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!cU.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Tf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,a=o?i.post:i.rules.find(({type:u})=>u===r);if(a||(a={type:r,rules:[]},i.rules.push(a)),i.keywords[t]=!0,!e)return;let c={keyword:t,definition:{...e,type:(0,Iu.getJSONTypes)(e.type),schemaType:(0,Iu.getJSONTypes)(e.schemaType)}};e.before?lU.call(this,a,c,e.before):a.rules.push(c),i.all[t]=c,(n=e.implements)===null||n===void 0||n.forEach(u=>this.addKeyword(u))}function lU(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function dU(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=pR(e)),t.validateSchema=this.compile(e,!0))}var pU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pR(t){return{anyOf:[t,pU]}}});var fR=k(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var mU={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};If.default=mU});var yR=k(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.callRef=jn.getValidate=void 0;var fU=gi(),hR=Pt(),it=V(),Ko=br(),gR=Eu(),$u=te(),hU={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:i,validateName:a,opts:c,self:u}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return p();let d=gR.resolveRef.call(u,l,o,r);if(d===void 0)throw new fU.default(n.opts.uriResolver,o,r);if(d instanceof gR.SchemaEnv)return m(d);return f(d);function p(){if(i===l)return zu(t,a,i,i.$async);let _=e.scopeValue("root",{ref:l});return zu(t,(0,it._)`${_}.validate`,l,l.$async)}function m(_){let g=_R(t,_);zu(t,g,_,_.$async)}function f(_){let g=e.scopeValue("schema",c.code.source===!0?{ref:_,code:(0,it.stringify)(_)}:{ref:_}),y=e.name("valid"),S=t.subschema({schema:_,dataTypes:[],schemaPath:it.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function _R(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,it._)`${r.scopeValue("wrapper",{ref:e})}.validate`}jn.getValidate=_R;function zu(t,e,r,n){let{gen:o,it:i}=t,{allErrors:a,schemaEnv:c,opts:u}=i,l=u.passContext?Ko.default.this:it.nil;n?d():p();function d(){if(!c.$async)throw new Error("async schema referenced by sync schema");let _=o.let("valid");o.try(()=>{o.code((0,it._)`await ${(0,hR.callValidateCode)(t,e,l)}`),f(e),a||o.assign(_,!0)},g=>{o.if((0,it._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),m(g),a||o.assign(_,!1)}),t.ok(_)}function p(){t.result((0,hR.callValidateCode)(t,e,l),()=>f(e),()=>m(e))}function m(_){let g=(0,it._)`${_}.errors`;o.assign(Ko.default.vErrors,(0,it._)`${Ko.default.vErrors} === null ? ${g} : ${Ko.default.vErrors}.concat(${g})`),o.assign(Ko.default.errors,(0,it._)`${Ko.default.vErrors}.length`)}function f(_){var g;if(!i.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(i.props=$u.mergeEvaluated.props(o,y.props,i.props));else{let S=o.var("props",(0,it._)`${_}.evaluated.props`);i.props=$u.mergeEvaluated.props(o,S,i.props,it.Name)}if(i.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(i.items=$u.mergeEvaluated.items(o,y.items,i.items));else{let S=o.var("items",(0,it._)`${_}.evaluated.items`);i.items=$u.mergeEvaluated.items(o,S,i.items,it.Name)}}}jn.callRef=zu;jn.default=hU});var vR=k($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var gU=fR(),_U=yR(),yU=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gU.default,_U.default];$f.default=yU});var bR=k(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var Ou=V(),Zr=Ou.operators,Du={maximum:{okStr:"<=",ok:Zr.LTE,fail:Zr.GT},minimum:{okStr:">=",ok:Zr.GTE,fail:Zr.LT},exclusiveMaximum:{okStr:"<",ok:Zr.LT,fail:Zr.GTE},exclusiveMinimum:{okStr:">",ok:Zr.GT,fail:Zr.LTE}},vU={message:({keyword:t,schemaCode:e})=>(0,Ou.str)`must be ${Du[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ou._)`{comparison: ${Du[t].okStr}, limit: ${e}}`},bU={keyword:Object.keys(Du),type:"number",schemaType:"number",$data:!0,error:vU,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ou._)`${r} ${Du[e].fail} ${n} || isNaN(${r})`)}};zf.default=bU});var SR=k(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var Si=V(),SU={message:({schemaCode:t})=>(0,Si.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Si._)`{multipleOf: ${t}}`},xU={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SU,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,i=o.opts.multipleOfPrecision,a=e.let("res"),c=i?(0,Si._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${i}`:(0,Si._)`${a} !== parseInt(${a})`;t.fail$data((0,Si._)`(${n} === 0 || (${a} = ${r}/${n}, ${c}))`)}};Of.default=xU});var wR=k(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});function xR(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Df.default=xR;xR.code='require("ajv/dist/runtime/ucs2length").default'});var kR=k(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Ln=V(),wU=te(),kU=wR(),RU={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ln.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ln._)`{limit: ${t}}`},PU={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:RU,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,i=e==="maxLength"?Ln.operators.GT:Ln.operators.LT,a=o.opts.unicode===!1?(0,Ln._)`${r}.length`:(0,Ln._)`${(0,wU.useFunc)(t.gen,kU.default)}(${r})`;t.fail$data((0,Ln._)`${a} ${i} ${n}`)}};Mf.default=PU});var RR=k(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var EU=Pt(),CU=te(),Go=V(),TU={message:({schemaCode:t})=>(0,Go.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Go._)`{pattern: ${t}}`},AU={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:TU,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:a}=t,c=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:u}=a.opts.code,l=u.code==="new RegExp"?(0,Go._)`new RegExp`:(0,CU.useFunc)(e,u),d=e.let("valid");e.try(()=>e.assign(d,(0,Go._)`${l}(${i}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Go._)`!${d}`)}else{let u=(0,EU.usePattern)(t,o);t.fail$data((0,Go._)`!${u}.test(${r})`)}}};Nf.default=AU});var PR=k(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var xi=V(),IU={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,xi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,xi._)`{limit: ${t}}`},$U={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:IU,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?xi.operators.GT:xi.operators.LT;t.fail$data((0,xi._)`Object.keys(${r}).length ${o} ${n}`)}};jf.default=$U});var ER=k(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var wi=Pt(),ki=V(),zU=te(),OU={message:({params:{missingProperty:t}})=>(0,ki.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ki._)`{missingProperty: ${t}}`},DU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:OU,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:i,it:a}=t,{opts:c}=a;if(!i&&r.length===0)return;let u=r.length>=c.loopRequired;if(a.allErrors?l():d(),c.strictRequired){let f=t.parentSchema.properties,{definedProperties:_}=t.it;for(let g of r)if(f?.[g]===void 0&&!_.has(g)){let y=a.schemaEnv.baseId+a.errSchemaPath,S=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,zU.checkStrictMode)(a,S,a.opts.strictRequired)}}function l(){if(u||i)t.block$data(ki.nil,p);else for(let f of r)(0,wi.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(u||i){let _=e.let("valid",!0);t.block$data(_,()=>m(f,_)),t.ok(_)}else e.if((0,wi.checkMissingProp)(t,r,f)),(0,wi.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,wi.noPropertyInData)(e,o,f,c.ownProperties),()=>t.error())})}function m(f,_){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(_,(0,wi.propertyInData)(e,o,f,c.ownProperties)),e.if((0,ki.not)(_),()=>{t.error(),e.break()})},ki.nil)}}};Lf.default=DU});var CR=k(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Ri=V(),MU={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ri.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ri._)`{limit: ${t}}`},NU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:MU,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ri.operators.GT:Ri.operators.LT;t.fail$data((0,Ri._)`${r}.length ${o} ${n}`)}};Ff.default=NU});var Mu=k(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var TR=lf();TR.code='require("ajv/dist/runtime/equal").default';Hf.default=TR});var AR=k(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Uf=di(),Fe=V(),jU=te(),LU=Mu(),FU={message:({params:{i:t,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Fe._)`{i: ${t}, j: ${e}}`},HU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FU,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:i,schemaCode:a,it:c}=t;if(!n&&!o)return;let u=e.let("valid"),l=i.items?(0,Uf.getSchemaTypes)(i.items):[];t.block$data(u,d,(0,Fe._)`${a} === false`),t.ok(u);function d(){let _=e.let("i",(0,Fe._)`${r}.length`),g=e.let("j");t.setParams({i:_,j:g}),e.assign(u,!0),e.if((0,Fe._)`${_} > 1`,()=>(p()?m:f)(_,g))}function p(){return l.length>0&&!l.some(_=>_==="object"||_==="array")}function m(_,g){let y=e.name("item"),S=(0,Uf.checkDataTypes)(l,y,c.opts.strictNumbers,Uf.DataType.Wrong),x=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${_}--;`,()=>{e.let(y,(0,Fe._)`${r}[${_}]`),e.if(S,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${x}[${y}] == "number"`,()=>{e.assign(g,(0,Fe._)`${x}[${y}]`),t.error(),e.assign(u,!1).break()}).code((0,Fe._)`${x}[${y}] = ${_}`)})}function f(_,g){let y=(0,jU.useFunc)(e,LU.default),S=e.name("outer");e.label(S).for((0,Fe._)`;${_}--;`,()=>e.for((0,Fe._)`${g} = ${_}; ${g}--;`,()=>e.if((0,Fe._)`${y}(${r}[${_}], ${r}[${g}])`,()=>{t.error(),e.assign(u,!1).break(S)})))}}};qf.default=HU});var IR=k(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Wf=V(),UU=te(),qU=Mu(),WU={message:"must be equal to constant",params:({schemaCode:t})=>(0,Wf._)`{allowedValue: ${t}}`},ZU={keyword:"const",$data:!0,error:WU,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,Wf._)`!${(0,UU.useFunc)(e,qU.default)}(${r}, ${o})`):t.fail((0,Wf._)`${i} !== ${r}`)}};Zf.default=ZU});var $R=k(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Pi=V(),BU=te(),VU=Mu(),KU={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Pi._)`{allowedValues: ${t}}`},GU={keyword:"enum",schemaType:"array",$data:!0,error:KU,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:a}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let c=o.length>=a.opts.loopEnum,u,l=()=>u??(u=(0,BU.useFunc)(e,VU.default)),d;if(c||n)d=e.let("valid"),t.block$data(d,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",i);d=(0,Pi.or)(...o.map((_,g)=>m(f,g)))}t.pass(d);function p(){e.assign(d,!1),e.forOf("v",i,f=>e.if((0,Pi._)`${l()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,_){let g=o[_];return typeof g=="object"&&g!==null?(0,Pi._)`${l()}(${r}, ${f}[${_}])`:(0,Pi._)`${r} === ${g}`}}};Bf.default=GU});var zR=k(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var JU=bR(),YU=SR(),XU=kR(),QU=RR(),eq=PR(),tq=ER(),rq=CR(),nq=AR(),oq=IR(),sq=$R(),iq=[JU.default,YU.default,XU.default,QU.default,eq.default,tq.default,rq.default,nq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oq.default,sq.default];Vf.default=iq});var Gf=k(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.validateAdditionalItems=void 0;var Fn=V(),Kf=te(),aq={message:({params:{len:t}})=>(0,Fn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Fn._)`{limit: ${t}}`},cq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:aq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Kf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}OR(t,n)}};function OR(t,e){let{gen:r,schema:n,data:o,keyword:i,it:a}=t;a.items=!0;let c=r.const("len",(0,Fn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Fn._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Kf.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,Fn._)`${c} <= ${e.length}`);r.if((0,Fn.not)(l),()=>u(l)),t.ok(l)}function u(l){r.forRange("i",e.length,c,d=>{t.subschema({keyword:i,dataProp:d,dataPropType:Kf.Type.Num},l),a.allErrors||r.if((0,Fn.not)(l),()=>r.break())})}}Ei.validateAdditionalItems=OR;Ei.default=cq});var Jf=k(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.validateTuple=void 0;var DR=V(),Nu=te(),uq=Pt(),lq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return MR(t,"additionalItems",e);r.items=!0,!(0,Nu.alwaysValidSchema)(r,e)&&t.ok((0,uq.validateArray)(t))}};function MR(t,e,r=t.schema){let{gen:n,parentSchema:o,data:i,keyword:a,it:c}=t;d(o),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Nu.mergeEvaluated.items(n,r.length,c.items));let u=n.name("valid"),l=n.const("len",(0,DR._)`${i}.length`);r.forEach((p,m)=>{(0,Nu.alwaysValidSchema)(c,p)||(n.if((0,DR._)`${l} > ${m}`,()=>t.subschema({keyword:a,schemaProp:m,dataProp:m},u)),t.ok(u))});function d(p){let{opts:m,errSchemaPath:f}=c,_=r.length,g=_===p.minItems&&(_===p.maxItems||p[e]===!1);if(m.strictTuples&&!g){let y=`"${a}" is ${_}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Nu.checkStrictMode)(c,y,m.strictTuples)}}}Ci.validateTuple=MR;Ci.default=lq});var NR=k(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var dq=Jf(),pq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,dq.validateTuple)(t,"items")};Yf.default=pq});var LR=k(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var jR=V(),mq=te(),fq=Pt(),hq=Gf(),gq={message:({params:{len:t}})=>(0,jR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,jR._)`{limit: ${t}}`},_q={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gq,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,mq.alwaysValidSchema)(n,e)&&(o?(0,hq.validateAdditionalItems)(t,o):t.ok((0,fq.validateArray)(t)))}};Xf.default=_q});var FR=k(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Ct=V(),ju=te(),yq={message:({params:{min:t,max:e}})=>e===void 0?(0,Ct.str)`must contain at least ${t} valid item(s)`:(0,Ct.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ct._)`{minContains: ${t}}`:(0,Ct._)`{minContains: ${t}, maxContains: ${e}}`},vq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:yq,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t,a,c,{minContains:u,maxContains:l}=n;i.opts.next?(a=u===void 0?1:u,c=l):a=1;let d=e.const("len",(0,Ct._)`${o}.length`);if(t.setParams({min:a,max:c}),c===void 0&&a===0){(0,ju.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&a>c){(0,ju.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ju.alwaysValidSchema)(i,r)){let g=(0,Ct._)`${d} >= ${a}`;c!==void 0&&(g=(0,Ct._)`${g} && ${d} <= ${c}`),t.pass(g);return}i.items=!0;let p=e.name("valid");c===void 0&&a===1?f(p,()=>e.if(p,()=>e.break())):a===0?(e.let(p,!0),c!==void 0&&e.if((0,Ct._)`${o}.length > 0`,m)):(e.let(p,!1),m()),t.result(p,()=>t.reset());function m(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>_(y)))}function f(g,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:ju.Type.Num,compositeRule:!0},g),y()})}function _(g){e.code((0,Ct._)`${g}++`),c===void 0?e.if((0,Ct._)`${g} >= ${a}`,()=>e.assign(p,!0).break()):(e.if((0,Ct._)`${g} > ${c}`,()=>e.assign(p,!1).break()),a===1?e.assign(p,!0):e.if((0,Ct._)`${g} >= ${a}`,()=>e.assign(p,!0)))}}};Qf.default=vq});var qR=k(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.validateSchemaDeps=rr.validatePropertyDeps=rr.error=void 0;var eh=V(),bq=te(),Ti=Pt();rr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,eh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,eh._)`{property: ${t},
14
14
  missingProperty: ${n},
15
15
  depsCount: ${e},
16
- deps: ${r}}`};var HU={keyword:"dependencies",type:"object",schemaType:"object",error:tr.error,code(t){let[e,r]=UU(t);TR(t,e),AR(t,r)}};function UU({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function TR(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let a in e){let c=e[a];if(c.length===0)continue;let u=(0,Ci.propertyInData)(r,n,a,o.opts.ownProperties);t.setParams({property:a,depsCount:c.length,deps:c.join(", ")}),o.allErrors?r.if(u,()=>{for(let l of c)(0,Ci.checkReportMissingProp)(t,l)}):(r.if((0,Kf._)`${u} && (${(0,Ci.checkMissingProp)(t,c,i)})`),(0,Ci.reportMissingProp)(t,i),r.else())}}tr.validatePropertyDeps=TR;function AR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:i}=t,a=r.name("valid");for(let c in e)(0,FU.alwaysValidSchema)(i,e[c])||(r.if((0,Ci.propertyInData)(r,n,c,i.opts.ownProperties),()=>{let u=t.subschema({keyword:o,schemaProp:c},a);t.mergeValidEvaluated(u,a)},()=>r.var(a,!0)),t.ok(a))}tr.validateSchemaDeps=AR;tr.default=HU});var zR=k(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var $R=V(),qU=te(),WU={message:"property name must be valid",params:({params:t})=>(0,$R._)`{propertyName: ${t.propertyName}}`},ZU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:WU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,qU.alwaysValidSchema)(o,r))return;let i=e.name("valid");e.forIn("key",n,a=>{t.setParams({propertyName:a}),t.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},i),e.if((0,$R.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Gf.default=ZU});var Yf=k(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Du=Rt(),Ht=V(),BU=vr(),Mu=te(),VU={message:"must NOT have additional properties",params:({params:t})=>(0,Ht._)`{additionalProperty: ${t.additionalProperty}}`},KU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:VU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:i,it:a}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:u}=a;if(a.props=!0,u.removeAdditional!=="all"&&(0,Mu.alwaysValidSchema)(a,r))return;let l=(0,Du.allSchemaProperties)(n.properties),d=(0,Du.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Ht._)`${i} === ${BU.default.errors}`);function p(){e.forIn("key",o,y=>{!l.length&&!d.length?_(y):e.if(m(y),()=>_(y))})}function m(y){let S;if(l.length>8){let x=(0,Mu.schemaRefOrVal)(a,n.properties,"properties");S=(0,Du.isOwnProperty)(e,x,y)}else l.length?S=(0,Ht.or)(...l.map(x=>(0,Ht._)`${y} === ${x}`)):S=Ht.nil;return d.length&&(S=(0,Ht.or)(S,...d.map(x=>(0,Ht._)`${(0,Du.usePattern)(t,x)}.test(${y})`))),(0,Ht.not)(S)}function f(y){e.code((0,Ht._)`delete ${o}[${y}]`)}function _(y){if(u.removeAdditional==="all"||u.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,Mu.alwaysValidSchema)(a,r)){let S=e.name("valid");u.removeAdditional==="failing"?(g(y,S,!1),e.if((0,Ht.not)(S),()=>{t.reset(),f(y)})):(g(y,S),c||e.if((0,Ht.not)(S),()=>e.break()))}}function g(y,S,x){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Mu.Type.Str};x===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,S)}}};Jf.default=KU});var MR=k(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var GU=fi(),OR=Rt(),Xf=te(),DR=Yf(),JU={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&DR.default.code(new GU.KeywordCxt(i,DR.default,"additionalProperties"));let a=(0,OR.allSchemaProperties)(r);for(let p of a)i.definedProperties.add(p);i.opts.unevaluated&&a.length&&i.props!==!0&&(i.props=Xf.mergeEvaluated.props(e,(0,Xf.toHash)(a),i.props));let c=a.filter(p=>!(0,Xf.alwaysValidSchema)(i,r[p]));if(c.length===0)return;let u=e.name("valid");for(let p of c)l(p)?d(p):(e.if((0,OR.propertyInData)(e,o,p,i.opts.ownProperties)),d(p),i.allErrors||e.else().var(u,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(u);function l(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function d(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},u)}}};Qf.default=JU});var FR=k(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var NR=Rt(),Nu=V(),jR=te(),LR=te(),YU={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:i}=t,{opts:a}=i,c=(0,NR.allSchemaProperties)(r),u=c.filter(g=>(0,jR.alwaysValidSchema)(i,r[g]));if(c.length===0||u.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let l=a.strictSchema&&!a.allowMatchingProperties&&o.properties,d=e.name("valid");i.props!==!0&&!(i.props instanceof Nu.Name)&&(i.props=(0,LR.evaluatedPropsToName)(e,i.props));let{props:p}=i;m();function m(){for(let g of c)l&&f(g),i.allErrors?_(g):(e.var(d,!0),_(g),e.if(d))}function f(g){for(let y in l)new RegExp(g).test(y)&&(0,jR.checkStrictMode)(i,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function _(g){e.forIn("key",n,y=>{e.if((0,Nu._)`${(0,NR.usePattern)(t,g)}.test(${y})`,()=>{let S=u.includes(g);S||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:LR.Type.Str},d),i.opts.unevaluated&&p!==!0?e.assign((0,Nu._)`${p}[${y}]`,!0):!S&&!i.allErrors&&e.if((0,Nu.not)(d),()=>e.break())})})}}};eh.default=YU});var HR=k(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var XU=te(),QU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,XU.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};th.default=QU});var UR=k(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var eq=Rt(),tq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eq.validateUnion,error:{message:"must match a schema in anyOf"}};rh.default=tq});var qR=k(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var ju=V(),rq=te(),nq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ju._)`{passingSchemas: ${t.passing}}`},oq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nq,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,a=e.let("valid",!1),c=e.let("passing",null),u=e.name("_valid");t.setParams({passing:c}),e.block(l),t.result(a,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((d,p)=>{let m;(0,rq.alwaysValidSchema)(o,d)?e.var(u,!0):m=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},u),p>0&&e.if((0,ju._)`${u} && ${a}`).assign(a,!1).assign(c,(0,ju._)`[${c}, ${p}]`).else(),e.if(u,()=>{e.assign(a,!0),e.assign(c,p),m&&t.mergeEvaluated(m,ju.Name)})})}}};nh.default=oq});var WR=k(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var sq=te(),iq={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((i,a)=>{if((0,sq.alwaysValidSchema)(n,i))return;let c=t.subschema({keyword:"allOf",schemaProp:a},o);t.ok(o),t.mergeEvaluated(c)})}};oh.default=iq});var VR=k(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Lu=V(),BR=te(),aq={message:({params:t})=>(0,Lu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lu._)`{failingKeyword: ${t.ifClause}}`},cq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aq,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,BR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ZR(n,"then"),i=ZR(n,"else");if(!o&&!i)return;let a=e.let("valid",!0),c=e.name("_valid");if(u(),t.reset(),o&&i){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(c,l("then",d),l("else",d))}else o?e.if(c,l("then")):e.if((0,Lu.not)(c),l("else"));t.pass(a,()=>t.error(!0));function u(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);t.mergeEvaluated(d)}function l(d,p){return()=>{let m=t.subschema({keyword:d},c);e.assign(a,c),t.mergeValidEvaluated(m,a),p?e.assign(p,(0,Lu._)`${d}`):t.setParams({ifClause:d})}}}};function ZR(t,e){let r=t.schema[e];return r!==void 0&&!(0,BR.alwaysValidSchema)(t,r)}sh.default=cq});var KR=k(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var uq=te(),lq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,uq.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ih.default=lq});var GR=k(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var dq=qf(),pq=RR(),mq=Wf(),fq=ER(),hq=CR(),gq=IR(),_q=zR(),yq=Yf(),vq=MR(),bq=FR(),Sq=HR(),xq=UR(),wq=qR(),kq=WR(),Rq=VR(),Pq=KR();function Eq(t=!1){let e=[Sq.default,xq.default,wq.default,kq.default,Rq.default,Pq.default,_q.default,yq.default,gq.default,vq.default,bq.default];return t?e.push(pq.default,fq.default):e.push(dq.default,mq.default),e.push(hq.default),e}ah.default=Eq});var JR=k(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Ee=V(),Cq={message:({schemaCode:t})=>(0,Ee.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ee._)`{format: ${t}}`},Tq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Cq,code(t,e){let{gen:r,data:n,$data:o,schema:i,schemaCode:a,it:c}=t,{opts:u,errSchemaPath:l,schemaEnv:d,self:p}=c;if(!u.validateFormats)return;o?m():f();function m(){let _=r.scopeValue("formats",{ref:p.formats,code:u.code.formats}),g=r.const("fDef",(0,Ee._)`${_}[${a}]`),y=r.let("fType"),S=r.let("format");r.if((0,Ee._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,Ee._)`${g}.type || "string"`).assign(S,(0,Ee._)`${g}.validate`),()=>r.assign(y,(0,Ee._)`"string"`).assign(S,g)),t.fail$data((0,Ee.or)(x(),w()));function x(){return u.strictSchema===!1?Ee.nil:(0,Ee._)`${a} && !${S}`}function w(){let T=d.$async?(0,Ee._)`(${g}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,Ee._)`${S}(${n})`,v=(0,Ee._)`(typeof ${S} == "function" ? ${T} : ${S}.test(${n}))`;return(0,Ee._)`${S} && ${S} !== true && ${y} === ${e} && !${v}`}}function f(){let _=p.formats[i];if(!_){x();return}if(_===!0)return;let[g,y,S]=w(_);g===e&&t.pass(T());function x(){if(u.strictSchema===!1){p.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,Ee.regexpCode)(v):u.code.formats?(0,Ee._)`${u.code.formats}${(0,Ee.getProperty)(i)}`:void 0,O=r.scopeValue("formats",{key:i,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ee._)`${O}.validate`]:["string",v,O]}function T(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ee._)`await ${S}(${n})`}return typeof y=="function"?(0,Ee._)`${S}(${n})`:(0,Ee._)`${S}.test(${n})`}}}};ch.default=Tq});var YR=k(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var Aq=JR(),Iq=[Aq.default];uh.default=Iq});var XR=k(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.contentVocabulary=Go.metadataVocabulary=void 0;Go.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Go.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var eP=k(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var $q=aR(),zq=SR(),Oq=GR(),Dq=YR(),QR=XR(),Mq=[$q.default,zq.default,(0,Oq.default)(),Dq.default,QR.metadataVocabulary,QR.contentVocabulary];lh.default=Mq});var rP=k(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.DiscrError=void 0;var tP;(function(t){t.Tag="tag",t.Mapping="mapping"})(tP||(Fu.DiscrError=tP={}))});var oP=k(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var Jo=V(),dh=rP(),nP=wu(),Nq=hi(),jq=te(),Lq={message:({params:{discrError:t,tagName:e}})=>t===dh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Jo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Fq={keyword:"discriminator",type:"object",schemaType:"object",error:Lq,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:i}=t,{oneOf:a}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",!1),l=e.const("tag",(0,Jo._)`${r}${(0,Jo.getProperty)(c)}`);e.if((0,Jo._)`typeof ${l} == "string"`,()=>d(),()=>t.error(!1,{discrError:dh.DiscrError.Tag,tag:l,tagName:c})),t.ok(u);function d(){let f=m();e.if(!1);for(let _ in f)e.elseIf((0,Jo._)`${l} === ${_}`),e.assign(u,p(f[_]));e.else(),t.error(!1,{discrError:dh.DiscrError.Mapping,tag:l,tagName:c}),e.endIf()}function p(f){let _=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},_);return t.mergeEvaluated(g,Jo.Name),_}function m(){var f;let _={},g=S(o),y=!0;for(let T=0;T<a.length;T++){let v=a[T];if(v?.$ref&&!(0,jq.schemaHasRulesButRef)(v,i.self.RULES)){let O=v.$ref;if(v=nP.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,O),v instanceof nP.SchemaEnv&&(v=v.schema),v===void 0)throw new Nq.default(i.opts.uriResolver,i.baseId,O)}let P=(f=v?.properties)===null||f===void 0?void 0:f[c];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);y=y&&(g||S(v)),x(P,T)}if(!y)throw new Error(`discriminator: "${c}" must be required`);return _;function S({required:T}){return Array.isArray(T)&&T.includes(c)}function x(T,v){if(T.const)w(T.const,v);else if(T.enum)for(let P of T.enum)w(P,v);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function w(T,v){if(typeof T!="string"||T in _)throw new Error(`discriminator: "${c}" values must be unique strings`);_[T]=v}}}};ph.default=Fq});var sP=k((wte,Hq)=>{Hq.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var fh=k((ve,mh)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var Uq=tR(),qq=eP(),Wq=oP(),iP=sP(),Zq=["/properties"],Hu="http://json-schema.org/draft-07/schema",Yo=class extends Uq.default{_addVocabularies(){super._addVocabularies(),qq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Wq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(iP,Zq):iP;this.addMetaSchema(e,Hu,!1),this.refs["http://json-schema.org/schema"]=Hu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hu)?Hu:void 0)}};ve.Ajv=Yo;mh.exports=ve=Yo;mh.exports.Ajv=Yo;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=Yo;var Bq=fi();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return Bq.KeywordCxt}});var Xo=V();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return Xo._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return Xo.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return Xo.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return Xo.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return Xo.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return Xo.CodeGen}});var Vq=Su();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return Vq.default}});var Kq=hi();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return Kq.default}})});var fP=k(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.formatNames=nr.fastFormats=nr.fullFormats=void 0;function rr(t,e){return{validate:t,compare:e}}nr.fullFormats={date:rr(lP,yh),time:rr(gh(!0),vh),"date-time":rr(aP(!0),pP),"iso-time":rr(gh(),dP),"iso-date-time":rr(aP(),mP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:eW,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:aW,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:tW,int32:{type:"number",validate:oW},int64:{type:"number",validate:sW},float:{type:"number",validate:uP},double:{type:"number",validate:uP},password:!0,binary:!0};nr.fastFormats={...nr.fullFormats,date:rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yh),time:rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,vh),"date-time":rr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pP),"iso-time":rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,dP),"iso-date-time":rr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mP),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};nr.formatNames=Object.keys(nr.fullFormats);function Gq(t){return t%4===0&&(t%100!==0||t%400===0)}var Jq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Yq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function lP(t){let e=Jq.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Gq(r)?29:Yq[n])}function yh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var hh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gh(t){return function(r){let n=hh.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],a=+n[3],c=n[4],u=n[5]==="-"?-1:1,l=+(n[6]||0),d=+(n[7]||0);if(l>23||d>59||t&&!c)return!1;if(o<=23&&i<=59&&a<60)return!0;let p=i-d*u,m=o-l*u-(p<0?1:0);return(m===23||m===-1)&&(p===59||p===-1)&&a<61}}function vh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function dP(t,e){if(!(t&&e))return;let r=hh.exec(t),n=hh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var _h=/t|\s/i;function aP(t){let e=gh(t);return function(n){let o=n.split(_h);return o.length===2&&lP(o[0])&&e(o[1])}}function pP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function mP(t,e){if(!(t&&e))return;let[r,n]=t.split(_h),[o,i]=e.split(_h),a=yh(r,o);if(a!==void 0)return a||vh(n,i)}var Xq=/\/|:/,Qq=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function eW(t){return Xq.test(t)&&Qq.test(t)}var cP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function tW(t){return cP.lastIndex=0,cP.test(t)}var rW=-(2**31),nW=2**31-1;function oW(t){return Number.isInteger(t)&&t<=nW&&t>=rW}function sW(t){return Number.isInteger(t)}function uP(){return!0}var iW=/[^\\]\\Z/;function aW(t){if(iW.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var hP=k(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.formatLimitDefinition=void 0;var cW=fh(),Ut=V(),Zr=Ut.operators,Uu={formatMaximum:{okStr:"<=",ok:Zr.LTE,fail:Zr.GT},formatMinimum:{okStr:">=",ok:Zr.GTE,fail:Zr.LT},formatExclusiveMaximum:{okStr:"<",ok:Zr.LT,fail:Zr.GTE},formatExclusiveMinimum:{okStr:">",ok:Zr.GT,fail:Zr.LTE}},uW={message:({keyword:t,schemaCode:e})=>(0,Ut.str)`should be ${Uu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ut._)`{comparison: ${Uu[t].okStr}, limit: ${e}}`};Qo.formatLimitDefinition={keyword:Object.keys(Uu),type:"string",schemaType:"string",$data:!0,error:uW,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:i}=t,{opts:a,self:c}=i;if(!a.validateFormats)return;let u=new cW.KeywordCxt(i,c.RULES.all.format.definition,"format");u.$data?l():d();function l(){let m=e.scopeValue("formats",{ref:c.formats,code:a.code.formats}),f=e.const("fmt",(0,Ut._)`${m}[${u.schemaCode}]`);t.fail$data((0,Ut.or)((0,Ut._)`typeof ${f} != "object"`,(0,Ut._)`${f} instanceof RegExp`,(0,Ut._)`typeof ${f}.compare != "function"`,p(f)))}function d(){let m=u.schema,f=c.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let _=e.scopeValue("formats",{key:m,ref:f,code:a.code.formats?(0,Ut._)`${a.code.formats}${(0,Ut.getProperty)(m)}`:void 0});t.fail$data(p(_))}function p(m){return(0,Ut._)`${m}.compare(${r}, ${n}) ${Uu[o].fail} 0`}},dependencies:["format"]};var lW=t=>(t.addKeyword(Qo.formatLimitDefinition),t);Qo.default=lW});var vP=k((Ti,yP)=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var es=fP(),dW=hP(),bh=V(),gP=new bh.Name("fullFormats"),pW=new bh.Name("fastFormats"),Sh=(t,e={keywords:!0})=>{if(Array.isArray(e))return _P(t,e,es.fullFormats,gP),t;let[r,n]=e.mode==="fast"?[es.fastFormats,pW]:[es.fullFormats,gP],o=e.formats||es.formatNames;return _P(t,o,r,n),e.keywords&&(0,dW.default)(t),t};Sh.get=(t,e="full")=>{let n=(e==="fast"?es.fastFormats:es.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function _P(t,e,r,n){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,bh._)`require("ajv-formats/dist/formats").${n}`);for(let a of e)t.addFormat(a,r[a])}yP.exports=Ti=Sh;Object.defineProperty(Ti,"__esModule",{value:!0});Ti.default=Sh});var CP=k((Nte,EP)=>{EP.exports=PP;PP.sync=gW;var kP=ue("fs");function hW(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&t.substr(-o.length).toLowerCase()===o)return!0}return!1}function RP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:hW(e,r)}function PP(t,e,r){kP.stat(t,function(n,o){r(n,n?!1:RP(o,t,e))})}function gW(t,e){return RP(kP.statSync(t),t,e)}});var zP=k((jte,$P)=>{$P.exports=AP;AP.sync=_W;var TP=ue("fs");function AP(t,e,r){TP.stat(t,function(n,o){r(n,n?!1:IP(o,e))})}function _W(t,e){return IP(TP.statSync(t),e)}function IP(t,e){return t.isFile()&&yW(t,e)}function yW(t,e){var r=t.mode,n=t.uid,o=t.gid,i=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),a=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),c=parseInt("100",8),u=parseInt("010",8),l=parseInt("001",8),d=c|u,p=r&l||r&u&&o===a||r&c&&n===i||r&d&&i===0;return p}});var DP=k((Fte,OP)=>{var Lte=ue("fs"),Vu;process.platform==="win32"||global.TESTING_WINDOWS?Vu=CP():Vu=zP();OP.exports=xh;xh.sync=vW;function xh(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){xh(t,e||{},function(i,a){i?o(i):n(a)})})}Vu(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function vW(t,e){try{return Vu.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var UP=k((Hte,HP)=>{var ts=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",MP=ue("path"),bW=ts?";":":",NP=DP(),jP=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),LP=(t,e)=>{let r=e.colon||bW,n=t.match(/\//)||ts&&t.match(/\\/)?[""]:[...ts?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=ts?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=ts?o.split(r):[""];return ts&&t.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},FP=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:i}=LP(t,e),a=[],c=l=>new Promise((d,p)=>{if(l===n.length)return e.all&&a.length?d(a):p(jP(t));let m=n[l],f=/^".*"$/.test(m)?m.slice(1,-1):m,_=MP.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+_:_;d(u(g,l,0))}),u=(l,d,p)=>new Promise((m,f)=>{if(p===o.length)return m(c(d+1));let _=o[p];NP(l+_,{pathExt:i},(g,y)=>{if(!g&&y)if(e.all)a.push(l+_);else return m(l+_);return m(u(l,d,p+1))})});return r?c(0).then(l=>r(null,l),r):c(0)},SW=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=LP(t,e),i=[];for(let a=0;a<r.length;a++){let c=r[a],u=/^".*"$/.test(c)?c.slice(1,-1):c,l=MP.join(u,t),d=!u&&/^\.[\\\/]/.test(t)?t.slice(0,2)+l:l;for(let p=0;p<n.length;p++){let m=d+n[p];try{if(NP.sync(m,{pathExt:o}))if(e.all)i.push(m);else return m}catch{}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw jP(t)};HP.exports=FP;FP.sync=SW});var WP=k((Ute,wh)=>{"use strict";var qP=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};wh.exports=qP;wh.exports.default=qP});var KP=k((qte,VP)=>{"use strict";var ZP=ue("path"),xW=UP(),wW=WP();function BP(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(t.options.cwd)}catch{}let a;try{a=xW.sync(t.command,{path:r[wW({env:r})],pathExt:e?ZP.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return a&&(a=ZP.resolve(o?t.options.cwd:"",a)),a}function kW(t){return BP(t)||BP(t,!0)}VP.exports=kW});var GP=k((Wte,Rh)=>{"use strict";var kh=/([()\][%!^"`<>&|;, *?])/g;function RW(t){return t=t.replace(kh,"^$1"),t}function PW(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(kh,"^$1"),e&&(t=t.replace(kh,"^$1")),t}Rh.exports.command=RW;Rh.exports.argument=PW});var YP=k((Zte,JP)=>{"use strict";JP.exports=/^#!(.*)/});var QP=k((Bte,XP)=>{"use strict";var EW=YP();XP.exports=(t="")=>{let e=t.match(EW);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var tE=k((Vte,eE)=>{"use strict";var Ph=ue("fs"),CW=QP();function TW(t){let r=Buffer.alloc(150),n;try{n=Ph.openSync(t,"r"),Ph.readSync(n,r,0,150,0),Ph.closeSync(n)}catch{}return CW(r.toString())}eE.exports=TW});var sE=k((Kte,oE)=>{"use strict";var AW=ue("path"),rE=KP(),nE=GP(),IW=tE(),$W=process.platform==="win32",zW=/\.(?:com|exe)$/i,OW=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function DW(t){t.file=rE(t);let e=t.file&&IW(t.file);return e?(t.args.unshift(t.file),t.command=e,rE(t)):t.file}function MW(t){if(!$W)return t;let e=DW(t),r=!zW.test(e);if(t.options.forceShell||r){let n=OW.test(e);t.command=AW.normalize(t.command),t.command=nE.command(t.command),t.args=t.args.map(i=>nE.argument(i,n));let o=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${o}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function NW(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:MW(n)}oE.exports=NW});var cE=k((Gte,aE)=>{"use strict";var Eh=process.platform==="win32";function Ch(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function jW(t,e){if(!Eh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let i=iE(o,e);if(i)return r.call(t,"error",i)}return r.apply(t,arguments)}}function iE(t,e){return Eh&&t===1&&!e.file?Ch(e.original,"spawn"):null}function LW(t,e){return Eh&&t===1&&!e.file?Ch(e.original,"spawnSync"):null}aE.exports={hookChildProcess:jW,verifyENOENT:iE,verifyENOENTSync:LW,notFoundError:Ch}});var dE=k((Jte,rs)=>{"use strict";var uE=ue("child_process"),Th=sE(),Ah=cE();function lE(t,e,r){let n=Th(t,e,r),o=uE.spawn(n.command,n.args,n.options);return Ah.hookChildProcess(o,n),o}function FW(t,e,r){let n=Th(t,e,r),o=uE.spawnSync(n.command,n.args,n.options);return o.error=o.error||Ah.verifyENOENTSync(o.status,n),o}rs.exports=lE;rs.exports.spawn=lE;rs.exports.sync=FW;rs.exports._parse=Th;rs.exports._enoent=Ah});import{existsSync as dg,mkdirSync as $0,readFileSync as z0,unlinkSync as O0,writeFileSync as D0}from"node:fs";import{dirname as M0}from"node:path";function pg(t){if($0(M0(t),{recursive:!0}),dg(t)){let e=fg(t),r=e?Number.parseInt(e.trim(),10):NaN;if(Number.isInteger(r)&&r>0&&N0(r))return{status:"conflict",conflictingPid:r}}return D0(t,`${process.pid}
17
- `,{mode:384}),{status:"wrote"}}function Qi(t){if(!dg(t))return;let e=fg(t);if((e?Number.parseInt(e.trim(),10):NaN)===process.pid)try{O0(t)}catch{}}function mg(t,e){let r=!1,n=o=>{if(r){t.warn({signal:o},"shutdown already in progress; ignoring signal");return}r=!0,t.info({signal:o},"received shutdown signal"),Promise.resolve(e(`signal:${o}`)).catch(i=>{t.error({err:i.message},"shutdown handler threw")}).finally(()=>{setImmediate(()=>process.exit(0))})};process.on("SIGINT",n),process.on("SIGTERM",n)}function fg(t){try{return z0(t,"utf8")}catch{return null}}function N0(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}import{readFileSync as K2}from"node:fs";import{dirname as o0,join as G2}from"node:path";import{homedir as J2}from"node:os";var s={};Xi(s,{BRAND:()=>uC,DIRTY:()=>Gr,EMPTY_PATH:()=>H0,INVALID:()=>L,NEVER:()=>VC,OK:()=>Ue,ParseStatus:()=>Oe,Schema:()=>B,ZodAny:()=>Pr,ZodArray:()=>cr,ZodBigInt:()=>Yr,ZodBoolean:()=>Xr,ZodBranded:()=>fs,ZodCatch:()=>ln,ZodDate:()=>Qr,ZodDefault:()=>un,ZodDiscriminatedUnion:()=>ra,ZodEffects:()=>gt,ZodEnum:()=>an,ZodError:()=>Qe,ZodFirstPartyTypeKind:()=>H,ZodFunction:()=>oa,ZodIntersection:()=>nn,ZodIssueCode:()=>R,ZodLazy:()=>on,ZodLiteral:()=>sn,ZodMap:()=>Qn,ZodNaN:()=>to,ZodNativeEnum:()=>cn,ZodNever:()=>At,ZodNull:()=>tn,ZodNullable:()=>Bt,ZodNumber:()=>Jr,ZodObject:()=>et,ZodOptional:()=>ft,ZodParsedType:()=>$,ZodPipeline:()=>hs,ZodPromise:()=>Er,ZodReadonly:()=>dn,ZodRecord:()=>na,ZodSchema:()=>B,ZodSet:()=>eo,ZodString:()=>Rr,ZodSymbol:()=>Yn,ZodTransformer:()=>gt,ZodTuple:()=>Zt,ZodType:()=>B,ZodUndefined:()=>en,ZodUnion:()=>rn,ZodUnknown:()=>ar,ZodVoid:()=>Xn,addIssueToContext:()=>I,any:()=>yC,array:()=>xC,bigint:()=>mC,boolean:()=>Rg,coerce:()=>BC,custom:()=>xg,date:()=>fC,datetimeRegex:()=>bg,defaultErrorMap:()=>sr,discriminatedUnion:()=>PC,effect:()=>jC,enum:()=>DC,function:()=>$C,getErrorMap:()=>Kn,getParsedType:()=>Wt,instanceof:()=>dC,intersection:()=>EC,isAborted:()=>ea,isAsync:()=>Gn,isDirty:()=>ta,isValid:()=>kr,late:()=>lC,lazy:()=>zC,literal:()=>OC,makeIssue:()=>ms,map:()=>AC,nan:()=>pC,nativeEnum:()=>MC,never:()=>bC,null:()=>_C,nullable:()=>FC,number:()=>kg,object:()=>wC,objectUtil:()=>yl,oboolean:()=>ZC,onumber:()=>WC,optional:()=>LC,ostring:()=>qC,pipeline:()=>UC,preprocess:()=>HC,promise:()=>NC,quotelessJson:()=>j0,record:()=>TC,set:()=>IC,setErrorMap:()=>F0,strictObject:()=>kC,string:()=>wg,symbol:()=>hC,transformer:()=>jC,tuple:()=>CC,undefined:()=>gC,union:()=>RC,unknown:()=>vC,util:()=>Y,void:()=>SC});var Y;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},t.find=(o,i)=>{for(let a of o)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(Y||(Y={}));var yl;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(yl||(yl={}));var $=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wt=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var R=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),j0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Qe=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},n={_errors:[]},o=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];r[i]=r[i]||[],r[i].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Qe.create=t=>new Qe(t);var L0=(t,e)=>{let r;switch(t.code){case R.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case R.invalid_union:r="Invalid input";break;case R.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case R.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:r="Invalid function arguments";break;case R.invalid_return_type:r="Invalid function return type";break;case R.invalid_date:r="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case R.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case R.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case R.custom:r="Invalid input";break;case R.invalid_intersection_types:r="Intersection results could not be merged";break;case R.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}},sr=L0;var hg=sr;function F0(t){hg=t}function Kn(){return hg}var ms=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,i=[...r,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)c=l(a,{data:e,defaultError:c}).message;return{...o,path:i,message:c}},H0=[];function I(t,e){let r=Kn(),n=ms({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===sr?void 0:sr].filter(o=>!!o)});t.common.issues.push(n)}var Oe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return L;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let i=await o.key,a=await o.value;n.push({key:i,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return L;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),Gr=t=>({status:"dirty",value:t}),Ue=t=>({status:"valid",value:t}),ea=t=>t.status==="aborted",ta=t=>t.status==="dirty",kr=t=>t.status==="valid",Gn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));var ht=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gg=(t,e)=>{if(kr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Qe(t.common.issues);return this._error=r,this._error}}};function W(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,c)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:u??n??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:u??r??c.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Wt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Gn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return gg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return kr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>kr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wt(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(Gn(o)?o:Promise.resolve(o));return gg(n,i)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let a=e(o),c=()=>i.addIssue({code:R.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new gt({schema:this,typeName:H.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ft.create(this,this._def)}nullable(){return Bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return cr.create(this)}promise(){return Er.create(this,this._def)}or(e){return rn.create([this,e],this._def)}and(e){return nn.create(this,e,this._def)}transform(e){return new gt({...W(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new un({...W(this._def),innerType:this,defaultValue:r,typeName:H.ZodDefault})}brand(){return new fs({typeName:H.ZodBranded,type:this,...W(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ln({...W(this._def),innerType:this,catchValue:r,typeName:H.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return hs.create(this,e)}readonly(){return dn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},U0=/^c[^\s-]{8,}$/i,q0=/^[0-9a-z]+$/,W0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Z0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,B0=/^[a-z0-9_-]{21}$/i,V0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,K0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vl,Y0=/^(?:(?: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])$/,X0=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Q0=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,eC=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yg="((\\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])))",nC=new RegExp(`^${yg}$`);function vg(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oC(t){return new RegExp(`^${vg(t)}$`)}function bg(t){let e=`${yg}T${vg(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sC(t,e){return!!((e==="v4"||!e)&&Y0.test(t)||(e==="v6"||!e)&&Q0.test(t))}function iC(t,e){if(!V0.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function aC(t,e){return!!((e==="v4"||!e)&&X0.test(t)||(e==="v6"||!e)&&eC.test(t))}var Rr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.string,received:i.parsedType}),L}let n=new Oe,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?I(o,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&I(o,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")G0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"email",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")vl||(vl=new RegExp(J0,"u")),vl.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"emoji",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Z0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"uuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")B0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"nanoid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")U0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")q0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid2",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")W0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ulid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),I(o,{validation:"url",code:R.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"regex",code:R.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?bg(i).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?nC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?oC(i).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?K0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"duration",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?sC(e.data,i.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ip",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?iC(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"jwt",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?aC(e.data,i.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?tC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?rC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64url",code:R.invalid_string,message:i.message}),n.dirty()):Y.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:R.invalid_string,...z.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rr.create=t=>new Rr({checks:[],typeName:H.ZodString,coerce:t?.coerce??!1,...W(t)});function cC(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}var Jr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.number,received:i.parsedType}),L}let n,o=new Oe;for(let i of this._def.checks)i.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?cC(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_finite,message:i.message}),o.dirty()):Y.assertNever(i);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Jr.create=t=>new Jr({checks:[],typeName:H.ZodNumber,coerce:t?.coerce||!1,...W(t)});var Yr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let n,o=new Oe;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):Y.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return I(r,{code:R.invalid_type,expected:$.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Yr.create=t=>new Yr({checks:[],typeName:H.ZodBigInt,coerce:t?.coerce??!1,...W(t)});var Xr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.boolean,received:n.parsedType}),L}return Ue(e.data)}};Xr.create=t=>new Xr({typeName:H.ZodBoolean,coerce:t?.coerce||!1,...W(t)});var Qr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_date}),L}let n=new Oe,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Y.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Qr.create=t=>new Qr({checks:[],coerce:t?.coerce||!1,typeName:H.ZodDate,...W(t)});var Yn=class extends B{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.symbol,received:n.parsedType}),L}return Ue(e.data)}};Yn.create=t=>new Yn({typeName:H.ZodSymbol,...W(t)});var en=class extends B{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.undefined,received:n.parsedType}),L}return Ue(e.data)}};en.create=t=>new en({typeName:H.ZodUndefined,...W(t)});var tn=class extends B{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.null,received:n.parsedType}),L}return Ue(e.data)}};tn.create=t=>new tn({typeName:H.ZodNull,...W(t)});var Pr=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Ue(e.data)}};Pr.create=t=>new Pr({typeName:H.ZodAny,...W(t)});var ar=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ue(e.data)}};ar.create=t=>new ar({typeName:H.ZodUnknown,...W(t)});var At=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return I(r,{code:R.invalid_type,expected:$.never,received:r.parsedType}),L}};At.create=t=>new At({typeName:H.ZodNever,...W(t)});var Xn=class extends B{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.void,received:n.parsedType}),L}return Ue(e.data)}};Xn.create=t=>new Xn({typeName:H.ZodVoid,...W(t)});var cr=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==$.array)return I(r,{code:R.invalid_type,expected:$.array,received:r.parsedType}),L;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(a||c)&&(I(r,{code:a?R.too_big:R.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(I(r,{code:R.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(I(r,{code:R.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,c)=>o.type._parseAsync(new ht(r,a,r.path,c)))).then(a=>Oe.mergeArray(n,a));let i=[...r.data].map((a,c)=>o.type._parseSync(new ht(r,a,r.path,c)));return Oe.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}};cr.create=(t,e)=>new cr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...W(e)});function Jn(t){if(t instanceof et){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ft.create(Jn(n))}return new et({...t._def,shape:()=>e})}else return t instanceof cr?new cr({...t._def,type:Jn(t.element)}):t instanceof ft?ft.create(Jn(t.unwrap())):t instanceof Bt?Bt.create(Jn(t.unwrap())):t instanceof Zt?Zt.create(t.items.map(e=>Jn(e))):t}var et=class t extends B{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let l=this._getOrReturnCtx(e);return I(l,{code:R.invalid_type,expected:$.object,received:l.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof At&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||c.push(l);let u=[];for(let l of a){let d=i[l],p=o.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new ht(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof At){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")c.length>0&&(I(o,{code:R.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of c){let p=o.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new ht(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Oe.mergeObjectSync(n,l)):Oe.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:z.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Jn(this)}partial(e){let r={};for(let n of Y.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ft;)i=i._def.innerType;r[n]=i}return new t({...this._def,shape:()=>r})}keyof(){return Sg(Y.objectKeys(this.shape))}};et.create=(t,e)=>new et({shape:()=>t,unknownKeys:"strip",catchall:At.create(),typeName:H.ZodObject,...W(e)});et.strictCreate=(t,e)=>new et({shape:()=>t,unknownKeys:"strict",catchall:At.create(),typeName:H.ZodObject,...W(e)});et.lazycreate=(t,e)=>new et({shape:t,unknownKeys:"strip",catchall:At.create(),typeName:H.ZodObject,...W(e)});var rn=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new Qe(c.ctx.common.issues));return I(r,{code:R.invalid_union,unionErrors:a}),L}if(r.common.async)return Promise.all(n.map(async i=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of n){let l={...r,common:{...r.common,issues:[]},parent:null},d=u._parseSync({data:r.data,path:r.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(u=>new Qe(u));return I(r,{code:R.invalid_union,unionErrors:c}),L}}get options(){return this._def.options}};rn.create=(t,e)=>new rn({options:t,typeName:H.ZodUnion,...W(e)});var ir=t=>t instanceof on?ir(t.schema):t instanceof gt?ir(t.innerType()):t instanceof sn?[t.value]:t instanceof an?t.options:t instanceof cn?Y.objectValues(t.enum):t instanceof un?ir(t._def.innerType):t instanceof en?[void 0]:t instanceof tn?[null]:t instanceof ft?[void 0,...ir(t.unwrap())]:t instanceof Bt?[null,...ir(t.unwrap())]:t instanceof fs||t instanceof dn?ir(t.unwrap()):t instanceof ln?ir(t._def.innerType):[],ra=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return I(r,{code:R.invalid_type,expected:$.object,received:r.parsedType}),L;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(I(r,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let i of r){let a=ir(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,i)}}return new t({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...W(n)})}};function bl(t,e){let r=Wt(t),n=Wt(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&n===$.object){let o=Y.objectKeys(e),i=Y.objectKeys(t).filter(c=>o.indexOf(c)!==-1),a={...t,...e};for(let c of i){let u=bl(t[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(r===$.array&&n===$.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],u=bl(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===$.date&&n===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var nn=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(i,a)=>{if(ea(i)||ea(a))return L;let c=bl(i.value,a.value);return c.valid?((ta(i)||ta(a))&&r.dirty(),{status:r.value,value:c.data}):(I(n,{code:R.invalid_intersection_types}),L)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};nn.create=(t,e,r)=>new nn({left:t,right:e,typeName:H.ZodIntersection,...W(r)});var Zt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return I(n,{code:R.invalid_type,expected:$.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return I(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new ht(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>Oe.mergeArray(r,a)):Oe.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Zt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:H.ZodTuple,rest:null,...W(e)})};var na=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return I(n,{code:R.invalid_type,expected:$.object,received:n.parsedType}),L;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in n.data)o.push({key:i._parse(new ht(n,c,n.path,c)),value:a._parse(new ht(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?Oe.mergeObjectAsync(r,o):Oe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:H.ZodRecord,...W(n)}):new t({keyType:Rr.create(),valueType:e,typeName:H.ZodRecord,...W(r)})}},Qn=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return I(n,{code:R.invalid_type,expected:$.map,received:n.parsedType}),L;let o=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:o._parse(new ht(n,c,n.path,[l,"key"])),value:i._parse(new ht(n,u,n.path,[l,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return L;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(l.value,d.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let u of a){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return L;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(l.value,d.value)}return{status:r.value,value:c}}}};Qn.create=(t,e,r)=>new Qn({valueType:e,keyType:t,typeName:H.ZodMap,...W(r)});var eo=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return I(n,{code:R.invalid_type,expected:$.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(I(n,{code:R.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(I(n,{code:R.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let d of u){if(d.status==="aborted")return L;d.status==="dirty"&&r.dirty(),l.add(d.value)}return{status:r.value,value:l}}let c=[...n.data.values()].map((u,l)=>i._parse(new ht(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,r){return new t({...this._def,minSize:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};eo.create=(t,e)=>new eo({valueType:t,minSize:null,maxSize:null,typeName:H.ZodSet,...W(e)});var oa=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return I(r,{code:R.invalid_type,expected:$.function,received:r.parsedType}),L;function n(c,u){return ms({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kn(),sr].filter(l=>!!l),issueData:{code:R.invalid_arguments,argumentsError:u}})}function o(c,u){return ms({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kn(),sr].filter(l=>!!l),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Er){let c=this;return Ue(async function(...u){let l=new Qe([]),d=await c._def.args.parseAsync(u,i).catch(f=>{throw l.addIssue(n(u,f)),l}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,i).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let c=this;return Ue(function(...u){let l=c._def.args.safeParse(u,i);if(!l.success)throw new Qe([n(u,l.error)]);let d=Reflect.apply(a,this,l.data),p=c._def.returns.safeParse(d,i);if(!p.success)throw new Qe([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Zt.create(e).rest(ar.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Zt.create([]).rest(ar.create()),returns:r||ar.create(),typeName:H.ZodFunction,...W(n)})}},on=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};on.create=(t,e)=>new on({getter:t,typeName:H.ZodLazy,...W(e)});var sn=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return I(r,{received:r.data,code:R.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};sn.create=(t,e)=>new sn({value:t,typeName:H.ZodLiteral,...W(e)});function Sg(t,e){return new an({values:t,typeName:H.ZodEnum,...W(e)})}var an=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{expected:Y.joinValues(n),received:r.parsedType,code:R.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{received:r.data,code:R.invalid_enum_value,options:n}),L}return Ue(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};an.create=Sg;var cn=class extends B{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let o=Y.objectValues(r);return I(n,{expected:Y.joinValues(o),received:n.parsedType,code:R.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return I(n,{received:n.data,code:R.invalid_enum_value,options:o}),L}return Ue(e.data)}get enum(){return this._def.values}};cn.create=(t,e)=>new cn({values:t,typeName:H.ZodNativeEnum,...W(e)});var Er=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return I(r,{code:R.invalid_type,expected:$.promise,received:r.parsedType}),L;let n=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return Ue(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Er.create=(t,e)=>new Er({type:t,typeName:H.ZodPromise,...W(e)});var gt=class extends B{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:a=>{I(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async c=>{if(r.value==="aborted")return L;let u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?L:u.status==="dirty"?Gr(u.value):r.value==="dirty"?Gr(u.value):u});{if(r.value==="aborted")return L;let c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Gr(c.value):r.value==="dirty"?Gr(c.value):c}}if(o.type==="refinement"){let a=c=>{let u=o.refinement(c,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?L:(c.status==="dirty"&&r.dirty(),a(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?L:(c.status==="dirty"&&r.dirty(),a(c.value).then(()=>({status:r.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!kr(a))return L;let c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>kr(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:r.value,value:c})):L);Y.assertNever(o)}};gt.create=(t,e,r)=>new gt({schema:t,typeName:H.ZodEffects,effect:e,...W(r)});gt.createWithPreprocess=(t,e,r)=>new gt({schema:e,effect:{type:"preprocess",transform:t},typeName:H.ZodEffects,...W(r)});var ft=class extends B{_parse(e){return this._getType(e)===$.undefined?Ue(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(t,e)=>new ft({innerType:t,typeName:H.ZodOptional,...W(e)});var Bt=class extends B{_parse(e){return this._getType(e)===$.null?Ue(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:H.ZodNullable,...W(e)});var un=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};un.create=(t,e)=>new un({innerType:t,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var ln=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Gn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ln.create=(t,e)=>new ln({innerType:t,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var to=class extends B{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};to.create=t=>new to({typeName:H.ZodNaN,...W(t)});var uC=Symbol("zod_brand"),fs=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},hs=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(r.dirty(),Gr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:H.ZodPipeline})}},dn=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(kr(o)&&(o.value=Object.freeze(o.value)),o);return Gn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};dn.create=(t,e)=>new dn({innerType:t,typeName:H.ZodReadonly,...W(e)});function _g(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function xg(t,e={},r){return t?Pr.create().superRefine((n,o)=>{let i=t(n);if(i instanceof Promise)return i.then(a=>{if(!a){let c=_g(e,n),u=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:u})}});if(!i){let a=_g(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}}):Pr.create()}var lC={object:et.lazycreate},H;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(H||(H={}));var dC=(t,e={message:`Input not instance of ${t.name}`})=>xg(r=>r instanceof t,e),wg=Rr.create,kg=Jr.create,pC=to.create,mC=Yr.create,Rg=Xr.create,fC=Qr.create,hC=Yn.create,gC=en.create,_C=tn.create,yC=Pr.create,vC=ar.create,bC=At.create,SC=Xn.create,xC=cr.create,wC=et.create,kC=et.strictCreate,RC=rn.create,PC=ra.create,EC=nn.create,CC=Zt.create,TC=na.create,AC=Qn.create,IC=eo.create,$C=oa.create,zC=on.create,OC=sn.create,DC=an.create,MC=cn.create,NC=Er.create,jC=gt.create,LC=ft.create,FC=Bt.create,HC=gt.createWithPreprocess,UC=hs.create,qC=()=>wg().optional(),WC=()=>kg().optional(),ZC=()=>Rg().optional(),BC={string:(t=>Rr.create({...t,coerce:!0})),number:(t=>Jr.create({...t,coerce:!0})),boolean:(t=>Xr.create({...t,coerce:!0})),bigint:(t=>Yr.create({...t,coerce:!0})),date:(t=>Qr.create({...t,coerce:!0}))};var VC=L;var De=s.enum(["claude","codex","cursor","gemini","qoder"]),ro=s.enum(["none","low","medium","high","xhigh","max"]),sa=s.boolean(),ia=s.enum(["local","remote"]),Pg=s.enum(["app_install","user_invite","system"]),H4=s.enum(["long_lived","bootstrap"]),Vt=s.enum(["regular","agent_home"]),_t=s.enum(["channel","dm_channel"]),Eg=s.enum(["starting","active","idle","archived","crashed"]),aa=s.enum(["idle","starting","active","crashed"]),ca=s.enum(["user","agent","system"]),It=s.enum(["todo","in_progress","in_review","done","closed"]),Cg=s.enum(["agent","user"]),Tg=s.enum(["session_init","thinking","text","tool_call","tool_output","file_change","shell","stderr","compaction_started","compaction_finished","turn_end","error","unknown","parsed_event_dropped"]),Ag=s.enum(["pending_materialization","active","failed"]),Ig=["read_messages","send_messages","read_tasks","create_tasks","write_tasks","read_attachments","upload_attachments","create_threads","create_channels","manage_conversation_members","manage_schedules"],$g=s.enum(["local","s3","oss"]),zg=s.enum(["user","agent"]),Og=s.enum(["mention_external","mention_self","agent_start_failed"]);var KC=s.enum(["pending","attached","active","revoked"]),Kt=s.object({id:s.string(),name:s.string(),kind:ia,created_at:s.number(),revoked_at:s.number().nullable(),last_seen_at:s.number().nullable(),activated_at:s.number().nullable().optional().default(null),finalized_at:s.number().nullable().optional().default(null),connected_host_name:s.string().nullable().optional().default(null),provisioning_source:Pg.optional().default("system"),status:KC.optional().default("pending"),placeable:s.boolean().optional().default(!1),creator_user_id:s.string().nullable().optional().default(null),display_label:s.string().nullable()}),Z4=s.object({display_label:s.string().max(256).nullable()}).strict(),B4=s.object({host:Kt}),V4=s.enum(["available","disconnected","unreachable","revoked"]);var Dg="host_revoked",Mg="host_disconnected",K4=s.object({host_id:s.string()}).strict(),GC=s.enum(["daemon_unreachable","timeout","protocol_error"]),ua=s.object({agent_id:s.string(),display_name:s.string(),handle:s.string(),runtime:s.string(),avatar_url:s.string().nullable().optional().default(null),online:s.enum(["online","offline"])}),JC=s.object({os:s.string().min(1),os_arch:s.string().optional(),daemon_version:s.string(),daemon_pid:s.number().int(),started_at:s.number().int(),uptime_ms:s.number().int()}),YC=s.object({host_id:s.string(),availability:s.literal("available"),snapshot:JC,agents:s.array(ua),last_seen_at:s.number().nullable().optional()}).strict(),XC=s.object({host_id:s.string(),availability:s.literal("disconnected"),agents:s.array(ua),last_seen_at:s.number().nullable().optional()}).strict(),QC=s.object({host_id:s.string(),availability:s.literal("unreachable"),reason:GC,agents:s.array(ua),last_seen_at:s.number().nullable().optional()}).strict(),eT=s.object({host_id:s.string(),availability:s.literal("revoked"),agents:s.array(ua),last_seen_at:s.number().nullable().optional()}).strict(),G4=s.discriminatedUnion("availability",[YC,XC,QC,eT]),Sl=s.object({proxy_url:s.string().nullable(),proxy_runtimes:s.array(De)}),J4=s.object({config:Sl}).strict(),tT="computer_offline",Y4=s.object({error:s.string(),error_code:s.literal(tT)}).strict(),X4=s.object({installation_id:s.string().uuid(),label:s.string().trim().min(1).max(128).optional(),current_host_id:s.string().min(1).optional()}).strict(),Q4=s.object({host_id:s.string(),host:Kt,server_url:s.string().url(),host_token:s.string().min(1).optional()}),eB=s.object({hosts:s.array(Kt)}),tB=s.object({}).strict(),rB=s.object({host_id:s.string(),host:Kt,server_url:s.string().url(),connect_token:s.string().min(1),daemon_command:s.string().min(1)}),nB=s.object({host_id:s.string().min(1)}),oB=s.object({host:Kt}),sB=s.object({host_id:s.string(),deleted:s.literal(!0)});var rT=s.object({agents:s.number().int().nonnegative(),workspaces:s.number().int().nonnegative()}),iB=s.object({error:s.string(),error_code:s.literal("has_dependents"),dependents:rT}),aB=s.object({host:Kt}),nT=s.object({host_id:s.string(),host:Kt,host_token:s.string().min(1)}),oT=s.object({host_id:s.string(),host:Kt,status:s.literal("rotated")}),sT=s.object({host_id:s.string(),host:Kt,status:s.literal("rotated"),connect_token:s.string().min(1),daemon_command:s.string().min(1)}),cB=s.object({host_id:s.string(),host:Kt,disconnected:s.boolean()}),uB=s.union([nT,oT,sT]);var gs=s.object({id:s.string(),name:s.string(),display_name:s.string(),avatar_url:s.string().nullable(),created_at:s.number(),updated_at:s.number()}),pB=s.object({users:s.array(gs)}),iT=s.object({registration_required:s.literal(!0),suggested_name:s.string()}),mB=s.union([gs,iT]),aT=/[\x00-\x1F\x7F-\x9F\u2028\u2029]/,cT="display_name must not contain control characters or Unicode line separators",_s=s.string().trim().min(1).max(64).refine(t=>!aT.test(t),{message:cT}),Ng=s.string().trim().email().max(320),fB=s.object({email:Ng,password:s.string().min(8).max(1024),display_name:_s.optional()}),hB=s.object({email:Ng,password:s.string().min(1).max(1024)}),gB=s.object({user_token:s.string().min(1),user:gs}),_B=s.object({ok:s.literal(!0)}),yB=s.object({display_name:_s.optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),vB=s.object({avatar_url:s.string()});var uT=s.enum(["loopback","lan","public"]),xB=s.object({signup_enabled:s.boolean(),bind_address_scope:uT.optional()});var jg={claude:{kind:"claude",label:"Claude",cliLabel:"Claude Code",selectable:!0,reasoningEffortOptions:[],supportsProfileMcp:!0,modelSuggestions:[]},codex:{kind:"codex",label:"Codex",cliLabel:"Codex CLI",selectable:!0,reasoningEffortOptions:["low","medium","high","xhigh"],supportsProfileMcp:!0,modelSuggestions:[]},qoder:{kind:"qoder",label:"Qoder",cliLabel:"Qoder",selectable:!0,reasoningEffortOptions:["none","low","medium","high","xhigh","max"],supportsProfileMcp:!0,modelSuggestions:["Auto","Ultimate","Performance","Efficient","Lite"],defaultModel:"Ultimate"},cursor:{kind:"cursor",label:"Cursor",cliLabel:"Cursor",selectable:!1,reasoningEffortOptions:[],supportsProfileMcp:!1,modelSuggestions:[]},gemini:{kind:"gemini",label:"Gemini",cliLabel:"Gemini",selectable:!1,reasoningEffortOptions:[],supportsProfileMcp:!1,modelSuggestions:[]}},lT=["claude","codex","qoder","cursor","gemini"],RB=lT.map(t=>jg[t]);function Lg(t,e){return e==null?!0:jg[t].reasoningEffortOptions.includes(e)}var Fg=s.object({id:s.string(),name:s.string(),display_name:s.string(),runtime:De,model:s.string().nullable(),reasoning_effort:ro.nullable(),fast_mode:sa.nullable(),host_id:s.string(),description:s.string().nullable(),created_by_user_id:s.string(),avatar_url:s.string().nullable(),materialization_status:Ag,materialization_failed_code:s.string().nullable(),materialization_failed_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),IB=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),runtime:De,model:s.string().optional(),reasoning_effort:ro.optional(),fast_mode:sa.optional(),host_id:s.string().optional(),description:s.string().optional()}).superRefine((t,e)=>{Lg(t.runtime,t.reasoning_effort)||e.addIssue({code:s.ZodIssueCode.custom,path:["reasoning_effort"],message:`reasoning_effort '${t.reasoning_effort}' is not valid for runtime '${t.runtime}'`})}),$B=s.object({display_name:_s.optional(),description:s.string().max(2e3).nullable().optional(),runtime:s.never().optional(),model:s.string().nullable().optional(),reasoning_effort:ro.nullable().optional(),fast_mode:sa.nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),zB=s.object({id:s.string(),name:s.string(),display_name:s.string(),description:s.string().nullable(),avatar_url:s.string().nullable()}),OB=s.object({display_name:_s.optional(),description:s.string().max(2e3).nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),DB=s.object({agent_id:s.string()}),dT=s.object({path:s.string().min(1),kind:s.enum(["file","directory"]),size:s.number(),mtime:s.number()}).strict(),Hg=s.object({nodes:s.array(dT)}).strict(),Ug=s.object({path:s.string().min(1),content:s.string(),size:s.number(),mtime:s.number(),truncated:s.boolean()}).strict(),qg=s.object({conversation_id:s.string(),workspace_id:s.string(),workspace_name:s.string(),workspace_kind:Vt,conversation_kind:_t,channel_id:s.string(),channel_title:s.string(),status:aa,pid:s.number().nullable(),closed_at:s.number().nullable()}),MB=s.object({conversation_agents:s.array(qg)}),NB=s.object({agent_id:s.string(),agent_name:s.string(),agent_display_name:s.string(),dm_channel:s.object({id:s.string(),name:s.string(),conversation_count:s.number(),message_count:s.number()}).nullable(),regular_workspaces:s.array(s.object({id:s.string(),name:s.string()})),regular_memberships:s.array(s.object({id:s.string(),name:s.string()})),owned_home:s.object({id:s.string(),name:s.string(),workspace_kind:Vt,owner_agent_id:s.string().nullable()}).nullable(),attachments_count:s.number(),running_conversation_agents:s.array(qg),pending_inbox_count:s.number()}),jB=s.object({confirm:s.literal(!0)});var WB=s.object({id:s.string(),name:s.string(),description:s.string().nullable(),workspace_kind:Vt,workspace_path:s.string(),workspace_host_id:s.string(),owner_agent_id:s.string().nullable(),owner_user_id:s.string().nullable(),dm_channel_id:s.string().nullable(),dm_channel_ids:s.array(s.string()),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),ZB=s.object({workspace_id:s.string(),agent_id:s.string(),joined_at:s.number()}),la=s.enum(["owner","admin","member"]),pT=s.object({workspace_id:s.string(),user_id:s.string(),joined_at:s.number(),role:la}),Wg=gs.extend({workspace_id:s.string(),user_id:s.string(),joined_at:s.number(),role:la}),ys=s.enum(Ig),BB=s.object({workspace_id:s.string(),agent_id:s.string(),capabilities:s.array(ys)}),VB=s.object({capabilities:s.array(ys)}),KB=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),description:s.string().optional(),workspace_path:s.string().optional(),workspace_host_id:s.string().optional(),member_agent_ids:s.array(s.string()).default([]),member_user_ids:s.array(s.string()).default([])}),GB=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore").optional(),description:s.string().nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),JB=s.object({archived:s.boolean()}),mT=s.object({agent_id:s.string()}),fT=s.object({kind:s.literal("agent"),agent_id:s.string()}),hT=s.object({kind:s.literal("human"),user_id:s.string()}),YB=s.union([fT,hT,mT]),XB=s.object({role:la}),QB=s.object({member:pT,human_member:Wg}),e9=s.object({members:s.array(Fg),human_members:s.array(Wg),viewer_role:la.nullable()});var Zg=s.object({id:s.string(),workspace_id:s.string(),workspace_path:s.string(),kind:_t,title:s.string(),status:Eg,spawned_by_agent_id:s.string().nullable(),closed_at:s.number().nullable(),close_summary:s.string().nullable(),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),gT=Zg.extend({kind:s.literal("channel")}),_T=Zg.extend({kind:s.literal("dm_channel")}),Bg=s.string().trim().min(1).max(128),o9=s.object({title:Bg,member_agent_ids:s.array(s.string()).default([]),member_user_ids:s.array(s.string()).optional()}),yT=s.enum(["regular","dm"]),vT=s.object({id:s.string(),kind:_t,title:s.string(),workspace_id:s.string(),workspace_kind:yT,workspace_path:s.string(),closed_at:s.number().nullable(),archived_at:s.number().nullable()}),s9=s.object({ref:vT}),i9=s.object({conversation_id:s.string(),agent_id:s.string(),cli_session_id:s.string().nullable(),pid:s.number().nullable(),status:aa,joined_at:s.number()}),a9=s.object({conversation_id:s.string(),user_id:s.string(),joined_at:s.number()}),bT=s.object({kind:s.literal("agent"),agent_id:s.string(),name:s.string(),display_name:s.string(),runtime:De}),ST=s.object({kind:s.literal("human"),user_id:s.string(),name:s.string(),display_name:s.string(),avatar_url:s.string().nullable()}),xl=s.discriminatedUnion("kind",[bT,ST]),c9=s.object({members:s.array(xl)}),xT=s.string().trim().regex(/^@?[a-zA-Z0-9_-]{1,64}$/,{message:"handle must be @optional alphanumeric / dash / underscore"}),wT=s.discriminatedUnion("kind",[s.object({kind:s.literal("agent"),agent_id:s.string()}),s.object({kind:s.literal("human"),user_id:s.string()})]),kT=s.object({handle:xT}),u9=s.union([wT,kT]),l9=s.object({ok:s.literal(!0),prev_cli_session_id:s.string().nullable(),was_running:s.boolean()}),RT=s.record(s.string(),s.unknown()).nullable(),PT=s.object({id:s.number().int(),conversation_id:s.string(),agent_id:s.string().nullable(),kind:Tg,payload:RT,created_at:s.number().int()}),d9=s.object({events:s.array(PT),next_before_id:s.number().int().nullable()});var ET=s.union([gT,_T]),p9=s.object({archived:s.boolean()}),m9=s.object({title:Bg}),f9=s.object({workspace_id:s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().optional()),since:s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional())}),CT=s.object({channel:ET,workspace:s.object({id:s.string(),name:s.string(),archived_at:s.number().nullable()})}),h9=s.object({channels:s.array(CT)});var TT=s.enum(["starting","thinking","tool_running","idle","failed"]),AT=s.enum(["replied","turn_ended","replaced","stopped","crashed","timeout","conversation_closed"]),no=s.object({runId:s.string(),agentId:s.string(),conversationId:s.string(),status:TT,startedAt:s.number(),updatedAt:s.number(),lastActivityAt:s.number(),terminalReason:AT.optional(),activitySnippet:s.string().optional(),toolCallCounts:s.record(s.string(),s.number()).optional(),compacting:s.boolean().optional(),compactingSince:s.number().optional(),compactionStale:s.boolean().optional(),detail:s.string().optional()});var v9=s.object({states:s.array(no)}),b9=s.object({kind:De,installed:s.boolean(),binary:s.string().nullable(),version:s.string().nullable()});var k9=s.object({id:s.string(),channel_id:s.string(),source_conversation_id:s.string().nullable(),filename:s.string(),size:s.number(),content_type:s.string(),storage:$g,created_by_kind:zg,created_by_id:s.string(),created_at:s.number()}),IT=/^(Image|File) #([1-9]\d{0,3})$/,Vg=s.string().trim().regex(IT,'label must be "Image #N" or "File #N"');var da=s.object({id:s.string(),filename:s.string(),size:s.number(),content_type:s.string(),label:Vg.optional()}),Kg=s.object({id:s.string().min(1),label:Vg.optional()});var R9=s.union([s.object({storage:s.literal("local"),local_path:s.string(),filename:s.string(),content_type:s.string()}),s.object({storage:s.enum(["s3","oss"]),download_url:s.string(),filename:s.string(),content_type:s.string()})]);var Gg=s.enum(["user","agent"]),pa=s.object({emoji:s.string(),count:s.number().int().positive(),viewer_reacted:s.boolean()}),$T=s.object({kind:Gg,id:s.string(),display_name:s.string()}),C9=s.object({emoji:s.string(),reactors:s.array($T)}),T9=s.object({emoji:s.string()}),A9=s.object({message_id:s.string().min(1),emoji:s.string()}),I9=s.object({message_id:s.string(),conversation_id:s.string(),thread_root_id:s.string().nullable(),emoji:s.string(),op:s.enum(["add","remove"]),reactor_kind:Gg,reactor_id:s.string(),count:s.number().int().nonnegative()});var $9=new RegExp("^(?:\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");var Cr=s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().trim().optional()),ma=s.array(s.union([s.string().min(1),Kg])).max(20).refine(t=>{let e=t.map(r=>typeof r=="string"?void 0:r.label).filter(r=>r!==void 0);return new Set(e).size===e.length},{message:"attachment labels must be unique within a message"}).optional();function fa(t){return t.content.trim().length>0||(t.attachment_ids?.length??0)>0}var wl=s.union([s.object({kind:s.literal("channel")}).strict(),s.object({kind:s.literal("thread"),message_id:s.string().min(1)}).strict()]),zT=s.literal("self"),kl=s.union([wl,zT]),U9=s.enum(["unaffected","revised","obsolete","force_send"]),Rl=s.enum(["unaffected","revised","force_send"]),q9=s.object({content:s.string(),target:kl.optional(),reply_to_message_id:s.string().min(1).optional(),stream_key:s.string().min(1).optional(),seen_up_to_seq:s.number().int().nonnegative().optional(),stale_event_id:s.string().min(1).optional(),stale_resolution_reason:Rl.optional(),freshness_bypass:s.boolean().optional(),attachment_ids:ma}).refine(fa,{message:"message must include text or at least one attachment",path:["content"]}),W9=s.object({stale_event_id:s.string().min(1),resolution_reason:s.literal("obsolete")}),Z9=s.object({message_id:s.string(),message_seq:s.number().int().positive(),thread_root_id:s.string().nullable()}),B9=s.object({title:s.string().min(1).max(128),context_summary:s.string().min(1),initial_prompt:s.string().min(1)}),V9=s.object({root_message_id:s.string().min(1)}),K9=s.object({thread_root_id:s.string(),changed:s.boolean()}),G9=s.object({task_number:s.number().int().positive(),status:s.enum(["todo","in_progress","in_review"]),title:s.string(),assignee_name:s.string().nullable(),assignee_agent_id:s.string().nullable()}),Jg=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional()),OT=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().positive().max(100).optional().default(50)),DT=s.union([s.literal("self"),s.object({thread_root_id:s.string().min(1)}),s.object({conversation_id:s.string().min(1)})]),J9=s.object({target:DT.optional(),before_seq:Jg,after_seq:Jg,around_message_id:s.string().min(1).optional(),include_content:s.boolean().optional().default(!1),include_system:s.boolean().optional().default(!0),limit:OT}).refine(t=>[t.before_seq,t.after_seq,t.around_message_id].filter(e=>e!==void 0).length<=1,{message:"pass at most one of before_seq, after_seq, or around_message_id; omit all to read the latest window",path:["before_seq"]}),Yg=s.object({id:s.string(),workspace_id:s.string(),conversation_id:s.string(),conversation_kind:_t,channel_id:s.string(),seq:s.number(),created_at:s.number()}),Xg=s.object({kind:ca,agent_id:s.string().nullable(),user_id:s.string().nullable(),display_name:s.string().nullable()}),MT=s.object({conversation_id:s.string(),conversation_kind:_t,channel_id:s.string(),thread_root_id:s.string().nullable(),workspace_id:s.string(),title:s.string()}),NT=s.object({message_ref:Yg,sender:Xg,snippet:s.string(),metadata:s.record(s.unknown()).nullable(),attachments:s.array(da).nullable(),reactions:s.array(pa).nullable(),content:s.string().optional()}),jT=s.union([s.object({type:s.literal("head")}),s.object({type:s.literal("before_seq"),seq:s.number()}),s.object({type:s.literal("after_seq"),seq:s.number()}),s.object({type:s.literal("around_message_id"),message_id:s.string()})]),Y9=s.object({target:MT,anchor:jT,limit:s.number(),include_content:s.boolean(),include_system:s.boolean(),messages:s.array(NT),has_more_before:s.boolean(),has_more_after:s.boolean()}),LT=s.object({id:s.string(),name:s.string(),kind:Vt,archived:s.boolean(),updated_at:s.number(),agent_dir:s.string()}),X9=s.object({workspaces:s.array(LT)}),Q9=s.object({workspace_id:s.string().min(1).optional()}),FT=s.object({id:s.string(),title:s.string(),kind:s.enum(["channel","dm_channel"]),archived:s.boolean(),updated_at:s.number()}),eV=s.object({workspace_id:s.string(),channels:s.array(FT)}),Qg=s.enum(["current","workspace","channel"]),HT=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().positive().max(100).optional().default(50)),tV=s.object({q:s.string().trim().min(1).max(200),scope:Qg.optional().default("current"),workspace_id:s.string().min(1).optional(),channel_id:Cr,include_system:s.boolean().optional().default(!0),limit:HT}).superRefine((t,e)=>{t.scope==="channel"!=!!t.channel_id&&e.addIssue({code:s.ZodIssueCode.custom,message:"channel_id is required only when scope is channel",path:["channel_id"]}),t.workspace_id&&t.scope!=="workspace"&&e.addIssue({code:s.ZodIssueCode.custom,message:"workspace_id is only valid with scope=workspace",path:["workspace_id"]})}),UT=s.object({message_ref:Yg,sender:Xg,excerpt:s.string(),match_offset:s.number().int().nonnegative()}),rV=s.object({query:s.string(),scope:Qg,workspace_id:s.string().nullable(),channel_id:s.string().nullable(),include_system:s.boolean(),limit:s.number(),hits:s.array(UT)}),nV=s.object({noun:s.string().max(64).optional(),verb:s.string().max(64).optional(),flags_seen:s.array(s.string().max(64)).max(64).optional(),error_code:s.string().max(64).optional(),error_subkind:s.string().max(64).optional(),error_message:s.string().max(500).optional(),duration_ms:s.number().nonnegative().optional()}).strict(),oV=s.object({ok:s.literal(!0)}),sV=s.object({enabled:s.boolean()}).strict(),iV=s.object({conversationId:s.string(),enabled:s.boolean(),expiresAt:s.number().int().nullable(),daemonSynced:s.boolean().optional()}).strict();var oo=s.object({type:Cg,id:s.string(),name:s.string()}),e_=s.object({id:s.string(),title:s.string()}),qT=s.object({type:s.enum(["agent","user","system"]),id:s.string().nullable(),name:s.string()}),pV=s.object({message_id:s.string(),task_number:s.number(),workspace_id:s.string(),workspace_name:s.string(),channel_id:s.string(),channel_name:s.string(),thread_root_id:s.string().nullable(),conversation:e_,status:It,title:s.string(),assignee:oo.nullable(),creator:qT,created_at:s.number(),closed_at:s.number().nullable()}),mV=s.object({workspace_id:s.string().optional(),conversation_id:s.string().optional(),status:s.array(It).optional(),task_number:s.array(s.coerce.number().int().positive()).optional(),assignee_id:s.string().optional(),limit:s.coerce.number().int().positive().max(500).optional()}),fV=s.object({tasks:s.array(s.object({title:s.string().min(1).max(200),body:s.string().optional()})).min(1),target:wl.optional(),reply_to_message_id:s.string().min(1).optional()}),WT=s.enum(["conversation_not_found","conversation_closed","not_conversation_member","agent_not_found","reply_target_not_found"]),ZT=s.object({tasks:s.array(s.object({message_id:s.string(),task_number:s.number(),title:s.string()}))}),BT=s.object({error:WT}),hV=s.union([ZT,BT]),gV=s.object({task_numbers:s.array(s.number()).optional(),message_ids:s.array(s.string()).optional(),workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>(t.task_numbers?.length??0)+(t.message_ids?.length??0)>0,{message:"provide at least one of task_numbers or message_ids"}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),VT=s.enum(["task_not_found","message_not_found","wrong_conversation","cannot_promote_system_message","cannot_promote_anchor","task_done","task_closed","already_claimed","not_self_assignment","assignee_not_conversation_member","conversation_not_found","not_conversation_member","agent_not_found","not_a_task","unknown_workspace","ambiguous_workspace","workspace_membership_required","capability_denied"]),KT=s.object({success:s.boolean(),task_number:s.number().optional(),message_id:s.string().optional(),reason:s.string().optional(),code:VT.optional(),capability:ys.optional(),owner_conversation:e_.optional(),workspace_candidates:s.array(s.string()).optional()}),_V=s.object({results:s.array(KT)}),yV=s.object({task_number:s.number().int().positive(),workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),vV=s.object({task_number:s.number().int().positive(),status:It,workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),GT=s.enum(["not_a_task","task_not_found","task_done","wrong_conversation","not_assignee","invalid_transition","already_at_status","task_closed","conversation_not_found","not_conversation_member","agent_not_found","unknown_workspace","ambiguous_workspace","workspace_membership_required","capability_denied"]),bV=s.object({success:s.boolean(),reason:s.string().optional(),code:GT.optional(),capability:ys.optional(),workspace_candidates:s.array(s.string()).optional()}),SV=s.object({status:It}),xV=s.object({agent_id:s.string().optional()}),wV=s.object({kind:s.enum(["create","claim","unclaim","status"]),workspace_id:s.string(),channel_id:s.string(),thread_root_id:s.string().nullable(),conversation_id:s.string(),task_number:s.number(),message_id:s.string(),status:It,assignee:oo.nullable(),title:s.string(),closed_at:s.number().nullable()});function ha(t,e){if(!Number.isInteger(t)||t<0)throw new RangeError(`${e}: cannot decode ${t} \u2014 expected a non-negative integer seq`)}function JT(t){return ha(t,"MessageSeq"),t}function YT(t){return ha(t,"TransportSeq"),t}function XT(t){return ha(t,"ReadSeq"),t}function ga(t){return ha(t,"ObservedSeq"),t}function QT(t){if(typeof t!="string"||t.length===0)throw new RangeError(`TransportEpoch: cannot decode ${JSON.stringify(t)} \u2014 expected a non-empty string`);return t}var _a=s.number().int().nonnegative(),pn=_a.transform(JT),PV=_a.transform(YT),EV=_a.transform(XT),CV=_a.transform(ga),TV=s.string().min(1).transform(QT);var eA=s.enum(["agent","human","system"]),tA=s.object({kind:eA,id:s.string()}),rA=s.object({kind:s.enum(["agent","human"]),id:s.string()}),t_=s.object({root_message_id:s.string(),root_author:tA,root_preview:s.string(),root_created_at:s.number(),root_seq:pn,reply_count:s.number().int().nonnegative(),last_reply_at:s.number(),last_reply_message_id:s.string(),repliers:s.array(rA),replier_total:s.number().int().nonnegative(),viewer_following:s.boolean()}),r_=t_.omit({viewer_following:!0}),zV=s.object({threads:s.array(t_),next_cursor:s.string().nullable()});var ya=s.object({id:s.string(),conversation_id:s.string(),from_kind:ca,from_agent_id:s.string().nullable(),from_user_id:s.string().nullable(),content:s.string(),metadata:s.record(s.unknown()).nullable(),attachments:s.array(da).nullable(),reactions:s.array(pa).nullable(),seq:pn,created_at:s.number(),thread_root_id:s.string().nullable(),task_number:s.number().nullable(),task_status:It.nullable(),task_title:s.string().nullable(),task_workspace_id:s.string().nullable(),task_closed_at:s.number().nullable(),task_assignee:oo.nullable()}),nA=s.object({root_id:s.string(),reply_count:s.number().int().nonnegative()}),oA=s.object({thread_root_reply_count:nA.optional(),threads_list_entry:s.object({entry:r_}).optional()}),qV=s.object({message:ya,projections:oA.optional()}),sA=s.object({reply_count:s.number().int().nonnegative(),last_reply_at:s.number(),repliers:s.array(s.object({kind:s.enum(["agent","human"]),id:s.string()})),replier_total:s.number().int().nonnegative()}),WV=s.object({messages:s.array(ya),reply_counts_by_root:s.record(s.string(),s.number().int().nonnegative()),reply_summaries_by_root:s.record(s.string(),sA).optional(),has_more_before:s.boolean(),stream_head_seq:pn,has_more_after:s.boolean()}),ZV=s.object({thread_root_id:s.string(),viewer_following:s.boolean(),follower_agent_ids:s.array(s.string())}),BV=s.object({thread_root_id:s.string(),changed:s.boolean(),viewer_following:s.boolean()}),VV=s.object({content:s.string(),attachment_ids:ma,reply_to_message_id:s.string().min(1).optional(),as_task:s.boolean().optional()}).refine(fa,{message:"message must include text or at least one attachment",path:["content"]}),n_=s.object({unread_count:s.number().int().nonnegative(),first_unread_message_id:s.string().nullable(),first_unread_seq:pn.nullable()}),KV=s.object({mainline:n_,threads:s.record(s.string(),n_)}),i_=s.object({conversation_id:s.string(),message_id:s.string(),seq:pn,thread_root_id:s.string().nullable()}),GV=s.object({by_conversation:s.record(s.string(),s.number()),latest_by_conversation:s.record(s.string(),i_),total:s.number()}),JV=s.object({by_workspace:s.record(s.string(),s.number())}),YV=s.object({conversation_id:s.string(),workspace_id:s.string(),conversation_unread_count:s.number(),workspace_unread_count:s.number(),latest_unread:i_.nullable()}),o_=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional()),iA=s.enum(["all","regular","dm"]),aA=s.enum(["all","mainline","thread"]),cA=s.enum(["recency_desc","seq_asc"]),uA=s.object({q:s.string().trim().max(200).optional().default(""),scope:iA.optional().default("all"),stream:aA.optional().default("all"),workspace_id:Cr,conversation_id:Cr,thread_root_id:Cr,user_id:Cr,agent_id:Cr,from:o_,to:o_,order:cA.optional().default("recency_desc"),limit:s.coerce.number().int().positive().max(500).optional().default(80)}).refine(t=>!(t.user_id&&t.agent_id),{message:"user_id and agent_id cannot both be set",path:["user_id"]}).refine(t=>t.stream==="all"||!!t.conversation_id,{message:"stream filter requires conversation_id",path:["stream"]}).refine(t=>t.stream!=="thread"||!!t.thread_root_id,{message:"stream=thread requires thread_root_id",path:["thread_root_id"]}).refine(t=>t.order!=="seq_asc"||!!t.conversation_id,{message:"order=seq_asc requires conversation_id",path:["order"]}),Pl=s.object({id:s.string(),name:s.string(),kind:s.enum(["regular","dm"])}),s_=s.object({id:s.string(),title:s.string(),kind:_t,channel_id:s.string(),closed_at:s.number().nullable(),created_at:s.number()}),lA=s.discriminatedUnion("type",[s.object({type:s.literal("workspace"),workspace:Pl.extend({description:s.string().nullable(),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()})}),s.object({type:s.literal("conversation"),workspace:Pl,conversation:s_}),s.object({type:s.literal("message"),workspace:Pl,conversation:s_,message:ya,agent_name:s.string().nullable()})]),XV=s.object({query:uA,results:s.array(lA),total:s.number(),truncated:s.boolean()}),QV=s.object({id:s.string(),message:ya,workspace_id:s.string(),workspace_name:s.string(),conversation_id:s.string(),conversation_title:s.string(),channel_id:s.string(),agent_name:s.string().nullable(),saved_at:s.number()}),eK=s.object({workspace_id:s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().optional()),since:s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional())});var a_=["all","mentions"];var nK=s.object({conversation_id:s.string(),mode:s.enum(a_)}),oK=s.object({mode:s.enum(a_)}),dA=["directed","ambient"],pA=["mention","agent_failed","unread"],mA=s.object({kind:s.enum(["user","agent"]),id:s.string(),display_name:s.string(),avatar_url:s.string().nullable()}),fA=s.object({id:s.string(),kind:s.enum(pA),salience:s.enum(dA),workspace_id:s.string(),conversation_id:s.string(),thread_root_id:s.string().nullable(),message_id:s.string().nullable(),notification_id:s.string().nullable(),conversation_kind:s.enum(["channel","dm_channel"]),title:s.string(),thread_root_preview:s.string().nullable(),preview:s.string().nullable(),preview_sender:mA.nullable(),timestamp:s.number(),unread_count:s.number().int().nonnegative().nullable()}),sK=s.object({items:s.array(fA)}),hA=s.discriminatedUnion("kind",[s.object({kind:s.literal("at_seq"),seq:s.number().int().nonnegative()}),s.object({kind:s.literal("stream_head")})]),gA=s.discriminatedUnion("kind",[s.object({kind:s.literal("stream"),conversation_id:s.string().min(1),thread_root_id:s.string().min(1).nullable(),position:hA}),s.object({kind:s.literal("notification"),notification_id:s.string().min(1)})]),iK=s.object({sources:s.array(gA).min(1).max(1e3)}),aK=s.object({changed:s.boolean()});var dK=s.object({id:s.string(),kind:Og,user_id:s.string().nullable(),agent_id:s.string().nullable(),workspace_id:s.string().nullable(),conversation_id:s.string().nullable(),message_id:s.string().nullable(),thread_root_id:s.string().nullable().optional(),source_workspace_id:s.string().nullable(),source_conversation_id:s.string().nullable(),source_message_id:s.string().nullable(),payload:s.record(s.unknown()).nullable(),read_at:s.number().nullable(),created_at:s.number()}),pK=s.object({id:s.string().optional(),workspace_id:s.string().optional(),conversation_id:s.string().optional(),all:s.boolean().optional()}).refine(t=>!!(t.id||t.workspace_id||t.conversation_id||t.all),{message:"must specify id, workspace_id, conversation_id, or all"});var hK=2160*60*60,_A=60;var yA=120,vA=500,bA=s.enum(["pending","firing","done","cancelled","failed"]),SA=s.object({kind:s.literal("once"),fire_at:s.number().int().positive()}),c_=s.object({kind:s.literal("interval"),every_seconds:s.number().int().min(_A),start_at:s.number().int().positive().optional()}),u_=s.object({kind:s.literal("cron"),expression:s.string().min(1).max(200),timezone:s.string().min(1).max(64)}),xA=s.discriminatedUnion("kind",[SA,c_,u_]),El=s.object({id:s.string(),owner_agent_id:s.string(),target_conversation_id:s.string(),target_label:s.string(),title:s.string(),message:s.string(),spec:xA,next_fire_at:s.number(),status:bA,fired_count:s.number(),last_fired_at:s.number().nullable(),max_occurrences:s.number().nullable(),until_at:s.number().nullable(),failure_reason:s.string().nullable(),cancelled_at:s.number().nullable(),last_failure_reason:s.string().nullable(),last_failure_at:s.number().nullable(),consecutive_failure_count:s.number(),created_at:s.number(),updated_at:s.number()}),wA=s.object({kind:s.literal("once"),fire_at:s.number().int().positive().optional(),delay_seconds:s.number().int().positive().optional()}),gK=s.object({title:s.string().trim().min(1).max(yA),message:s.string().min(1).max(vA),target_conversation_id:s.string().optional(),spec:s.discriminatedUnion("kind",[wA,c_,u_]),until_at:s.number().int().positive().optional(),max_occurrences:s.number().int().positive().optional(),allow_unbounded:s.boolean().optional()}).superRefine((t,e)=>{t.spec.kind==="once"&&(t.until_at!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["until_at"],message:"until_at is not valid on a `once` schedule"}),t.max_occurrences!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["max_occurrences"],message:"max_occurrences is not valid on a `once` schedule"}),t.allow_unbounded!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["allow_unbounded"],message:"allow_unbounded is not valid on a `once` schedule"}),!!t.spec.fire_at==!!t.spec.delay_seconds&&e.addIssue({code:s.ZodIssueCode.custom,path:["spec","fire_at"],message:"once spec requires exactly one of fire_at or delay_seconds"}))}),kA=s.enum(["pending","firing","active","done","cancelled","failed","all"]),_K=s.object({status:kA.optional(),limit:s.number().int().min(1).max(200).optional()}),yK=s.object({schedule_id:s.string()}),vK=s.object({schedule:El}),bK=s.object({schedules:s.array(El)}),SK=s.object({schedule:El});var RA=s.enum(["online","offline"]),PA=s.object({user_id:s.string(),presence:RA,last_seen_at:s.number().nullable()});var kK=s.object({users:s.array(PA)});var l_=s.enum(["recent","manual"]),d_=s.enum(["starred","dm","regular","unstarred","favorites"]),Cl=s.string().refine(t=>t==="workspaces"||t==="favorites"||t.startsWith("channels:"),{message:"list_key must be 'workspaces', 'favorites', or 'channels:<ws_id>'"}),EA=s.object({entity_id:s.string(),rank:s.number().nullable(),last_accessed_at:s.number().nullable(),starred_at:s.number().nullable()}),p_=s.object({list_key:s.string(),modes:s.record(l_),entries:s.array(EA)}),EK=s.object({list_key:Cl,group:d_.optional(),mode:l_}),CK=s.object({list_key:Cl,group:d_,ordered_ids:s.array(s.string())}),TK=s.object({list_key:Cl,entity_id:s.string()});var CA=s.enum(["workspace","dm"]),TA=s.object({kind:CA,favorite_key:s.string(),entity_id:s.string(),workspace_id:s.string(),title:s.string(),icon_url:s.string().nullable(),runtime:De.nullable(),starred_at:s.number(),created_at:s.number(),unread_count:s.number().nullable()}),OK=s.object({items:s.array(TA),viewer_sort:p_});var va={health:"/api/health",serverInfo:"/api/server/info",runtimes:"/api/runtimes",eventWebSocket:"/api/ws/events",presence:"/api/presence",hosts:"/api/hosts",hostConnect:"/api/hosts/connect",hostConnectTokenResolve:"/api/hosts/connect-token/resolve",hostClaimOrCreate:"/api/hosts/claim-or-create",hostRevoke:t=>`/api/hosts/${t}/revoke`,hostRotateToken:t=>`/api/hosts/${t}/rotate-token`,hostRotateConnectToken:t=>`/api/hosts/${t}/connect-token/rotate`,hostDisconnect:t=>`/api/hosts/${t}/disconnect`,host:t=>`/api/hosts/${t}`,hostDelete:t=>`/api/hosts/${t}`,hostCancelPending:t=>`/api/hosts/${t}`,hostStatus:t=>`/api/hosts/${t}/status`,hostProxyConfig:t=>`/api/hosts/${t}/proxy-config`,agents:"/api/agents",agent:t=>`/api/agents/${t}`,agentWorkspaceTree:t=>`/api/agents/${t}/workspace/tree`,agentWorkspaceFile:t=>`/api/agents/${t}/workspace/file`,agentProfileMcp:t=>`/api/agents/${t}/profile/mcp`,agentProfileMcpProbe:t=>`/api/agents/${t}/profile/mcp/probe`,agentRuntimeState:t=>`/api/agents/${t}/runtime-state`,agentStop:t=>`/api/agents/${t}/stop`,agentDeleteImpact:t=>`/api/agents/${t}/delete-impact`,agentAvatar:t=>`/api/agents/${t}/avatar`,agentSchedules:t=>`/api/agents/${t}/schedules`,agentScheduleCancel:(t,e)=>`/api/agents/${t}/schedules/${e}/cancel`,workspaces:"/api/workspaces",workspace:t=>`/api/workspaces/${t}`,workspaceStar:t=>`/api/workspaces/${t}/star`,workspaceMembers:t=>`/api/workspaces/${t}/members`,workspaceMember:(t,e)=>`/api/workspaces/${t}/members/${e}`,workspaceHumanMember:(t,e)=>`/api/workspaces/${t}/members/users/${e}`,workspaceHumanMemberRole:(t,e)=>`/api/workspaces/${t}/members/users/${e}/role`,workspaceAgentCapabilities:(t,e)=>`/api/workspaces/${t}/agents/${e}/capabilities`,workspaceChannels:t=>`/api/workspaces/${t}/channels`,workspaceArchivedChannels:t=>`/api/workspaces/${t}/channels/archived`,archivedChannels:"/api/archived-channels",sortMode:"/api/sort/mode",sortOrder:"/api/sort/order",sortTouch:"/api/sort/touch",channelStar:t=>`/api/channels/${t}/star`,channelMessages:t=>`/api/channels/${t}/messages`,channelThreadFollowers:(t,e)=>`/api/channels/${t}/threads/${e}/followers`,channelThreadFollow:(t,e)=>`/api/channels/${t}/threads/${e}/follow`,channelAgents:t=>`/api/channels/${t}/agents`,channelAgentStart:(t,e)=>`/api/channels/${t}/agents/${e}/start`,channelAgentStop:(t,e)=>`/api/channels/${t}/agents/${e}/stop`,channelAgentClearSession:(t,e)=>`/api/channels/${t}/agents/${e}/clear-session`,channelAgentRunStates:t=>`/api/channels/${t}/agent-run-states`,channelClose:t=>`/api/channels/${t}/close`,channelStop:t=>`/api/channels/${t}/stop`,channelResume:t=>`/api/channels/${t}/resume`,channelArchive:t=>`/api/channels/${t}/archive`,conversationChannel:t=>`/api/channels/${t}`,conversationChannelMessages:t=>`/api/channels/${t}/messages`,conversationChannelAgents:t=>`/api/channels/${t}/agents`,conversationRef:t=>`/api/conversations/${t}/ref`,conversationThreads:t=>`/api/conversations/${t}/threads`,conversationUnread:t=>`/api/conversations/${t}/unread`,conversationAttentionPreference:t=>`/api/conversations/${t}/attention-preference`,activity:"/api/activity",favorites:"/api/favorites",attentionObserve:"/api/attention/observe",conversationLogDebug:t=>`/api/conversations/${t}/log-debug`,conversationAgentActivity:(t,e)=>`/api/conversations/${t}/agents/${e}/activity`,conversationMembers:t=>`/api/conversations/${t}/members`,conversationAgentMember:(t,e)=>`/api/conversations/${t}/members/agents/${e}`,channelAttachments:t=>`/api/channels/${t}/attachments`,attachment:t=>`/api/attachments/${t}`,messageUnreadSummary:"/api/message-unread-summary",saved:"/api/saved",search:"/api/search",messageSave:t=>`/api/messages/${t}/save`,messageReactions:t=>`/api/messages/${t}/reactions`,message:t=>`/api/messages/${t}`,users:"/api/users",me:"/api/me",meAvatar:"/api/me/avatar",userAvatar:t=>`/api/users/${t}/avatar`,notifications:"/api/notifications",notificationsUnread:"/api/notifications/unread",notificationsRead:"/api/notifications/read",tasks:"/api/tasks",taskClaim:t=>`/api/tasks/${t}/claim`,taskUnclaim:t=>`/api/tasks/${t}/unclaim`,taskStatus:t=>`/api/tasks/${t}/status`};var Tl={agentSendConversationMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/send-message`,agentResolveStaleMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/stale-message-resolution`,agentCreateChannel:(t,e)=>`/internal/conversations/${t}/agents/${e}/create-channel`,agentReadHistory:(t,e)=>`/internal/conversations/${t}/agents/${e}/read-history`,agentFollowThread:(t,e)=>`/internal/conversations/${t}/agents/${e}/follow-thread`,agentUnfollowThread:(t,e)=>`/internal/conversations/${t}/agents/${e}/unfollow-thread`,agentListWorkspaces:(t,e)=>`/internal/conversations/${t}/agents/${e}/list-workspaces`,agentListChannels:(t,e)=>`/internal/conversations/${t}/agents/${e}/list-channels`,agentSearchMessages:(t,e)=>`/internal/conversations/${t}/agents/${e}/search-messages`,agentAddConversationMember:(t,e)=>`/internal/conversations/${t}/agents/${e}/members`,agentReactMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/react-message`,agentListConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks`,agentCreateConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/create`,agentClaimConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/claim`,agentUnclaimConversationTask:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/unclaim`,agentUpdateConversationTaskStatus:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/update-status`,agentScheduleCreate:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules`,agentScheduleList:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules/list`,agentScheduleCancel:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules/cancel`,agentUploadAttachment:(t,e)=>`/internal/conversations/${t}/agents/${e}/attachments`,agentLocateAttachment:(t,e,r)=>`/internal/conversations/${t}/agents/${e}/attachments/${r}/locate`,agentDownloadAttachment:(t,e,r)=>`/internal/conversations/${t}/agents/${e}/attachments/${r}/download`,agentUploadAvatar:(t,e)=>`/internal/conversations/${t}/agents/${e}/avatar`,agentDeleteAvatar:(t,e)=>`/internal/conversations/${t}/agents/${e}/avatar`,agentCliTrace:(t,e)=>`/internal/conversations/${t}/agents/${e}/cli-trace`,agentProfileMcpGet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp`,agentProfileMcpSet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp`,agentProfileMcpProbe:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp/probe`,agentProfileGet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile`,agentProfileUpdate:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile`};var AA="wsah_";function Al(t){return`${AA}${t}`}function ba(t,e){return e.length>0&&t===Al(e)}var IA=s.unknown().refine(t=>t!==void 0,{message:"field is required (opaque payload must be present)"}),so=s.discriminatedUnion("kind",[s.object({kind:s.literal("session_init"),sessionId:s.string().min(1)}).strict(),s.object({kind:s.literal("thinking"),text:s.string()}).strict(),s.object({kind:s.literal("text"),text:s.string()}).strict(),s.object({kind:s.literal("tool_call"),name:s.string().min(1),input:IA,toolCallId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("tool_output"),name:s.string().min(1).optional(),toolCallId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("turn_end"),sessionId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("compaction_started")}).strict(),s.object({kind:s.literal("compaction_finished")}).strict(),s.object({kind:s.literal("error"),message:s.string(),code:s.string().optional(),fatal:s.boolean().optional()}).strict(),s.object({kind:s.literal("unknown"),raw:s.string()}).strict()]),$A=["session_init","thinking","text","tool_call","tool_output","turn_end","compaction_started","compaction_finished","error","unknown"],Sa=s.enum($A);var zA=s.enum(["embedded","remote"]),OA=s.object({max_concurrent_per_parent:s.number().int().positive().nullable().default(null),spawn_cooldown_seconds:s.number().int().nonnegative().nullable().default(null),max_depth:s.literal(1).default(1)}),p6=s.object({mode:zA,url:s.string().url(),auth_token:s.string().min(16).optional(),event_ws_allowed_origins:s.array(s.string().url()).optional(),refresh_token:s.string().nullable().default(null),child_sessions:OA.default({max_concurrent_per_parent:null,spawn_cooldown_seconds:null,max_depth:1})});var Il="daemon-config.json";var m_="authorization",xa=s.object({server_url:s.string().url(),host_id:s.string().min(1),host_token:s.string().min(1),allow_insecure_remote:s.boolean().optional(),profile_version:s.number().int().nonnegative().optional()}).strict(),f_="SILVERHAND_CONVERSATION_ID",h_="SILVERHAND_AGENT_ID",g_="SILVERHAND_SERVER_URL",__="SILVERHAND_AUTH_TOKEN",y_="SILVERHAND_LAST_DELIVERED_SEQ_FILE",v_="SILVERHAND_DAEMON_SOCKET",DA="SILVERHAND_ALLOW_INSECURE_REMOTE";function b_(t=process.env){return t[DA]==="1"}var $l="SILVERHAND_LOG_LEVEL",S_=["error","warn","info","debug"],MA="warn";var x_=["payload","chunk","body","text","prompt","line","env","stdout","stderr","soft_directive"],w_=["env_"];function zl(t){return t==="error"||t==="warn"||t==="info"||t==="debug"?t:MA}function Ol(t){let{value:e,redacted:r}=R_(t,new WeakSet);return r>0&&(e.redactedFieldCount=r),e}function k_(t,e){if(Array.isArray(t)){if(e.has(t))return{value:"[Circular]",redacted:0};e.add(t);let r=0,n=t.map(o=>{let i=k_(o,e);return r+=i.redacted,i.value});return e.delete(t),{value:n,redacted:r}}return jA(t)?R_(t,e):{value:t,redacted:0}}function R_(t,e){if(e.has(t))return{value:{_circular:!0},redacted:0};e.add(t);let r={},n=0;for(let[o,i]of Object.entries(t)){if(NA(o)){n+=1;continue}let a=k_(i,e);r[o]=a.value,n+=a.redacted}return e.delete(t),{value:r,redacted:n}}function NA(t){return x_.includes(t)?!0:w_.some(e=>t.startsWith(e))}function jA(t){if(!t||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Tr="mcp.json",LA=/^[A-Za-z0-9_-]{1,64}$/,FA=s.object({type:s.literal("stdio").optional(),command:s.string().min(1),args:s.array(s.string()).optional(),env:s.record(s.string()).optional()}).strict(),HA=s.object({type:s.enum(["http","sse"]),url:s.string().url(),headers:s.record(s.string()).optional()}).strict(),UA=s.union([FA,HA]),qA=s.object({mcpServers:s.record(UA).default({}).superRefine((t,e)=>{for(let r of Object.keys(t))LA.test(r)||e.addIssue({code:s.ZodIssueCode.custom,message:`invalid MCP server name "${r}": use 1-64 chars of [A-Za-z0-9_-]`,path:["mcpServers",r]})})}).strict(),WA={mcpServers:{}};function io(t){let e=t.trim();if(e.length===0)return{ok:!0,config:WA};let r;try{r=JSON.parse(e)}catch(o){return{ok:!1,error:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}}let n=qA.safeParse(r);if(!n.success){let o=n.error.issues[0];return{ok:!1,error:`invalid MCP config${o?.path.length?` at ${o.path.join(".")}`:""}: ${o?.message??"schema mismatch"}`}}return{ok:!0,config:n.data}}function wa(t,e){return`silverhand_${t}__${e}`}function P_(t,e="profile"){let r=Object.keys(t.mcpServers);if(r.length===0)return null;let n={};for(let o of r)n[wa(e,o)]=t.mcpServers[o];return{mcpServers:n}}function E_(t,e="profile"){let r=[];for(let[n,o]of Object.entries(t.mcpServers)){let i=`mcp_servers.${wa(e,n)}`;r.push(`${i}=${Dl(ZA(o))}`)}return r}function ZA(t){if("url"in t){let r={url:t.url};return t.headers&&(r.http_headers=t.headers),r}let e={command:t.command};return t.args&&(e.args=t.args),t.env&&(e.env=t.env),e}function Dl(t){if(typeof t=="string")return C_(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`cannot serialize non-finite number to TOML: ${t}`);return String(t)}if(Array.isArray(t))return`[${t.map(Dl).join(", ")}]`;if(t!==null&&typeof t=="object"){let e=[];for(let[r,n]of Object.entries(t))n!==void 0&&e.push(`${GA(r)} = ${Dl(n)}`);return`{${e.join(", ")}}`}throw new Error(`cannot serialize value to TOML: ${String(t)}`)}var BA=["parse","not_found","connect","initialize","tools"],VA=s.enum(BA),KA=s.object({name:s.string(),description:s.string().optional()}).strict(),ka=s.object({ok:s.boolean(),phase:VA,message:s.string().optional(),server_info:s.object({name:s.string().optional(),version:s.string().optional()}).strict().optional(),tools:s.array(KA).optional()}).strict(),g6=s.object({server_name:s.string().min(1),include_tools:s.boolean().optional()}).strict();function GA(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:C_(t)}function C_(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var y6=Object.freeze({html:"text/html",htm:"text/html",svg:"image/svg+xml",json:"application/json",md:"text/markdown",markdown:"text/markdown",txt:"text/plain",log:"text/plain",csv:"text/csv",pdf:"application/pdf",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"});var v6=Object.freeze(new Set(["html","htm","pdf","txt","log","md","markdown","json","csv","png","jpg","jpeg","gif","webp"]));var T_={send_message:"`silverhand message send`",react_message:"`silverhand message react`",create_channel:"`silverhand channel create`",list_tasks:"`silverhand task list`",create_tasks:"`silverhand task create`",claim_tasks:"`silverhand task claim`",unclaim_task:"`silverhand task unclaim`",update_task_status:"`silverhand task status`",upload_file:"`silverhand file upload`",view_file:"`silverhand file view`",read_history:"`silverhand message history`",list_workspaces:"`silverhand workspace list`",list_channels:"`silverhand channel list`",search_messages:"`silverhand message search`",add_member:"`silverhand member add`",schedule:"`silverhand schedule create`",list_schedules:"`silverhand schedule list`",cancel_schedule:"`silverhand schedule cancel`"};function JA(t){let e=F=>T_[F],r=e("send_message"),n=e("create_channel"),o=e("add_member"),i=e("list_tasks"),a=e("create_tasks"),c=e("claim_tasks"),u=e("unclaim_task"),l=e("update_task_status"),d=e("upload_file"),p=e("view_file"),m=e("read_history"),f=e("list_workspaces"),_=e("list_channels"),g=e("search_messages"),y=e("schedule"),S=e("list_schedules"),x=e("cancel_schedule"),w=rI(t.sessionContext),T=YA(t.activeProfileDir),v=A_(T,"MEMORY.md"),P=A_(T,"notes"),O=XA({title:"Active Workspace Memory",relPath:v,description:"This is the current workspace's MEMORY.md, auto-loaded for you. Treat it as your recovery index. Edit it to add/update Key Knowledge entries or the current Active Context; keep durable detail in the linked notes/ files.",content:t.currentMemory,missingHint:"No MEMORY.md exists yet. Create one at the path above when you first capture durable knowledge for this workspace."}),J=eI(t.workspaceMemoryIndex);return`You are **@${t.agentName}**, an agent collaborating with humans and
16
+ deps: ${r}}`};var Sq={keyword:"dependencies",type:"object",schemaType:"object",error:rr.error,code(t){let[e,r]=xq(t);HR(t,e),UR(t,r)}};function xq({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function HR(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let a in e){let c=e[a];if(c.length===0)continue;let u=(0,Ti.propertyInData)(r,n,a,o.opts.ownProperties);t.setParams({property:a,depsCount:c.length,deps:c.join(", ")}),o.allErrors?r.if(u,()=>{for(let l of c)(0,Ti.checkReportMissingProp)(t,l)}):(r.if((0,eh._)`${u} && (${(0,Ti.checkMissingProp)(t,c,i)})`),(0,Ti.reportMissingProp)(t,i),r.else())}}rr.validatePropertyDeps=HR;function UR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:i}=t,a=r.name("valid");for(let c in e)(0,bq.alwaysValidSchema)(i,e[c])||(r.if((0,Ti.propertyInData)(r,n,c,i.opts.ownProperties),()=>{let u=t.subschema({keyword:o,schemaProp:c},a);t.mergeValidEvaluated(u,a)},()=>r.var(a,!0)),t.ok(a))}rr.validateSchemaDeps=UR;rr.default=Sq});var ZR=k(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var WR=V(),wq=te(),kq={message:"property name must be valid",params:({params:t})=>(0,WR._)`{propertyName: ${t.propertyName}}`},Rq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kq,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,wq.alwaysValidSchema)(o,r))return;let i=e.name("valid");e.forIn("key",n,a=>{t.setParams({propertyName:a}),t.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},i),e.if((0,WR.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};th.default=Rq});var nh=k(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var Lu=Pt(),Ut=V(),Pq=br(),Fu=te(),Eq={message:"must NOT have additional properties",params:({params:t})=>(0,Ut._)`{additionalProperty: ${t.additionalProperty}}`},Cq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Eq,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:i,it:a}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:u}=a;if(a.props=!0,u.removeAdditional!=="all"&&(0,Fu.alwaysValidSchema)(a,r))return;let l=(0,Lu.allSchemaProperties)(n.properties),d=(0,Lu.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Ut._)`${i} === ${Pq.default.errors}`);function p(){e.forIn("key",o,y=>{!l.length&&!d.length?_(y):e.if(m(y),()=>_(y))})}function m(y){let S;if(l.length>8){let x=(0,Fu.schemaRefOrVal)(a,n.properties,"properties");S=(0,Lu.isOwnProperty)(e,x,y)}else l.length?S=(0,Ut.or)(...l.map(x=>(0,Ut._)`${y} === ${x}`)):S=Ut.nil;return d.length&&(S=(0,Ut.or)(S,...d.map(x=>(0,Ut._)`${(0,Lu.usePattern)(t,x)}.test(${y})`))),(0,Ut.not)(S)}function f(y){e.code((0,Ut._)`delete ${o}[${y}]`)}function _(y){if(u.removeAdditional==="all"||u.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,Fu.alwaysValidSchema)(a,r)){let S=e.name("valid");u.removeAdditional==="failing"?(g(y,S,!1),e.if((0,Ut.not)(S),()=>{t.reset(),f(y)})):(g(y,S),c||e.if((0,Ut.not)(S),()=>e.break()))}}function g(y,S,x){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Fu.Type.Str};x===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,S)}}};rh.default=Cq});var KR=k(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Tq=hi(),BR=Pt(),oh=te(),VR=nh(),Aq={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&VR.default.code(new Tq.KeywordCxt(i,VR.default,"additionalProperties"));let a=(0,BR.allSchemaProperties)(r);for(let p of a)i.definedProperties.add(p);i.opts.unevaluated&&a.length&&i.props!==!0&&(i.props=oh.mergeEvaluated.props(e,(0,oh.toHash)(a),i.props));let c=a.filter(p=>!(0,oh.alwaysValidSchema)(i,r[p]));if(c.length===0)return;let u=e.name("valid");for(let p of c)l(p)?d(p):(e.if((0,BR.propertyInData)(e,o,p,i.opts.ownProperties)),d(p),i.allErrors||e.else().var(u,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(u);function l(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function d(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},u)}}};sh.default=Aq});var XR=k(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var GR=Pt(),Hu=V(),JR=te(),YR=te(),Iq={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:i}=t,{opts:a}=i,c=(0,GR.allSchemaProperties)(r),u=c.filter(g=>(0,JR.alwaysValidSchema)(i,r[g]));if(c.length===0||u.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let l=a.strictSchema&&!a.allowMatchingProperties&&o.properties,d=e.name("valid");i.props!==!0&&!(i.props instanceof Hu.Name)&&(i.props=(0,YR.evaluatedPropsToName)(e,i.props));let{props:p}=i;m();function m(){for(let g of c)l&&f(g),i.allErrors?_(g):(e.var(d,!0),_(g),e.if(d))}function f(g){for(let y in l)new RegExp(g).test(y)&&(0,JR.checkStrictMode)(i,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function _(g){e.forIn("key",n,y=>{e.if((0,Hu._)`${(0,GR.usePattern)(t,g)}.test(${y})`,()=>{let S=u.includes(g);S||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:YR.Type.Str},d),i.opts.unevaluated&&p!==!0?e.assign((0,Hu._)`${p}[${y}]`,!0):!S&&!i.allErrors&&e.if((0,Hu.not)(d),()=>e.break())})})}}};ih.default=Iq});var QR=k(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var $q=te(),zq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,$q.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ah.default=zq});var eP=k(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Oq=Pt(),Dq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Oq.validateUnion,error:{message:"must match a schema in anyOf"}};ch.default=Dq});var tP=k(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var Uu=V(),Mq=te(),Nq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Uu._)`{passingSchemas: ${t.passing}}`},jq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Nq,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,a=e.let("valid",!1),c=e.let("passing",null),u=e.name("_valid");t.setParams({passing:c}),e.block(l),t.result(a,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((d,p)=>{let m;(0,Mq.alwaysValidSchema)(o,d)?e.var(u,!0):m=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},u),p>0&&e.if((0,Uu._)`${u} && ${a}`).assign(a,!1).assign(c,(0,Uu._)`[${c}, ${p}]`).else(),e.if(u,()=>{e.assign(a,!0),e.assign(c,p),m&&t.mergeEvaluated(m,Uu.Name)})})}}};uh.default=jq});var rP=k(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Lq=te(),Fq={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((i,a)=>{if((0,Lq.alwaysValidSchema)(n,i))return;let c=t.subschema({keyword:"allOf",schemaProp:a},o);t.ok(o),t.mergeEvaluated(c)})}};lh.default=Fq});var sP=k(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var qu=V(),oP=te(),Hq={message:({params:t})=>(0,qu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qu._)`{failingKeyword: ${t.ifClause}}`},Uq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Hq,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,oP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=nP(n,"then"),i=nP(n,"else");if(!o&&!i)return;let a=e.let("valid",!0),c=e.name("_valid");if(u(),t.reset(),o&&i){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(c,l("then",d),l("else",d))}else o?e.if(c,l("then")):e.if((0,qu.not)(c),l("else"));t.pass(a,()=>t.error(!0));function u(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);t.mergeEvaluated(d)}function l(d,p){return()=>{let m=t.subschema({keyword:d},c);e.assign(a,c),t.mergeValidEvaluated(m,a),p?e.assign(p,(0,qu._)`${d}`):t.setParams({ifClause:d})}}}};function nP(t,e){let r=t.schema[e];return r!==void 0&&!(0,oP.alwaysValidSchema)(t,r)}dh.default=Uq});var iP=k(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var qq=te(),Wq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,qq.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ph.default=Wq});var aP=k(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var Zq=Gf(),Bq=NR(),Vq=Jf(),Kq=LR(),Gq=FR(),Jq=qR(),Yq=ZR(),Xq=nh(),Qq=KR(),eW=XR(),tW=QR(),rW=eP(),nW=tP(),oW=rP(),sW=sP(),iW=iP();function aW(t=!1){let e=[tW.default,rW.default,nW.default,oW.default,sW.default,iW.default,Yq.default,Xq.default,Jq.default,Qq.default,eW.default];return t?e.push(Bq.default,Kq.default):e.push(Zq.default,Vq.default),e.push(Gq.default),e}mh.default=aW});var cP=k(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var Ee=V(),cW={message:({schemaCode:t})=>(0,Ee.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ee._)`{format: ${t}}`},uW={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:cW,code(t,e){let{gen:r,data:n,$data:o,schema:i,schemaCode:a,it:c}=t,{opts:u,errSchemaPath:l,schemaEnv:d,self:p}=c;if(!u.validateFormats)return;o?m():f();function m(){let _=r.scopeValue("formats",{ref:p.formats,code:u.code.formats}),g=r.const("fDef",(0,Ee._)`${_}[${a}]`),y=r.let("fType"),S=r.let("format");r.if((0,Ee._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,Ee._)`${g}.type || "string"`).assign(S,(0,Ee._)`${g}.validate`),()=>r.assign(y,(0,Ee._)`"string"`).assign(S,g)),t.fail$data((0,Ee.or)(x(),w()));function x(){return u.strictSchema===!1?Ee.nil:(0,Ee._)`${a} && !${S}`}function w(){let T=d.$async?(0,Ee._)`(${g}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,Ee._)`${S}(${n})`,v=(0,Ee._)`(typeof ${S} == "function" ? ${T} : ${S}.test(${n}))`;return(0,Ee._)`${S} && ${S} !== true && ${y} === ${e} && !${v}`}}function f(){let _=p.formats[i];if(!_){x();return}if(_===!0)return;let[g,y,S]=w(_);g===e&&t.pass(T());function x(){if(u.strictSchema===!1){p.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,Ee.regexpCode)(v):u.code.formats?(0,Ee._)`${u.code.formats}${(0,Ee.getProperty)(i)}`:void 0,O=r.scopeValue("formats",{key:i,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ee._)`${O}.validate`]:["string",v,O]}function T(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ee._)`await ${S}(${n})`}return typeof y=="function"?(0,Ee._)`${S}(${n})`:(0,Ee._)`${S}.test(${n})`}}}};fh.default=uW});var uP=k(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var lW=cP(),dW=[lW.default];hh.default=dW});var lP=k(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.contentVocabulary=Jo.metadataVocabulary=void 0;Jo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Jo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var pP=k(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var pW=vR(),mW=zR(),fW=aP(),hW=uP(),dP=lP(),gW=[pW.default,mW.default,(0,fW.default)(),hW.default,dP.metadataVocabulary,dP.contentVocabulary];gh.default=gW});var fP=k(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});Wu.DiscrError=void 0;var mP;(function(t){t.Tag="tag",t.Mapping="mapping"})(mP||(Wu.DiscrError=mP={}))});var gP=k(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var Yo=V(),_h=fP(),hP=Eu(),_W=gi(),yW=te(),vW={message:({params:{discrError:t,tagName:e}})=>t===_h.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Yo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bW={keyword:"discriminator",type:"object",schemaType:"object",error:vW,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:i}=t,{oneOf:a}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",!1),l=e.const("tag",(0,Yo._)`${r}${(0,Yo.getProperty)(c)}`);e.if((0,Yo._)`typeof ${l} == "string"`,()=>d(),()=>t.error(!1,{discrError:_h.DiscrError.Tag,tag:l,tagName:c})),t.ok(u);function d(){let f=m();e.if(!1);for(let _ in f)e.elseIf((0,Yo._)`${l} === ${_}`),e.assign(u,p(f[_]));e.else(),t.error(!1,{discrError:_h.DiscrError.Mapping,tag:l,tagName:c}),e.endIf()}function p(f){let _=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},_);return t.mergeEvaluated(g,Yo.Name),_}function m(){var f;let _={},g=S(o),y=!0;for(let T=0;T<a.length;T++){let v=a[T];if(v?.$ref&&!(0,yW.schemaHasRulesButRef)(v,i.self.RULES)){let O=v.$ref;if(v=hP.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,O),v instanceof hP.SchemaEnv&&(v=v.schema),v===void 0)throw new _W.default(i.opts.uriResolver,i.baseId,O)}let P=(f=v?.properties)===null||f===void 0?void 0:f[c];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);y=y&&(g||S(v)),x(P,T)}if(!y)throw new Error(`discriminator: "${c}" must be required`);return _;function S({required:T}){return Array.isArray(T)&&T.includes(c)}function x(T,v){if(T.const)w(T.const,v);else if(T.enum)for(let P of T.enum)w(P,v);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function w(T,v){if(typeof T!="string"||T in _)throw new Error(`discriminator: "${c}" values must be unique strings`);_[T]=v}}}};yh.default=bW});var _P=k((nre,SW)=>{SW.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var bh=k((be,vh)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var xW=mR(),wW=pP(),kW=gP(),yP=_P(),RW=["/properties"],Zu="http://json-schema.org/draft-07/schema",Xo=class extends xW.default{_addVocabularies(){super._addVocabularies(),wW.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(kW.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(yP,RW):yP;this.addMetaSchema(e,Zu,!1),this.refs["http://json-schema.org/schema"]=Zu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zu)?Zu:void 0)}};be.Ajv=Xo;vh.exports=be=Xo;vh.exports.Ajv=Xo;Object.defineProperty(be,"__esModule",{value:!0});be.default=Xo;var PW=hi();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return PW.KeywordCxt}});var Qo=V();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Qo._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Qo.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Qo.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Qo.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Qo.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return Qo.CodeGen}});var EW=Ru();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return EW.default}});var CW=gi();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return CW.default}})});var PP=k(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.formatNames=or.fastFormats=or.fullFormats=void 0;function nr(t,e){return{validate:t,compare:e}}or.fullFormats={date:nr(xP,kh),time:nr(xh(!0),Rh),"date-time":nr(vP(!0),kP),"iso-time":nr(xh(),wP),"iso-date-time":nr(vP(),RP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:OW,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:HW,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:DW,int32:{type:"number",validate:jW},int64:{type:"number",validate:LW},float:{type:"number",validate:SP},double:{type:"number",validate:SP},password:!0,binary:!0};or.fastFormats={...or.fullFormats,date:nr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,kh),time:nr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Rh),"date-time":nr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,kP),"iso-time":nr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wP),"iso-date-time":nr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,RP),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};or.formatNames=Object.keys(or.fullFormats);function TW(t){return t%4===0&&(t%100!==0||t%400===0)}var AW=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,IW=[0,31,28,31,30,31,30,31,31,30,31,30,31];function xP(t){let e=AW.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&TW(r)?29:IW[n])}function kh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xh(t){return function(r){let n=Sh.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],a=+n[3],c=n[4],u=n[5]==="-"?-1:1,l=+(n[6]||0),d=+(n[7]||0);if(l>23||d>59||t&&!c)return!1;if(o<=23&&i<=59&&a<60)return!0;let p=i-d*u,m=o-l*u-(p<0?1:0);return(m===23||m===-1)&&(p===59||p===-1)&&a<61}}function Rh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function wP(t,e){if(!(t&&e))return;let r=Sh.exec(t),n=Sh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var wh=/t|\s/i;function vP(t){let e=xh(t);return function(n){let o=n.split(wh);return o.length===2&&xP(o[0])&&e(o[1])}}function kP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function RP(t,e){if(!(t&&e))return;let[r,n]=t.split(wh),[o,i]=e.split(wh),a=kh(r,o);if(a!==void 0)return a||Rh(n,i)}var $W=/\/|:/,zW=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function OW(t){return $W.test(t)&&zW.test(t)}var bP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DW(t){return bP.lastIndex=0,bP.test(t)}var MW=-(2**31),NW=2**31-1;function jW(t){return Number.isInteger(t)&&t<=NW&&t>=MW}function LW(t){return Number.isInteger(t)}function SP(){return!0}var FW=/[^\\]\\Z/;function HW(t){if(FW.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var EP=k(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.formatLimitDefinition=void 0;var UW=bh(),qt=V(),Br=qt.operators,Bu={formatMaximum:{okStr:"<=",ok:Br.LTE,fail:Br.GT},formatMinimum:{okStr:">=",ok:Br.GTE,fail:Br.LT},formatExclusiveMaximum:{okStr:"<",ok:Br.LT,fail:Br.GTE},formatExclusiveMinimum:{okStr:">",ok:Br.GT,fail:Br.LTE}},qW={message:({keyword:t,schemaCode:e})=>(0,qt.str)`should be ${Bu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qt._)`{comparison: ${Bu[t].okStr}, limit: ${e}}`};es.formatLimitDefinition={keyword:Object.keys(Bu),type:"string",schemaType:"string",$data:!0,error:qW,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:i}=t,{opts:a,self:c}=i;if(!a.validateFormats)return;let u=new UW.KeywordCxt(i,c.RULES.all.format.definition,"format");u.$data?l():d();function l(){let m=e.scopeValue("formats",{ref:c.formats,code:a.code.formats}),f=e.const("fmt",(0,qt._)`${m}[${u.schemaCode}]`);t.fail$data((0,qt.or)((0,qt._)`typeof ${f} != "object"`,(0,qt._)`${f} instanceof RegExp`,(0,qt._)`typeof ${f}.compare != "function"`,p(f)))}function d(){let m=u.schema,f=c.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let _=e.scopeValue("formats",{key:m,ref:f,code:a.code.formats?(0,qt._)`${a.code.formats}${(0,qt.getProperty)(m)}`:void 0});t.fail$data(p(_))}function p(m){return(0,qt._)`${m}.compare(${r}, ${n}) ${Bu[o].fail} 0`}},dependencies:["format"]};var WW=t=>(t.addKeyword(es.formatLimitDefinition),t);es.default=WW});var IP=k((Ai,AP)=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});var ts=PP(),ZW=EP(),Ph=V(),CP=new Ph.Name("fullFormats"),BW=new Ph.Name("fastFormats"),Eh=(t,e={keywords:!0})=>{if(Array.isArray(e))return TP(t,e,ts.fullFormats,CP),t;let[r,n]=e.mode==="fast"?[ts.fastFormats,BW]:[ts.fullFormats,CP],o=e.formats||ts.formatNames;return TP(t,o,r,n),e.keywords&&(0,ZW.default)(t),t};Eh.get=(t,e="full")=>{let n=(e==="fast"?ts.fastFormats:ts.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function TP(t,e,r,n){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Ph._)`require("ajv-formats/dist/formats").${n}`);for(let a of e)t.addFormat(a,r[a])}AP.exports=Ai=Eh;Object.defineProperty(Ai,"__esModule",{value:!0});Ai.default=Eh});var FP=k((_re,LP)=>{LP.exports=jP;jP.sync=JW;var MP=ue("fs");function GW(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&t.substr(-o.length).toLowerCase()===o)return!0}return!1}function NP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:GW(e,r)}function jP(t,e,r){MP.stat(t,function(n,o){r(n,n?!1:NP(o,t,e))})}function JW(t,e){return NP(MP.statSync(t),t,e)}});var ZP=k((yre,WP)=>{WP.exports=UP;UP.sync=YW;var HP=ue("fs");function UP(t,e,r){HP.stat(t,function(n,o){r(n,n?!1:qP(o,e))})}function YW(t,e){return qP(HP.statSync(t),e)}function qP(t,e){return t.isFile()&&XW(t,e)}function XW(t,e){var r=t.mode,n=t.uid,o=t.gid,i=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),a=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),c=parseInt("100",8),u=parseInt("010",8),l=parseInt("001",8),d=c|u,p=r&l||r&u&&o===a||r&c&&n===i||r&d&&i===0;return p}});var VP=k((bre,BP)=>{var vre=ue("fs"),Yu;process.platform==="win32"||global.TESTING_WINDOWS?Yu=FP():Yu=ZP();BP.exports=Ch;Ch.sync=QW;function Ch(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Ch(t,e||{},function(i,a){i?o(i):n(a)})})}Yu(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function QW(t,e){try{return Yu.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var eE=k((Sre,QP)=>{var rs=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",KP=ue("path"),e2=rs?";":":",GP=VP(),JP=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),YP=(t,e)=>{let r=e.colon||e2,n=t.match(/\//)||rs&&t.match(/\\/)?[""]:[...rs?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=rs?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=rs?o.split(r):[""];return rs&&t.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},XP=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:i}=YP(t,e),a=[],c=l=>new Promise((d,p)=>{if(l===n.length)return e.all&&a.length?d(a):p(JP(t));let m=n[l],f=/^".*"$/.test(m)?m.slice(1,-1):m,_=KP.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+_:_;d(u(g,l,0))}),u=(l,d,p)=>new Promise((m,f)=>{if(p===o.length)return m(c(d+1));let _=o[p];GP(l+_,{pathExt:i},(g,y)=>{if(!g&&y)if(e.all)a.push(l+_);else return m(l+_);return m(u(l,d,p+1))})});return r?c(0).then(l=>r(null,l),r):c(0)},t2=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=YP(t,e),i=[];for(let a=0;a<r.length;a++){let c=r[a],u=/^".*"$/.test(c)?c.slice(1,-1):c,l=KP.join(u,t),d=!u&&/^\.[\\\/]/.test(t)?t.slice(0,2)+l:l;for(let p=0;p<n.length;p++){let m=d+n[p];try{if(GP.sync(m,{pathExt:o}))if(e.all)i.push(m);else return m}catch{}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw JP(t)};QP.exports=XP;XP.sync=t2});var rE=k((xre,Th)=>{"use strict";var tE=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Th.exports=tE;Th.exports.default=tE});var iE=k((wre,sE)=>{"use strict";var nE=ue("path"),r2=eE(),n2=rE();function oE(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(t.options.cwd)}catch{}let a;try{a=r2.sync(t.command,{path:r[n2({env:r})],pathExt:e?nE.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return a&&(a=nE.resolve(o?t.options.cwd:"",a)),a}function o2(t){return oE(t)||oE(t,!0)}sE.exports=o2});var aE=k((kre,Ih)=>{"use strict";var Ah=/([()\][%!^"`<>&|;, *?])/g;function s2(t){return t=t.replace(Ah,"^$1"),t}function i2(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Ah,"^$1"),e&&(t=t.replace(Ah,"^$1")),t}Ih.exports.command=s2;Ih.exports.argument=i2});var uE=k((Rre,cE)=>{"use strict";cE.exports=/^#!(.*)/});var dE=k((Pre,lE)=>{"use strict";var a2=uE();lE.exports=(t="")=>{let e=t.match(a2);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var mE=k((Ere,pE)=>{"use strict";var $h=ue("fs"),c2=dE();function u2(t){let r=Buffer.alloc(150),n;try{n=$h.openSync(t,"r"),$h.readSync(n,r,0,150,0),$h.closeSync(n)}catch{}return c2(r.toString())}pE.exports=u2});var _E=k((Cre,gE)=>{"use strict";var l2=ue("path"),fE=iE(),hE=aE(),d2=mE(),p2=process.platform==="win32",m2=/\.(?:com|exe)$/i,f2=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function h2(t){t.file=fE(t);let e=t.file&&d2(t.file);return e?(t.args.unshift(t.file),t.command=e,fE(t)):t.file}function g2(t){if(!p2)return t;let e=h2(t),r=!m2.test(e);if(t.options.forceShell||r){let n=f2.test(e);t.command=l2.normalize(t.command),t.command=hE.command(t.command),t.args=t.args.map(i=>hE.argument(i,n));let o=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${o}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function _2(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:g2(n)}gE.exports=_2});var bE=k((Tre,vE)=>{"use strict";var zh=process.platform==="win32";function Oh(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function y2(t,e){if(!zh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let i=yE(o,e);if(i)return r.call(t,"error",i)}return r.apply(t,arguments)}}function yE(t,e){return zh&&t===1&&!e.file?Oh(e.original,"spawn"):null}function v2(t,e){return zh&&t===1&&!e.file?Oh(e.original,"spawnSync"):null}vE.exports={hookChildProcess:y2,verifyENOENT:yE,verifyENOENTSync:v2,notFoundError:Oh}});var wE=k((Are,ns)=>{"use strict";var SE=ue("child_process"),Dh=_E(),Mh=bE();function xE(t,e,r){let n=Dh(t,e,r),o=SE.spawn(n.command,n.args,n.options);return Mh.hookChildProcess(o,n),o}function b2(t,e,r){let n=Dh(t,e,r),o=SE.spawnSync(n.command,n.args,n.options);return o.error=o.error||Mh.verifyENOENTSync(o.status,n),o}ns.exports=xE;ns.exports.spawn=xE;ns.exports.sync=b2;ns.exports._parse=Dh;ns.exports._enoent=Mh});import{existsSync as gg,mkdirSync as U0,readFileSync as q0,unlinkSync as W0,writeFileSync as Z0}from"node:fs";import{dirname as B0}from"node:path";function _g(t){if(U0(B0(t),{recursive:!0}),gg(t)){let e=vg(t),r=e?Number.parseInt(e.trim(),10):NaN;if(Number.isInteger(r)&&r>0&&V0(r))return{status:"conflict",conflictingPid:r}}return Z0(t,`${process.pid}
17
+ `,{mode:384}),{status:"wrote"}}function ea(t){if(!gg(t))return;let e=vg(t);if((e?Number.parseInt(e.trim(),10):NaN)===process.pid)try{W0(t)}catch{}}function yg(t,e){let r=!1,n=o=>{if(r){t.warn({signal:o},"shutdown already in progress; ignoring signal");return}r=!0,t.info({signal:o},"received shutdown signal"),Promise.resolve(e(`signal:${o}`)).catch(i=>{t.error({err:i.message},"shutdown handler threw")}).finally(()=>{setImmediate(()=>process.exit(0))})};process.on("SIGINT",n),process.on("SIGTERM",n)}function vg(t){try{return q0(t,"utf8")}catch{return null}}function V0(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}import{readFileSync as CZ}from"node:fs";import{dirname as g0,join as TZ}from"node:path";import{homedir as AZ}from"node:os";var s={};Qi(s,{BRAND:()=>vC,DIRTY:()=>Jr,EMPTY_PATH:()=>Y0,INVALID:()=>L,NEVER:()=>nT,OK:()=>Ue,ParseStatus:()=>Oe,Schema:()=>B,ZodAny:()=>Er,ZodArray:()=>ur,ZodBigInt:()=>Xr,ZodBoolean:()=>Qr,ZodBranded:()=>hs,ZodCatch:()=>dn,ZodDate:()=>en,ZodDefault:()=>ln,ZodDiscriminatedUnion:()=>na,ZodEffects:()=>_t,ZodEnum:()=>cn,ZodError:()=>et,ZodFirstPartyTypeKind:()=>H,ZodFunction:()=>sa,ZodIntersection:()=>on,ZodIssueCode:()=>R,ZodLazy:()=>sn,ZodLiteral:()=>an,ZodMap:()=>eo,ZodNaN:()=>ro,ZodNativeEnum:()=>un,ZodNever:()=>It,ZodNull:()=>rn,ZodNullable:()=>Vt,ZodNumber:()=>Yr,ZodObject:()=>tt,ZodOptional:()=>ht,ZodParsedType:()=>$,ZodPipeline:()=>gs,ZodPromise:()=>Cr,ZodReadonly:()=>pn,ZodRecord:()=>oa,ZodSchema:()=>B,ZodSet:()=>to,ZodString:()=>Pr,ZodSymbol:()=>Xn,ZodTransformer:()=>_t,ZodTuple:()=>Bt,ZodType:()=>B,ZodUndefined:()=>tn,ZodUnion:()=>nn,ZodUnknown:()=>cr,ZodVoid:()=>Qn,addIssueToContext:()=>I,any:()=>CC,array:()=>$C,bigint:()=>wC,boolean:()=>Ag,coerce:()=>rT,custom:()=>Eg,date:()=>kC,datetimeRegex:()=>Rg,defaultErrorMap:()=>ir,discriminatedUnion:()=>MC,effect:()=>KC,enum:()=>ZC,function:()=>UC,getErrorMap:()=>Gn,getParsedType:()=>Zt,instanceof:()=>SC,intersection:()=>NC,isAborted:()=>ta,isAsync:()=>Jn,isDirty:()=>ra,isValid:()=>Rr,late:()=>bC,lazy:()=>qC,literal:()=>WC,makeIssue:()=>fs,map:()=>FC,nan:()=>xC,nativeEnum:()=>BC,never:()=>AC,null:()=>EC,nullable:()=>JC,number:()=>Tg,object:()=>zC,objectUtil:()=>xl,oboolean:()=>tT,onumber:()=>eT,optional:()=>GC,ostring:()=>QC,pipeline:()=>XC,preprocess:()=>YC,promise:()=>VC,quotelessJson:()=>K0,record:()=>LC,set:()=>HC,setErrorMap:()=>J0,strictObject:()=>OC,string:()=>Cg,symbol:()=>RC,transformer:()=>KC,tuple:()=>jC,undefined:()=>PC,union:()=>DC,unknown:()=>TC,util:()=>Y,void:()=>IC});var Y;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},t.find=(o,i)=>{for(let a of o)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(Y||(Y={}));var xl;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(xl||(xl={}));var $=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Zt=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var R=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),K0=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),et=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},n={_errors:[]},o=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];r[i]=r[i]||[],r[i].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};et.create=t=>new et(t);var G0=(t,e)=>{let r;switch(t.code){case R.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case R.invalid_union:r="Invalid input";break;case R.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case R.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:r="Invalid function arguments";break;case R.invalid_return_type:r="Invalid function return type";break;case R.invalid_date:r="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case R.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case R.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case R.custom:r="Invalid input";break;case R.invalid_intersection_types:r="Intersection results could not be merged";break;case R.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}},ir=G0;var bg=ir;function J0(t){bg=t}function Gn(){return bg}var fs=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,i=[...r,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)c=l(a,{data:e,defaultError:c}).message;return{...o,path:i,message:c}},Y0=[];function I(t,e){let r=Gn(),n=fs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ir?void 0:ir].filter(o=>!!o)});t.common.issues.push(n)}var Oe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return L;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let i=await o.key,a=await o.value;n.push({key:i,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return L;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),Jr=t=>({status:"dirty",value:t}),Ue=t=>({status:"valid",value:t}),ta=t=>t.status==="aborted",ra=t=>t.status==="dirty",Rr=t=>t.status==="valid",Jn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));var gt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Sg=(t,e)=>{if(Rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new et(t.common.issues);return this._error=r,this._error}}};function W(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,c)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:u??n??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:u??r??c.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Zt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Zt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Zt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Jn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Sg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Rr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Rr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Zt(e)},o=this._parse({data:e,path:n.path,parent:n}),i=await(Jn(o)?o:Promise.resolve(o));return Sg(n,i)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let a=e(o),c=()=>i.addIssue({code:R.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new _t({schema:this,typeName:H.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ht.create(this,this._def)}nullable(){return Vt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ur.create(this)}promise(){return Cr.create(this,this._def)}or(e){return nn.create([this,e],this._def)}and(e){return on.create(this,e,this._def)}transform(e){return new _t({...W(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ln({...W(this._def),innerType:this,defaultValue:r,typeName:H.ZodDefault})}brand(){return new hs({typeName:H.ZodBranded,type:this,...W(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new dn({...W(this._def),innerType:this,catchValue:r,typeName:H.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return gs.create(this,e)}readonly(){return pn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},X0=/^c[^\s-]{8,}$/i,Q0=/^[0-9a-z]+$/,eC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tC=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rC=/^[a-z0-9_-]{21}$/i,nC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oC=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,iC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wl,aC=/^(?:(?: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])$/,cC=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,uC=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,lC=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wg="((\\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])))",mC=new RegExp(`^${wg}$`);function kg(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function fC(t){return new RegExp(`^${kg(t)}$`)}function Rg(t){let e=`${wg}T${kg(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function hC(t,e){return!!((e==="v4"||!e)&&aC.test(t)||(e==="v6"||!e)&&uC.test(t))}function gC(t,e){if(!nC.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function _C(t,e){return!!((e==="v4"||!e)&&cC.test(t)||(e==="v6"||!e)&&lC.test(t))}var Pr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.string,received:i.parsedType}),L}let n=new Oe,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?I(o,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&I(o,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")sC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"email",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")wl||(wl=new RegExp(iC,"u")),wl.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"emoji",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")tC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"uuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")rC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"nanoid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")X0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Q0.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cuid2",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")eC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ulid",code:R.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),I(o,{validation:"url",code:R.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"regex",code:R.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Rg(i).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?mC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?fC(i).test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?oC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"duration",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?hC(e.data,i.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"ip",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?gC(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"jwt",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?_C(e.data,i.version)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?dC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?pC.test(e.data)||(o=this._getOrReturnCtx(e,o),I(o,{validation:"base64url",code:R.invalid_string,message:i.message}),n.dirty()):Y.assertNever(i);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:R.invalid_string,...z.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:H.ZodString,coerce:t?.coerce??!1,...W(t)});function yC(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}var Yr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.number,received:i.parsedType}),L}let n,o=new Oe;for(let i of this._def.checks)i.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?yC(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_finite,message:i.message}),o.dirty()):Y.assertNever(i);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Yr.create=t=>new Yr({checks:[],typeName:H.ZodNumber,coerce:t?.coerce||!1,...W(t)});var Xr=class t extends B{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let n,o=new Oe;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),I(n,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):Y.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return I(r,{code:R.invalid_type,expected:$.bigint,received:r.parsedType}),L}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Xr.create=t=>new Xr({checks:[],typeName:H.ZodBigInt,coerce:t?.coerce??!1,...W(t)});var Qr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.boolean,received:n.parsedType}),L}return Ue(e.data)}};Qr.create=t=>new Qr({typeName:H.ZodBoolean,coerce:t?.coerce||!1,...W(t)});var en=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_type,expected:$.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return I(i,{code:R.invalid_date}),L}let n=new Oe,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),I(o,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Y.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};en.create=t=>new en({checks:[],coerce:t?.coerce||!1,typeName:H.ZodDate,...W(t)});var Xn=class extends B{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.symbol,received:n.parsedType}),L}return Ue(e.data)}};Xn.create=t=>new Xn({typeName:H.ZodSymbol,...W(t)});var tn=class extends B{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.undefined,received:n.parsedType}),L}return Ue(e.data)}};tn.create=t=>new tn({typeName:H.ZodUndefined,...W(t)});var rn=class extends B{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.null,received:n.parsedType}),L}return Ue(e.data)}};rn.create=t=>new rn({typeName:H.ZodNull,...W(t)});var Er=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Ue(e.data)}};Er.create=t=>new Er({typeName:H.ZodAny,...W(t)});var cr=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ue(e.data)}};cr.create=t=>new cr({typeName:H.ZodUnknown,...W(t)});var It=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return I(r,{code:R.invalid_type,expected:$.never,received:r.parsedType}),L}};It.create=t=>new It({typeName:H.ZodNever,...W(t)});var Qn=class extends B{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.void,received:n.parsedType}),L}return Ue(e.data)}};Qn.create=t=>new Qn({typeName:H.ZodVoid,...W(t)});var ur=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==$.array)return I(r,{code:R.invalid_type,expected:$.array,received:r.parsedType}),L;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(a||c)&&(I(r,{code:a?R.too_big:R.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(I(r,{code:R.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(I(r,{code:R.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,c)=>o.type._parseAsync(new gt(r,a,r.path,c)))).then(a=>Oe.mergeArray(n,a));let i=[...r.data].map((a,c)=>o.type._parseSync(new gt(r,a,r.path,c)));return Oe.mergeArray(n,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}};ur.create=(t,e)=>new ur({type:t,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...W(e)});function Yn(t){if(t instanceof tt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ht.create(Yn(n))}return new tt({...t._def,shape:()=>e})}else return t instanceof ur?new ur({...t._def,type:Yn(t.element)}):t instanceof ht?ht.create(Yn(t.unwrap())):t instanceof Vt?Vt.create(Yn(t.unwrap())):t instanceof Bt?Bt.create(t.items.map(e=>Yn(e))):t}var tt=class t extends B{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let l=this._getOrReturnCtx(e);return I(l,{code:R.invalid_type,expected:$.object,received:l.parsedType}),L}let{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||c.push(l);let u=[];for(let l of a){let d=i[l],p=o.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new gt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof It){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")c.length>0&&(I(o,{code:R.unrecognized_keys,keys:c}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of c){let p=o.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new gt(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Oe.mergeObjectSync(n,l)):Oe.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:z.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Yn(this)}partial(e){let r={};for(let n of Y.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ht;)i=i._def.innerType;r[n]=i}return new t({...this._def,shape:()=>r})}keyof(){return Pg(Y.objectKeys(this.shape))}};tt.create=(t,e)=>new tt({shape:()=>t,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...W(e)});tt.strictCreate=(t,e)=>new tt({shape:()=>t,unknownKeys:"strict",catchall:It.create(),typeName:H.ZodObject,...W(e)});tt.lazycreate=(t,e)=>new tt({shape:t,unknownKeys:"strip",catchall:It.create(),typeName:H.ZodObject,...W(e)});var nn=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new et(c.ctx.common.issues));return I(r,{code:R.invalid_union,unionErrors:a}),L}if(r.common.async)return Promise.all(n.map(async i=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of n){let l={...r,common:{...r.common,issues:[]},parent:null},d=u._parseSync({data:r.data,path:r.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(u=>new et(u));return I(r,{code:R.invalid_union,unionErrors:c}),L}}get options(){return this._def.options}};nn.create=(t,e)=>new nn({options:t,typeName:H.ZodUnion,...W(e)});var ar=t=>t instanceof sn?ar(t.schema):t instanceof _t?ar(t.innerType()):t instanceof an?[t.value]:t instanceof cn?t.options:t instanceof un?Y.objectValues(t.enum):t instanceof ln?ar(t._def.innerType):t instanceof tn?[void 0]:t instanceof rn?[null]:t instanceof ht?[void 0,...ar(t.unwrap())]:t instanceof Vt?[null,...ar(t.unwrap())]:t instanceof hs||t instanceof pn?ar(t.unwrap()):t instanceof dn?ar(t._def.innerType):[],na=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return I(r,{code:R.invalid_type,expected:$.object,received:r.parsedType}),L;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(I(r,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let i of r){let a=ar(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,i)}}return new t({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...W(n)})}};function kl(t,e){let r=Zt(t),n=Zt(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&n===$.object){let o=Y.objectKeys(e),i=Y.objectKeys(t).filter(c=>o.indexOf(c)!==-1),a={...t,...e};for(let c of i){let u=kl(t[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(r===$.array&&n===$.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let a=t[i],c=e[i],u=kl(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return r===$.date&&n===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var on=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(i,a)=>{if(ta(i)||ta(a))return L;let c=kl(i.value,a.value);return c.valid?((ra(i)||ra(a))&&r.dirty(),{status:r.value,value:c.data}):(I(n,{code:R.invalid_intersection_types}),L)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};on.create=(t,e,r)=>new on({left:t,right:e,typeName:H.ZodIntersection,...W(r)});var Bt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return I(n,{code:R.invalid_type,expected:$.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return I(n,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new gt(n,a,n.path,c)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>Oe.mergeArray(r,a)):Oe.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Bt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bt({items:t,typeName:H.ZodTuple,rest:null,...W(e)})};var oa=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return I(n,{code:R.invalid_type,expected:$.object,received:n.parsedType}),L;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in n.data)o.push({key:i._parse(new gt(n,c,n.path,c)),value:a._parse(new gt(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?Oe.mergeObjectAsync(r,o):Oe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:H.ZodRecord,...W(n)}):new t({keyType:Pr.create(),valueType:e,typeName:H.ZodRecord,...W(r)})}},eo=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return I(n,{code:R.invalid_type,expected:$.map,received:n.parsedType}),L;let o=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([c,u],l)=>({key:o._parse(new gt(n,c,n.path,[l,"key"])),value:i._parse(new gt(n,u,n.path,[l,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return L;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(l.value,d.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let u of a){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return L;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),c.set(l.value,d.value)}return{status:r.value,value:c}}}};eo.create=(t,e,r)=>new eo({valueType:e,keyType:t,typeName:H.ZodMap,...W(r)});var to=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return I(n,{code:R.invalid_type,expected:$.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(I(n,{code:R.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(I(n,{code:R.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let d of u){if(d.status==="aborted")return L;d.status==="dirty"&&r.dirty(),l.add(d.value)}return{status:r.value,value:l}}let c=[...n.data.values()].map((u,l)=>i._parse(new gt(n,u,n.path,l)));return n.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,r){return new t({...this._def,minSize:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};to.create=(t,e)=>new to({valueType:t,minSize:null,maxSize:null,typeName:H.ZodSet,...W(e)});var sa=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return I(r,{code:R.invalid_type,expected:$.function,received:r.parsedType}),L;function n(c,u){return fs({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Gn(),ir].filter(l=>!!l),issueData:{code:R.invalid_arguments,argumentsError:u}})}function o(c,u){return fs({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Gn(),ir].filter(l=>!!l),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Cr){let c=this;return Ue(async function(...u){let l=new et([]),d=await c._def.args.parseAsync(u,i).catch(f=>{throw l.addIssue(n(u,f)),l}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,i).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let c=this;return Ue(function(...u){let l=c._def.args.safeParse(u,i);if(!l.success)throw new et([n(u,l.error)]);let d=Reflect.apply(a,this,l.data),p=c._def.returns.safeParse(d,i);if(!p.success)throw new et([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Bt.create(e).rest(cr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Bt.create([]).rest(cr.create()),returns:r||cr.create(),typeName:H.ZodFunction,...W(n)})}},sn=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};sn.create=(t,e)=>new sn({getter:t,typeName:H.ZodLazy,...W(e)});var an=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return I(r,{received:r.data,code:R.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};an.create=(t,e)=>new an({value:t,typeName:H.ZodLiteral,...W(e)});function Pg(t,e){return new cn({values:t,typeName:H.ZodEnum,...W(e)})}var cn=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{expected:Y.joinValues(n),received:r.parsedType,code:R.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{received:r.data,code:R.invalid_enum_value,options:n}),L}return Ue(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};cn.create=Pg;var un=class extends B{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let o=Y.objectValues(r);return I(n,{expected:Y.joinValues(o),received:n.parsedType,code:R.invalid_type}),L}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return I(n,{received:n.data,code:R.invalid_enum_value,options:o}),L}return Ue(e.data)}get enum(){return this._def.values}};un.create=(t,e)=>new un({values:t,typeName:H.ZodNativeEnum,...W(e)});var Cr=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return I(r,{code:R.invalid_type,expected:$.promise,received:r.parsedType}),L;let n=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return Ue(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cr.create=(t,e)=>new Cr({type:t,typeName:H.ZodPromise,...W(e)});var _t=class extends B{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:a=>{I(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async c=>{if(r.value==="aborted")return L;let u=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return u.status==="aborted"?L:u.status==="dirty"?Jr(u.value):r.value==="dirty"?Jr(u.value):u});{if(r.value==="aborted")return L;let c=this._def.schema._parseSync({data:a,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Jr(c.value):r.value==="dirty"?Jr(c.value):c}}if(o.type==="refinement"){let a=c=>{let u=o.refinement(c,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?L:(c.status==="dirty"&&r.dirty(),a(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?L:(c.status==="dirty"&&r.dirty(),a(c.value).then(()=>({status:r.value,value:c.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Rr(a))return L;let c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Rr(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:r.value,value:c})):L);Y.assertNever(o)}};_t.create=(t,e,r)=>new _t({schema:t,typeName:H.ZodEffects,effect:e,...W(r)});_t.createWithPreprocess=(t,e,r)=>new _t({schema:e,effect:{type:"preprocess",transform:t},typeName:H.ZodEffects,...W(r)});var ht=class extends B{_parse(e){return this._getType(e)===$.undefined?Ue(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ht.create=(t,e)=>new ht({innerType:t,typeName:H.ZodOptional,...W(e)});var Vt=class extends B{_parse(e){return this._getType(e)===$.null?Ue(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vt.create=(t,e)=>new Vt({innerType:t,typeName:H.ZodNullable,...W(e)});var ln=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ln.create=(t,e)=>new ln({innerType:t,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var dn=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Jn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new et(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new et(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};dn.create=(t,e)=>new dn({innerType:t,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var ro=class extends B{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return I(n,{code:R.invalid_type,expected:$.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};ro.create=t=>new ro({typeName:H.ZodNaN,...W(t)});var vC=Symbol("zod_brand"),hs=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},gs=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(r.dirty(),Jr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:H.ZodPipeline})}},pn=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Rr(o)&&(o.value=Object.freeze(o.value)),o);return Jn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};pn.create=(t,e)=>new pn({innerType:t,typeName:H.ZodReadonly,...W(e)});function xg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Eg(t,e={},r){return t?Er.create().superRefine((n,o)=>{let i=t(n);if(i instanceof Promise)return i.then(a=>{if(!a){let c=xg(e,n),u=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:u})}});if(!i){let a=xg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}}):Er.create()}var bC={object:tt.lazycreate},H;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(H||(H={}));var SC=(t,e={message:`Input not instance of ${t.name}`})=>Eg(r=>r instanceof t,e),Cg=Pr.create,Tg=Yr.create,xC=ro.create,wC=Xr.create,Ag=Qr.create,kC=en.create,RC=Xn.create,PC=tn.create,EC=rn.create,CC=Er.create,TC=cr.create,AC=It.create,IC=Qn.create,$C=ur.create,zC=tt.create,OC=tt.strictCreate,DC=nn.create,MC=na.create,NC=on.create,jC=Bt.create,LC=oa.create,FC=eo.create,HC=to.create,UC=sa.create,qC=sn.create,WC=an.create,ZC=cn.create,BC=un.create,VC=Cr.create,KC=_t.create,GC=ht.create,JC=Vt.create,YC=_t.createWithPreprocess,XC=gs.create,QC=()=>Cg().optional(),eT=()=>Tg().optional(),tT=()=>Ag().optional(),rT={string:(t=>Pr.create({...t,coerce:!0})),number:(t=>Yr.create({...t,coerce:!0})),boolean:(t=>Qr.create({...t,coerce:!0})),bigint:(t=>Xr.create({...t,coerce:!0})),date:(t=>en.create({...t,coerce:!0}))};var nT=L;var De=s.enum(["claude","codex","cursor","gemini","qoder"]),no=s.enum(["none","low","medium","high","xhigh","max"]),ia=s.boolean(),aa=s.enum(["local","remote"]),Ig=s.enum(["app_install","user_invite","system"]),hB=s.enum(["long_lived","bootstrap"]),Kt=s.enum(["regular","agent_home"]),yt=s.enum(["channel","dm_channel"]),$g=s.enum(["starting","active","idle","archived","crashed"]),ca=s.enum(["idle","starting","active","crashed"]),ua=s.enum(["user","agent","system"]),$t=s.enum(["todo","in_progress","in_review","done","closed"]),zg=s.enum(["agent","user"]),Og=s.enum(["session_init","thinking","text","tool_call","tool_output","file_change","shell","stderr","compaction_started","compaction_finished","turn_end","error","unknown","parsed_event_dropped"]),Dg=s.enum(["pending_materialization","active","failed"]),Mg=["read_messages","send_messages","read_tasks","create_tasks","write_tasks","read_attachments","upload_attachments","create_threads","create_channels","manage_conversation_members","manage_schedules"],Ng=s.enum(["local","s3","oss"]),jg=s.enum(["user","agent"]),Lg=s.enum(["mention_external","mention_self","agent_start_failed"]);var oT=s.enum(["pending","attached","active","revoked"]),Gt=s.object({id:s.string(),name:s.string(),kind:aa,created_at:s.number(),revoked_at:s.number().nullable(),last_seen_at:s.number().nullable(),activated_at:s.number().nullable().optional().default(null),finalized_at:s.number().nullable().optional().default(null),connected_host_name:s.string().nullable().optional().default(null),provisioning_source:Ig.optional().default("system"),status:oT.optional().default("pending"),placeable:s.boolean().optional().default(!1),creator_user_id:s.string().nullable().optional().default(null),display_label:s.string().nullable()}),vB=s.object({display_label:s.string().max(256).nullable()}).strict(),bB=s.object({host:Gt}),SB=s.enum(["available","disconnected","unreachable","revoked"]);var Fg="host_revoked",Hg="host_disconnected",xB=s.object({host_id:s.string()}).strict(),sT=s.enum(["daemon_unreachable","timeout","protocol_error"]),la=s.object({agent_id:s.string(),display_name:s.string(),handle:s.string(),runtime:s.string(),avatar_url:s.string().nullable().optional().default(null),online:s.enum(["online","offline"])}),iT=s.object({os:s.string().min(1),os_arch:s.string().optional(),daemon_version:s.string(),daemon_pid:s.number().int(),started_at:s.number().int(),uptime_ms:s.number().int()}),aT=s.object({host_id:s.string(),availability:s.literal("available"),snapshot:iT,agents:s.array(la),last_seen_at:s.number().nullable().optional()}).strict(),cT=s.object({host_id:s.string(),availability:s.literal("disconnected"),agents:s.array(la),last_seen_at:s.number().nullable().optional()}).strict(),uT=s.object({host_id:s.string(),availability:s.literal("unreachable"),reason:sT,agents:s.array(la),last_seen_at:s.number().nullable().optional()}).strict(),lT=s.object({host_id:s.string(),availability:s.literal("revoked"),agents:s.array(la),last_seen_at:s.number().nullable().optional()}).strict(),wB=s.discriminatedUnion("availability",[aT,cT,uT,lT]),Rl=s.object({proxy_url:s.string().nullable(),proxy_runtimes:s.array(De)}),kB=s.object({config:Rl}).strict(),dT="computer_offline",RB=s.object({error:s.string(),error_code:s.literal(dT)}).strict(),PB=s.object({installation_id:s.string().uuid(),label:s.string().trim().min(1).max(128).optional(),current_host_id:s.string().min(1).optional()}).strict(),EB=s.object({host_id:s.string(),host:Gt,server_url:s.string().url(),host_token:s.string().min(1).optional()}),CB=s.object({hosts:s.array(Gt)}),TB=s.object({}).strict(),AB=s.object({host_id:s.string(),host:Gt,server_url:s.string().url(),connect_token:s.string().min(1),daemon_command:s.string().min(1)}),IB=s.object({host_id:s.string().min(1)}),$B=s.object({host:Gt}),zB=s.object({host_id:s.string(),deleted:s.literal(!0)});var pT=s.object({agents:s.number().int().nonnegative(),workspaces:s.number().int().nonnegative()}),OB=s.object({error:s.string(),error_code:s.literal("has_dependents"),dependents:pT}),DB=s.object({host:Gt}),mT=s.object({host_id:s.string(),host:Gt,host_token:s.string().min(1)}),fT=s.object({host_id:s.string(),host:Gt,status:s.literal("rotated")}),hT=s.object({host_id:s.string(),host:Gt,status:s.literal("rotated"),connect_token:s.string().min(1),daemon_command:s.string().min(1)}),MB=s.object({host_id:s.string(),host:Gt,disconnected:s.boolean()}),NB=s.union([mT,fT,hT]);var _s=s.object({id:s.string(),name:s.string(),display_name:s.string(),avatar_url:s.string().nullable(),created_at:s.number(),updated_at:s.number()}),FB=s.object({users:s.array(_s)}),gT=s.object({registration_required:s.literal(!0),suggested_name:s.string()}),HB=s.union([_s,gT]),_T=/[\x00-\x1F\x7F-\x9F\u2028\u2029]/,yT="display_name must not contain control characters or Unicode line separators",ys=s.string().trim().min(1).max(64).refine(t=>!_T.test(t),{message:yT}),Ug=s.string().trim().email().max(320),UB=s.object({email:Ug,password:s.string().min(8).max(1024),display_name:ys.optional()}),qB=s.object({email:Ug,password:s.string().min(1).max(1024)}),WB=s.object({user_token:s.string().min(1),user:_s}),ZB=s.object({ok:s.literal(!0)}),BB=s.object({display_name:ys.optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),VB=s.object({avatar_url:s.string()});var vT=s.enum(["loopback","lan","public"]),JB=s.object({signup_enabled:s.boolean(),bind_address_scope:vT.optional()});var qg={claude:{kind:"claude",label:"Claude",cliLabel:"Claude Code",selectable:!0,reasoningEffortOptions:[],supportsProfileMcp:!0,modelSuggestions:[]},codex:{kind:"codex",label:"Codex",cliLabel:"Codex CLI",selectable:!0,reasoningEffortOptions:["low","medium","high","xhigh"],supportsProfileMcp:!0,modelSuggestions:[]},qoder:{kind:"qoder",label:"Qoder",cliLabel:"Qoder",selectable:!0,reasoningEffortOptions:["none","low","medium","high","xhigh","max"],supportsProfileMcp:!0,modelSuggestions:["Auto","Ultimate","Performance","Efficient","Lite"],defaultModel:"Ultimate"},cursor:{kind:"cursor",label:"Cursor",cliLabel:"Cursor",selectable:!1,reasoningEffortOptions:[],supportsProfileMcp:!1,modelSuggestions:[]},gemini:{kind:"gemini",label:"Gemini",cliLabel:"Gemini",selectable:!1,reasoningEffortOptions:[],supportsProfileMcp:!1,modelSuggestions:[]}},bT=["claude","codex","qoder","cursor","gemini"],Wg=bT.map(t=>qg[t]);function Zg(t,e){return e==null?!0:qg[t].reasoningEffortOptions.includes(e)}var Bg=s.object({id:s.string(),name:s.string(),display_name:s.string(),runtime:De,model:s.string().nullable(),reasoning_effort:no.nullable(),fast_mode:ia.nullable(),host_id:s.string(),description:s.string().nullable(),created_by_user_id:s.string(),avatar_url:s.string().nullable(),materialization_status:Dg,materialization_failed_code:s.string().nullable(),materialization_failed_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),o9=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),runtime:De,model:s.string().optional(),reasoning_effort:no.optional(),fast_mode:ia.optional(),host_id:s.string().optional(),description:s.string().optional()}).superRefine((t,e)=>{Zg(t.runtime,t.reasoning_effort)||e.addIssue({code:s.ZodIssueCode.custom,path:["reasoning_effort"],message:`reasoning_effort '${t.reasoning_effort}' is not valid for runtime '${t.runtime}'`})}),s9=s.object({display_name:ys.optional(),description:s.string().max(2e3).nullable().optional(),runtime:s.never().optional(),model:s.string().nullable().optional(),reasoning_effort:no.nullable().optional(),fast_mode:ia.nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),i9=s.object({id:s.string(),name:s.string(),display_name:s.string(),description:s.string().nullable(),avatar_url:s.string().nullable()}),a9=s.object({display_name:ys.optional(),description:s.string().max(2e3).nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),c9=s.object({agent_id:s.string()}),ST=s.object({path:s.string().min(1),kind:s.enum(["file","directory"]),size:s.number(),mtime:s.number()}).strict(),Vg=s.object({nodes:s.array(ST)}).strict(),Kg=s.object({path:s.string().min(1),content:s.string(),size:s.number(),mtime:s.number(),truncated:s.boolean()}).strict(),Gg=s.object({conversation_id:s.string(),workspace_id:s.string(),workspace_name:s.string(),workspace_kind:Kt,conversation_kind:yt,channel_id:s.string(),channel_title:s.string(),status:ca,pid:s.number().nullable(),closed_at:s.number().nullable()}),u9=s.object({conversation_agents:s.array(Gg)}),l9=s.object({agent_id:s.string(),agent_name:s.string(),agent_display_name:s.string(),dm_channel:s.object({id:s.string(),name:s.string(),conversation_count:s.number(),message_count:s.number()}).nullable(),regular_workspaces:s.array(s.object({id:s.string(),name:s.string()})),regular_memberships:s.array(s.object({id:s.string(),name:s.string()})),owned_home:s.object({id:s.string(),name:s.string(),workspace_kind:Kt,owner_agent_id:s.string().nullable()}).nullable(),attachments_count:s.number(),running_conversation_agents:s.array(Gg),pending_inbox_count:s.number()}),d9=s.object({confirm:s.literal(!0)});var _9=s.object({id:s.string(),name:s.string(),description:s.string().nullable(),workspace_kind:Kt,workspace_path:s.string(),workspace_host_id:s.string(),owner_agent_id:s.string().nullable(),owner_user_id:s.string().nullable(),dm_channel_id:s.string().nullable(),dm_channel_ids:s.array(s.string()),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),y9=s.object({workspace_id:s.string(),agent_id:s.string(),joined_at:s.number()}),da=s.enum(["owner","admin","member"]),xT=s.object({workspace_id:s.string(),user_id:s.string(),joined_at:s.number(),role:da}),Jg=_s.extend({workspace_id:s.string(),user_id:s.string(),joined_at:s.number(),role:da}),vs=s.enum(Mg),v9=s.object({workspace_id:s.string(),agent_id:s.string(),capabilities:s.array(vs)}),b9=s.object({capabilities:s.array(vs)}),S9=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),description:s.string().optional(),workspace_path:s.string().optional(),workspace_host_id:s.string().optional(),member_agent_ids:s.array(s.string()).default([]),member_user_ids:s.array(s.string()).default([])}),x9=s.object({name:s.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore").optional(),description:s.string().nullable().optional()}).refine(t=>Object.keys(t).length>0,{message:"no fields to update"}),w9=s.object({archived:s.boolean()}),wT=s.object({agent_id:s.string()}),kT=s.object({kind:s.literal("agent"),agent_id:s.string()}),RT=s.object({kind:s.literal("human"),user_id:s.string()}),k9=s.union([kT,RT,wT]),R9=s.object({role:da}),P9=s.object({member:xT,human_member:Jg}),E9=s.object({members:s.array(Bg),human_members:s.array(Jg),viewer_role:da.nullable()});var Yg=s.object({id:s.string(),workspace_id:s.string(),workspace_path:s.string(),kind:yt,title:s.string(),status:$g,spawned_by_agent_id:s.string().nullable(),closed_at:s.number().nullable(),close_summary:s.string().nullable(),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()}),PT=Yg.extend({kind:s.literal("channel")}),ET=Yg.extend({kind:s.literal("dm_channel")}),Xg=s.string().trim().min(1).max(128),I9=s.object({title:Xg,member_agent_ids:s.array(s.string()).default([]),member_user_ids:s.array(s.string()).optional()}),CT=s.enum(["regular","dm"]),TT=s.object({id:s.string(),kind:yt,title:s.string(),workspace_id:s.string(),workspace_kind:CT,workspace_path:s.string(),closed_at:s.number().nullable(),archived_at:s.number().nullable()}),$9=s.object({ref:TT}),z9=s.object({conversation_id:s.string(),agent_id:s.string(),cli_session_id:s.string().nullable(),pid:s.number().nullable(),status:ca,joined_at:s.number()}),O9=s.object({conversation_id:s.string(),user_id:s.string(),joined_at:s.number()}),AT=s.object({kind:s.literal("agent"),agent_id:s.string(),name:s.string(),display_name:s.string(),runtime:De}),IT=s.object({kind:s.literal("human"),user_id:s.string(),name:s.string(),display_name:s.string(),avatar_url:s.string().nullable()}),Pl=s.discriminatedUnion("kind",[AT,IT]),D9=s.object({members:s.array(Pl)}),$T=s.string().trim().regex(/^@?[a-zA-Z0-9_-]{1,64}$/,{message:"handle must be @optional alphanumeric / dash / underscore"}),zT=s.discriminatedUnion("kind",[s.object({kind:s.literal("agent"),agent_id:s.string()}),s.object({kind:s.literal("human"),user_id:s.string()})]),OT=s.object({handle:$T}),M9=s.union([zT,OT]),N9=s.object({ok:s.literal(!0),prev_cli_session_id:s.string().nullable(),was_running:s.boolean()}),DT=s.record(s.string(),s.unknown()).nullable(),MT=s.object({id:s.number().int(),conversation_id:s.string(),agent_id:s.string().nullable(),kind:Og,payload:DT,created_at:s.number().int()}),j9=s.object({events:s.array(MT),next_before_id:s.number().int().nullable()});var NT=s.union([PT,ET]),L9=s.object({archived:s.boolean()}),F9=s.object({title:Xg}),H9=s.object({workspace_id:s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().optional()),since:s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional())}),jT=s.object({channel:NT,workspace:s.object({id:s.string(),name:s.string(),archived_at:s.number().nullable()})}),U9=s.object({channels:s.array(jT)});var LT=s.enum(["starting","thinking","tool_running","idle","failed"]),FT=s.enum(["replied","turn_ended","replaced","stopped","crashed","timeout","conversation_closed"]),oo=s.object({runId:s.string(),agentId:s.string(),conversationId:s.string(),status:LT,startedAt:s.number(),updatedAt:s.number(),lastActivityAt:s.number(),terminalReason:FT.optional(),activitySnippet:s.string().optional(),toolCallCounts:s.record(s.string(),s.number()).optional(),compacting:s.boolean().optional(),compactingSince:s.number().optional(),compactionStale:s.boolean().optional(),detail:s.string().optional()});var B9=s.object({states:s.array(oo)}),HT=s.enum(["present","present_unverified","absent","unknown"]),UT=s.enum(["resolved","version_unavailable","not_found","probe_failed"]),qT=s.object({kind:De,state:HT,reason:UT,installed:s.boolean(),binary:s.string().nullable(),version:s.string().nullable()}),Qg=s.object({runtimes:s.array(qT),detected_at:s.number()});var J9=s.object({id:s.string(),channel_id:s.string(),source_conversation_id:s.string().nullable(),filename:s.string(),size:s.number(),content_type:s.string(),storage:Ng,created_by_kind:jg,created_by_id:s.string(),created_at:s.number()}),WT=/^(Image|File) #([1-9]\d{0,3})$/,e_=s.string().trim().regex(WT,'label must be "Image #N" or "File #N"');var pa=s.object({id:s.string(),filename:s.string(),size:s.number(),content_type:s.string(),label:e_.optional()}),t_=s.object({id:s.string().min(1),label:e_.optional()});var Y9=s.union([s.object({storage:s.literal("local"),local_path:s.string(),filename:s.string(),content_type:s.string()}),s.object({storage:s.enum(["s3","oss"]),download_url:s.string(),filename:s.string(),content_type:s.string()})]);var r_=s.enum(["user","agent"]),ma=s.object({emoji:s.string(),count:s.number().int().positive(),viewer_reacted:s.boolean()}),ZT=s.object({kind:r_,id:s.string(),display_name:s.string()}),eV=s.object({emoji:s.string(),reactors:s.array(ZT)}),tV=s.object({emoji:s.string()}),rV=s.object({message_id:s.string().min(1),emoji:s.string()}),nV=s.object({message_id:s.string(),conversation_id:s.string(),thread_root_id:s.string().nullable(),emoji:s.string(),op:s.enum(["add","remove"]),reactor_kind:r_,reactor_id:s.string(),count:s.number().int().nonnegative()});var oV=new RegExp("^(?:\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");var Tr=s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().trim().optional()),fa=s.array(s.union([s.string().min(1),t_])).max(20).refine(t=>{let e=t.map(r=>typeof r=="string"?void 0:r.label).filter(r=>r!==void 0);return new Set(e).size===e.length},{message:"attachment labels must be unique within a message"}).optional();function ha(t){return t.content.trim().length>0||(t.attachment_ids?.length??0)>0}var El=s.union([s.object({kind:s.literal("channel")}).strict(),s.object({kind:s.literal("thread"),message_id:s.string().min(1)}).strict()]),BT=s.literal("self"),Cl=s.union([El,BT]),fV=s.enum(["unaffected","revised","obsolete","force_send"]),Tl=s.enum(["unaffected","revised","force_send"]),hV=s.object({content:s.string(),target:Cl.optional(),reply_to_message_id:s.string().min(1).optional(),stream_key:s.string().min(1).optional(),seen_up_to_seq:s.number().int().nonnegative().optional(),stale_event_id:s.string().min(1).optional(),stale_resolution_reason:Tl.optional(),freshness_bypass:s.boolean().optional(),attachment_ids:fa}).refine(ha,{message:"message must include text or at least one attachment",path:["content"]}),gV=s.object({stale_event_id:s.string().min(1),resolution_reason:s.literal("obsolete")}),_V=s.object({message_id:s.string(),message_seq:s.number().int().positive(),thread_root_id:s.string().nullable()}),yV=s.object({title:s.string().min(1).max(128),context_summary:s.string().min(1),initial_prompt:s.string().min(1)}),vV=s.object({root_message_id:s.string().min(1)}),bV=s.object({thread_root_id:s.string(),changed:s.boolean()}),SV=s.object({task_number:s.number().int().positive(),status:s.enum(["todo","in_progress","in_review"]),title:s.string(),assignee_name:s.string().nullable(),assignee_agent_id:s.string().nullable()}),n_=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional()),VT=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().positive().max(100).optional().default(50)),KT=s.union([s.literal("self"),s.object({thread_root_id:s.string().min(1)}),s.object({conversation_id:s.string().min(1)})]),xV=s.object({target:KT.optional(),before_seq:n_,after_seq:n_,around_message_id:s.string().min(1).optional(),include_content:s.boolean().optional().default(!1),include_system:s.boolean().optional().default(!0),limit:VT}).refine(t=>[t.before_seq,t.after_seq,t.around_message_id].filter(e=>e!==void 0).length<=1,{message:"pass at most one of before_seq, after_seq, or around_message_id; omit all to read the latest window",path:["before_seq"]}),o_=s.object({id:s.string(),workspace_id:s.string(),conversation_id:s.string(),conversation_kind:yt,channel_id:s.string(),seq:s.number(),created_at:s.number()}),s_=s.object({kind:ua,agent_id:s.string().nullable(),user_id:s.string().nullable(),display_name:s.string().nullable()}),GT=s.object({conversation_id:s.string(),conversation_kind:yt,channel_id:s.string(),thread_root_id:s.string().nullable(),workspace_id:s.string(),title:s.string()}),JT=s.object({message_ref:o_,sender:s_,snippet:s.string(),metadata:s.record(s.unknown()).nullable(),attachments:s.array(pa).nullable(),reactions:s.array(ma).nullable(),content:s.string().optional()}),YT=s.union([s.object({type:s.literal("head")}),s.object({type:s.literal("before_seq"),seq:s.number()}),s.object({type:s.literal("after_seq"),seq:s.number()}),s.object({type:s.literal("around_message_id"),message_id:s.string()})]),wV=s.object({target:GT,anchor:YT,limit:s.number(),include_content:s.boolean(),include_system:s.boolean(),messages:s.array(JT),has_more_before:s.boolean(),has_more_after:s.boolean()}),XT=s.object({id:s.string(),name:s.string(),kind:Kt,archived:s.boolean(),updated_at:s.number(),agent_dir:s.string()}),kV=s.object({workspaces:s.array(XT)}),RV=s.object({workspace_id:s.string().min(1).optional()}),QT=s.object({id:s.string(),title:s.string(),kind:s.enum(["channel","dm_channel"]),archived:s.boolean(),updated_at:s.number()}),PV=s.object({workspace_id:s.string(),channels:s.array(QT)}),i_=s.enum(["current","workspace","channel"]),eA=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().positive().max(100).optional().default(50)),EV=s.object({q:s.string().trim().min(1).max(200),scope:i_.optional().default("current"),workspace_id:s.string().min(1).optional(),channel_id:Tr,include_system:s.boolean().optional().default(!0),limit:eA}).superRefine((t,e)=>{t.scope==="channel"!=!!t.channel_id&&e.addIssue({code:s.ZodIssueCode.custom,message:"channel_id is required only when scope is channel",path:["channel_id"]}),t.workspace_id&&t.scope!=="workspace"&&e.addIssue({code:s.ZodIssueCode.custom,message:"workspace_id is only valid with scope=workspace",path:["workspace_id"]})}),tA=s.object({message_ref:o_,sender:s_,excerpt:s.string(),match_offset:s.number().int().nonnegative()}),CV=s.object({query:s.string(),scope:i_,workspace_id:s.string().nullable(),channel_id:s.string().nullable(),include_system:s.boolean(),limit:s.number(),hits:s.array(tA)}),TV=s.object({noun:s.string().max(64).optional(),verb:s.string().max(64).optional(),flags_seen:s.array(s.string().max(64)).max(64).optional(),error_code:s.string().max(64).optional(),error_subkind:s.string().max(64).optional(),error_message:s.string().max(500).optional(),duration_ms:s.number().nonnegative().optional()}).strict(),AV=s.object({ok:s.literal(!0)}),IV=s.object({enabled:s.boolean()}).strict(),$V=s.object({conversationId:s.string(),enabled:s.boolean(),expiresAt:s.number().int().nullable(),daemonSynced:s.boolean().optional()}).strict();var so=s.object({type:zg,id:s.string(),name:s.string()}),a_=s.object({id:s.string(),title:s.string()}),rA=s.object({type:s.enum(["agent","user","system"]),id:s.string().nullable(),name:s.string()}),jV=s.object({message_id:s.string(),task_number:s.number(),workspace_id:s.string(),workspace_name:s.string(),channel_id:s.string(),channel_name:s.string(),thread_root_id:s.string().nullable(),conversation:a_,status:$t,title:s.string(),assignee:so.nullable(),creator:rA,created_at:s.number(),closed_at:s.number().nullable()}),LV=s.object({workspace_id:s.string().optional(),conversation_id:s.string().optional(),status:s.array($t).optional(),task_number:s.array(s.coerce.number().int().positive()).optional(),assignee_id:s.string().optional(),limit:s.coerce.number().int().positive().max(500).optional()}),FV=s.object({tasks:s.array(s.object({title:s.string().min(1).max(200),body:s.string().optional()})).min(1),target:El.optional(),reply_to_message_id:s.string().min(1).optional()}),nA=s.enum(["conversation_not_found","conversation_closed","not_conversation_member","agent_not_found","reply_target_not_found"]),oA=s.object({tasks:s.array(s.object({message_id:s.string(),task_number:s.number(),title:s.string()}))}),sA=s.object({error:nA}),HV=s.union([oA,sA]),UV=s.object({task_numbers:s.array(s.number()).optional(),message_ids:s.array(s.string()).optional(),workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>(t.task_numbers?.length??0)+(t.message_ids?.length??0)>0,{message:"provide at least one of task_numbers or message_ids"}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),iA=s.enum(["task_not_found","message_not_found","wrong_conversation","cannot_promote_system_message","cannot_promote_anchor","task_done","task_closed","already_claimed","not_self_assignment","assignee_not_conversation_member","conversation_not_found","not_conversation_member","agent_not_found","not_a_task","unknown_workspace","ambiguous_workspace","workspace_membership_required","capability_denied"]),aA=s.object({success:s.boolean(),task_number:s.number().optional(),message_id:s.string().optional(),reason:s.string().optional(),code:iA.optional(),capability:vs.optional(),owner_conversation:a_.optional(),workspace_candidates:s.array(s.string()).optional()}),qV=s.object({results:s.array(aA)}),WV=s.object({task_number:s.number().int().positive(),workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),ZV=s.object({task_number:s.number().int().positive(),status:$t,workspace_id:s.string().optional(),workspace_name:s.string().optional()}).refine(t=>!(t.workspace_id&&t.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),cA=s.enum(["not_a_task","task_not_found","task_done","wrong_conversation","not_assignee","invalid_transition","already_at_status","task_closed","conversation_not_found","not_conversation_member","agent_not_found","unknown_workspace","ambiguous_workspace","workspace_membership_required","capability_denied"]),BV=s.object({success:s.boolean(),reason:s.string().optional(),code:cA.optional(),capability:vs.optional(),workspace_candidates:s.array(s.string()).optional()}),VV=s.object({status:$t}),KV=s.object({agent_id:s.string().optional()}),GV=s.object({kind:s.enum(["create","claim","unclaim","status"]),workspace_id:s.string(),channel_id:s.string(),thread_root_id:s.string().nullable(),conversation_id:s.string(),task_number:s.number(),message_id:s.string(),status:$t,assignee:so.nullable(),title:s.string(),closed_at:s.number().nullable()});function ga(t,e){if(!Number.isInteger(t)||t<0)throw new RangeError(`${e}: cannot decode ${t} \u2014 expected a non-negative integer seq`)}function uA(t){return ga(t,"MessageSeq"),t}function lA(t){return ga(t,"TransportSeq"),t}function dA(t){return ga(t,"ReadSeq"),t}function _a(t){return ga(t,"ObservedSeq"),t}function pA(t){if(typeof t!="string"||t.length===0)throw new RangeError(`TransportEpoch: cannot decode ${JSON.stringify(t)} \u2014 expected a non-empty string`);return t}var ya=s.number().int().nonnegative(),mn=ya.transform(uA),XV=ya.transform(lA),QV=ya.transform(dA),eK=ya.transform(_a),tK=s.string().min(1).transform(pA);var mA=s.enum(["agent","human","system"]),fA=s.object({kind:mA,id:s.string()}),hA=s.object({kind:s.enum(["agent","human"]),id:s.string()}),c_=s.object({root_message_id:s.string(),root_author:fA,root_preview:s.string(),root_created_at:s.number(),root_seq:mn,reply_count:s.number().int().nonnegative(),last_reply_at:s.number(),last_reply_message_id:s.string(),repliers:s.array(hA),replier_total:s.number().int().nonnegative(),viewer_following:s.boolean()}),u_=c_.omit({viewer_following:!0}),sK=s.object({threads:s.array(c_),next_cursor:s.string().nullable()});var va=s.object({id:s.string(),conversation_id:s.string(),from_kind:ua,from_agent_id:s.string().nullable(),from_user_id:s.string().nullable(),content:s.string(),metadata:s.record(s.unknown()).nullable(),attachments:s.array(pa).nullable(),reactions:s.array(ma).nullable(),seq:mn,created_at:s.number(),thread_root_id:s.string().nullable(),task_number:s.number().nullable(),task_status:$t.nullable(),task_title:s.string().nullable(),task_workspace_id:s.string().nullable(),task_closed_at:s.number().nullable(),task_assignee:so.nullable()}),gA=s.object({root_id:s.string(),reply_count:s.number().int().nonnegative()}),_A=s.object({thread_root_reply_count:gA.optional(),threads_list_entry:s.object({entry:u_}).optional()}),hK=s.object({message:va,projections:_A.optional()}),yA=s.object({reply_count:s.number().int().nonnegative(),last_reply_at:s.number(),repliers:s.array(s.object({kind:s.enum(["agent","human"]),id:s.string()})),replier_total:s.number().int().nonnegative()}),gK=s.object({messages:s.array(va),reply_counts_by_root:s.record(s.string(),s.number().int().nonnegative()),reply_summaries_by_root:s.record(s.string(),yA).optional(),has_more_before:s.boolean(),stream_head_seq:mn,has_more_after:s.boolean()}),_K=s.object({thread_root_id:s.string(),viewer_following:s.boolean(),follower_agent_ids:s.array(s.string())}),yK=s.object({thread_root_id:s.string(),changed:s.boolean(),viewer_following:s.boolean()}),vK=s.object({content:s.string(),attachment_ids:fa,reply_to_message_id:s.string().min(1).optional(),as_task:s.boolean().optional()}).refine(ha,{message:"message must include text or at least one attachment",path:["content"]}),l_=s.object({unread_count:s.number().int().nonnegative(),first_unread_message_id:s.string().nullable(),first_unread_seq:mn.nullable()}),bK=s.object({mainline:l_,threads:s.record(s.string(),l_)}),m_=s.object({conversation_id:s.string(),message_id:s.string(),seq:mn,thread_root_id:s.string().nullable()}),SK=s.object({by_conversation:s.record(s.string(),s.number()),latest_by_conversation:s.record(s.string(),m_),total:s.number()}),xK=s.object({by_workspace:s.record(s.string(),s.number())}),wK=s.object({conversation_id:s.string(),workspace_id:s.string(),conversation_unread_count:s.number(),workspace_unread_count:s.number(),latest_unread:m_.nullable()}),d_=s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional()),vA=s.enum(["all","regular","dm"]),bA=s.enum(["all","mainline","thread"]),SA=s.enum(["recency_desc","seq_asc"]),xA=s.object({q:s.string().trim().max(200).optional().default(""),scope:vA.optional().default("all"),stream:bA.optional().default("all"),workspace_id:Tr,conversation_id:Tr,thread_root_id:Tr,user_id:Tr,agent_id:Tr,from:d_,to:d_,order:SA.optional().default("recency_desc"),limit:s.coerce.number().int().positive().max(500).optional().default(80)}).refine(t=>!(t.user_id&&t.agent_id),{message:"user_id and agent_id cannot both be set",path:["user_id"]}).refine(t=>t.stream==="all"||!!t.conversation_id,{message:"stream filter requires conversation_id",path:["stream"]}).refine(t=>t.stream!=="thread"||!!t.thread_root_id,{message:"stream=thread requires thread_root_id",path:["thread_root_id"]}).refine(t=>t.order!=="seq_asc"||!!t.conversation_id,{message:"order=seq_asc requires conversation_id",path:["order"]}),Al=s.object({id:s.string(),name:s.string(),kind:s.enum(["regular","dm"])}),p_=s.object({id:s.string(),title:s.string(),kind:yt,channel_id:s.string(),closed_at:s.number().nullable(),created_at:s.number()}),wA=s.discriminatedUnion("type",[s.object({type:s.literal("workspace"),workspace:Al.extend({description:s.string().nullable(),archived_at:s.number().nullable(),created_at:s.number(),updated_at:s.number()})}),s.object({type:s.literal("conversation"),workspace:Al,conversation:p_}),s.object({type:s.literal("message"),workspace:Al,conversation:p_,message:va,agent_name:s.string().nullable()})]),kK=s.object({query:xA,results:s.array(wA),total:s.number(),truncated:s.boolean()}),RK=s.object({id:s.string(),message:va,workspace_id:s.string(),workspace_name:s.string(),conversation_id:s.string(),conversation_title:s.string(),channel_id:s.string(),agent_name:s.string().nullable(),saved_at:s.number()}),PK=s.object({workspace_id:s.preprocess(t=>typeof t=="string"&&t.trim()===""?void 0:t,s.string().optional()),since:s.preprocess(t=>t===""||t===void 0?void 0:t,s.coerce.number().int().nonnegative().optional())});var f_=["all","mentions"];var TK=s.object({conversation_id:s.string(),mode:s.enum(f_)}),AK=s.object({mode:s.enum(f_)}),kA=["directed","ambient"],RA=["mention","agent_failed","unread"],PA=s.object({kind:s.enum(["user","agent"]),id:s.string(),display_name:s.string(),avatar_url:s.string().nullable()}),EA=s.object({id:s.string(),kind:s.enum(RA),salience:s.enum(kA),workspace_id:s.string(),conversation_id:s.string(),thread_root_id:s.string().nullable(),message_id:s.string().nullable(),notification_id:s.string().nullable(),conversation_kind:s.enum(["channel","dm_channel"]),title:s.string(),thread_root_preview:s.string().nullable(),preview:s.string().nullable(),preview_sender:PA.nullable(),timestamp:s.number(),unread_count:s.number().int().nonnegative().nullable()}),IK=s.object({items:s.array(EA)}),CA=s.discriminatedUnion("kind",[s.object({kind:s.literal("at_seq"),seq:s.number().int().nonnegative()}),s.object({kind:s.literal("stream_head")})]),TA=s.discriminatedUnion("kind",[s.object({kind:s.literal("stream"),conversation_id:s.string().min(1),thread_root_id:s.string().min(1).nullable(),position:CA}),s.object({kind:s.literal("notification"),notification_id:s.string().min(1)})]),$K=s.object({sources:s.array(TA).min(1).max(1e3)}),zK=s.object({changed:s.boolean()});var NK=s.object({id:s.string(),kind:Lg,user_id:s.string().nullable(),agent_id:s.string().nullable(),workspace_id:s.string().nullable(),conversation_id:s.string().nullable(),message_id:s.string().nullable(),thread_root_id:s.string().nullable().optional(),source_workspace_id:s.string().nullable(),source_conversation_id:s.string().nullable(),source_message_id:s.string().nullable(),payload:s.record(s.unknown()).nullable(),read_at:s.number().nullable(),created_at:s.number()}),jK=s.object({id:s.string().optional(),workspace_id:s.string().optional(),conversation_id:s.string().optional(),all:s.boolean().optional()}).refine(t=>!!(t.id||t.workspace_id||t.conversation_id||t.all),{message:"must specify id, workspace_id, conversation_id, or all"});var HK=2160*60*60,AA=60;var IA=120,$A=500,zA=s.enum(["pending","firing","done","cancelled","failed"]),OA=s.object({kind:s.literal("once"),fire_at:s.number().int().positive()}),h_=s.object({kind:s.literal("interval"),every_seconds:s.number().int().min(AA),start_at:s.number().int().positive().optional()}),g_=s.object({kind:s.literal("cron"),expression:s.string().min(1).max(200),timezone:s.string().min(1).max(64)}),DA=s.discriminatedUnion("kind",[OA,h_,g_]),Il=s.object({id:s.string(),owner_agent_id:s.string(),target_conversation_id:s.string(),target_label:s.string(),title:s.string(),message:s.string(),spec:DA,next_fire_at:s.number(),status:zA,fired_count:s.number(),last_fired_at:s.number().nullable(),max_occurrences:s.number().nullable(),until_at:s.number().nullable(),failure_reason:s.string().nullable(),cancelled_at:s.number().nullable(),last_failure_reason:s.string().nullable(),last_failure_at:s.number().nullable(),consecutive_failure_count:s.number(),created_at:s.number(),updated_at:s.number()}),MA=s.object({kind:s.literal("once"),fire_at:s.number().int().positive().optional(),delay_seconds:s.number().int().positive().optional()}),UK=s.object({title:s.string().trim().min(1).max(IA),message:s.string().min(1).max($A),target_conversation_id:s.string().optional(),spec:s.discriminatedUnion("kind",[MA,h_,g_]),until_at:s.number().int().positive().optional(),max_occurrences:s.number().int().positive().optional(),allow_unbounded:s.boolean().optional()}).superRefine((t,e)=>{t.spec.kind==="once"&&(t.until_at!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["until_at"],message:"until_at is not valid on a `once` schedule"}),t.max_occurrences!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["max_occurrences"],message:"max_occurrences is not valid on a `once` schedule"}),t.allow_unbounded!==void 0&&e.addIssue({code:s.ZodIssueCode.custom,path:["allow_unbounded"],message:"allow_unbounded is not valid on a `once` schedule"}),!!t.spec.fire_at==!!t.spec.delay_seconds&&e.addIssue({code:s.ZodIssueCode.custom,path:["spec","fire_at"],message:"once spec requires exactly one of fire_at or delay_seconds"}))}),NA=s.enum(["pending","firing","active","done","cancelled","failed","all"]),qK=s.object({status:NA.optional(),limit:s.number().int().min(1).max(200).optional()}),WK=s.object({schedule_id:s.string()}),ZK=s.object({schedule:Il}),BK=s.object({schedules:s.array(Il)}),VK=s.object({schedule:Il});var jA=s.enum(["online","offline"]),LA=s.object({user_id:s.string(),presence:jA,last_seen_at:s.number().nullable()});var JK=s.object({users:s.array(LA)});var __=s.enum(["recent","manual"]),y_=s.enum(["starred","dm","regular","unstarred","favorites"]),$l=s.string().refine(t=>t==="workspaces"||t==="favorites"||t.startsWith("channels:"),{message:"list_key must be 'workspaces', 'favorites', or 'channels:<ws_id>'"}),FA=s.object({entity_id:s.string(),rank:s.number().nullable(),last_accessed_at:s.number().nullable(),starred_at:s.number().nullable()}),v_=s.object({list_key:s.string(),modes:s.record(__),entries:s.array(FA)}),QK=s.object({list_key:$l,group:y_.optional(),mode:__}),e6=s.object({list_key:$l,group:y_,ordered_ids:s.array(s.string())}),t6=s.object({list_key:$l,entity_id:s.string()});var HA=s.enum(["workspace","dm"]),UA=s.object({kind:HA,favorite_key:s.string(),entity_id:s.string(),workspace_id:s.string(),title:s.string(),icon_url:s.string().nullable(),runtime:De.nullable(),starred_at:s.number(),created_at:s.number(),unread_count:s.number().nullable()}),i6=s.object({items:s.array(UA),viewer_sort:v_});var ba={health:"/api/health",serverInfo:"/api/server/info",runtimes:"/api/runtimes",eventWebSocket:"/api/ws/events",presence:"/api/presence",hosts:"/api/hosts",hostConnect:"/api/hosts/connect",hostConnectTokenResolve:"/api/hosts/connect-token/resolve",hostClaimOrCreate:"/api/hosts/claim-or-create",hostRevoke:t=>`/api/hosts/${t}/revoke`,hostRotateToken:t=>`/api/hosts/${t}/rotate-token`,hostRotateConnectToken:t=>`/api/hosts/${t}/connect-token/rotate`,hostDisconnect:t=>`/api/hosts/${t}/disconnect`,host:t=>`/api/hosts/${t}`,hostDelete:t=>`/api/hosts/${t}`,hostCancelPending:t=>`/api/hosts/${t}`,hostStatus:t=>`/api/hosts/${t}/status`,hostRuntimeCatalog:t=>`/api/hosts/${t}/runtime-catalog`,hostProxyConfig:t=>`/api/hosts/${t}/proxy-config`,agents:"/api/agents",agent:t=>`/api/agents/${t}`,agentWorkspaceTree:t=>`/api/agents/${t}/workspace/tree`,agentWorkspaceFile:t=>`/api/agents/${t}/workspace/file`,agentProfileMcp:t=>`/api/agents/${t}/profile/mcp`,agentProfileMcpProbe:t=>`/api/agents/${t}/profile/mcp/probe`,agentRuntimeState:t=>`/api/agents/${t}/runtime-state`,agentStop:t=>`/api/agents/${t}/stop`,agentDeleteImpact:t=>`/api/agents/${t}/delete-impact`,agentAvatar:t=>`/api/agents/${t}/avatar`,agentSchedules:t=>`/api/agents/${t}/schedules`,agentScheduleCancel:(t,e)=>`/api/agents/${t}/schedules/${e}/cancel`,workspaces:"/api/workspaces",workspace:t=>`/api/workspaces/${t}`,workspaceStar:t=>`/api/workspaces/${t}/star`,workspaceMembers:t=>`/api/workspaces/${t}/members`,workspaceMember:(t,e)=>`/api/workspaces/${t}/members/${e}`,workspaceHumanMember:(t,e)=>`/api/workspaces/${t}/members/users/${e}`,workspaceHumanMemberRole:(t,e)=>`/api/workspaces/${t}/members/users/${e}/role`,workspaceAgentCapabilities:(t,e)=>`/api/workspaces/${t}/agents/${e}/capabilities`,workspaceChannels:t=>`/api/workspaces/${t}/channels`,workspaceArchivedChannels:t=>`/api/workspaces/${t}/channels/archived`,archivedChannels:"/api/archived-channels",sortMode:"/api/sort/mode",sortOrder:"/api/sort/order",sortTouch:"/api/sort/touch",channelStar:t=>`/api/channels/${t}/star`,channelMessages:t=>`/api/channels/${t}/messages`,channelThreadFollowers:(t,e)=>`/api/channels/${t}/threads/${e}/followers`,channelThreadFollow:(t,e)=>`/api/channels/${t}/threads/${e}/follow`,channelAgents:t=>`/api/channels/${t}/agents`,channelAgentStart:(t,e)=>`/api/channels/${t}/agents/${e}/start`,channelAgentStop:(t,e)=>`/api/channels/${t}/agents/${e}/stop`,channelAgentClearSession:(t,e)=>`/api/channels/${t}/agents/${e}/clear-session`,channelAgentRunStates:t=>`/api/channels/${t}/agent-run-states`,channelClose:t=>`/api/channels/${t}/close`,channelStop:t=>`/api/channels/${t}/stop`,channelResume:t=>`/api/channels/${t}/resume`,channelArchive:t=>`/api/channels/${t}/archive`,conversationChannel:t=>`/api/channels/${t}`,conversationChannelMessages:t=>`/api/channels/${t}/messages`,conversationChannelAgents:t=>`/api/channels/${t}/agents`,conversationRef:t=>`/api/conversations/${t}/ref`,conversationThreads:t=>`/api/conversations/${t}/threads`,conversationUnread:t=>`/api/conversations/${t}/unread`,conversationAttentionPreference:t=>`/api/conversations/${t}/attention-preference`,activity:"/api/activity",favorites:"/api/favorites",attentionObserve:"/api/attention/observe",conversationLogDebug:t=>`/api/conversations/${t}/log-debug`,conversationAgentActivity:(t,e)=>`/api/conversations/${t}/agents/${e}/activity`,conversationMembers:t=>`/api/conversations/${t}/members`,conversationAgentMember:(t,e)=>`/api/conversations/${t}/members/agents/${e}`,channelAttachments:t=>`/api/channels/${t}/attachments`,attachment:t=>`/api/attachments/${t}`,messageUnreadSummary:"/api/message-unread-summary",saved:"/api/saved",search:"/api/search",messageSave:t=>`/api/messages/${t}/save`,messageReactions:t=>`/api/messages/${t}/reactions`,message:t=>`/api/messages/${t}`,users:"/api/users",me:"/api/me",meAvatar:"/api/me/avatar",userAvatar:t=>`/api/users/${t}/avatar`,notifications:"/api/notifications",notificationsUnread:"/api/notifications/unread",notificationsRead:"/api/notifications/read",tasks:"/api/tasks",taskClaim:t=>`/api/tasks/${t}/claim`,taskUnclaim:t=>`/api/tasks/${t}/unclaim`,taskStatus:t=>`/api/tasks/${t}/status`};var zl={agentSendConversationMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/send-message`,agentResolveStaleMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/stale-message-resolution`,agentCreateChannel:(t,e)=>`/internal/conversations/${t}/agents/${e}/create-channel`,agentReadHistory:(t,e)=>`/internal/conversations/${t}/agents/${e}/read-history`,agentFollowThread:(t,e)=>`/internal/conversations/${t}/agents/${e}/follow-thread`,agentUnfollowThread:(t,e)=>`/internal/conversations/${t}/agents/${e}/unfollow-thread`,agentListWorkspaces:(t,e)=>`/internal/conversations/${t}/agents/${e}/list-workspaces`,agentListChannels:(t,e)=>`/internal/conversations/${t}/agents/${e}/list-channels`,agentSearchMessages:(t,e)=>`/internal/conversations/${t}/agents/${e}/search-messages`,agentAddConversationMember:(t,e)=>`/internal/conversations/${t}/agents/${e}/members`,agentReactMessage:(t,e)=>`/internal/conversations/${t}/agents/${e}/react-message`,agentListConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks`,agentCreateConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/create`,agentClaimConversationTasks:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/claim`,agentUnclaimConversationTask:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/unclaim`,agentUpdateConversationTaskStatus:(t,e)=>`/internal/conversations/${t}/agents/${e}/tasks/update-status`,agentScheduleCreate:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules`,agentScheduleList:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules/list`,agentScheduleCancel:(t,e)=>`/internal/conversations/${t}/agents/${e}/schedules/cancel`,agentUploadAttachment:(t,e)=>`/internal/conversations/${t}/agents/${e}/attachments`,agentLocateAttachment:(t,e,r)=>`/internal/conversations/${t}/agents/${e}/attachments/${r}/locate`,agentDownloadAttachment:(t,e,r)=>`/internal/conversations/${t}/agents/${e}/attachments/${r}/download`,agentUploadAvatar:(t,e)=>`/internal/conversations/${t}/agents/${e}/avatar`,agentDeleteAvatar:(t,e)=>`/internal/conversations/${t}/agents/${e}/avatar`,agentCliTrace:(t,e)=>`/internal/conversations/${t}/agents/${e}/cli-trace`,agentProfileMcpGet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp`,agentProfileMcpSet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp`,agentProfileMcpProbe:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile/mcp/probe`,agentProfileGet:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile`,agentProfileUpdate:(t,e)=>`/internal/conversations/${t}/agents/${e}/profile`};var qA="wsah_";function Ol(t){return`${qA}${t}`}function Sa(t,e){return e.length>0&&t===Ol(e)}var WA=s.unknown().refine(t=>t!==void 0,{message:"field is required (opaque payload must be present)"}),io=s.discriminatedUnion("kind",[s.object({kind:s.literal("session_init"),sessionId:s.string().min(1)}).strict(),s.object({kind:s.literal("thinking"),text:s.string()}).strict(),s.object({kind:s.literal("text"),text:s.string()}).strict(),s.object({kind:s.literal("tool_call"),name:s.string().min(1),input:WA,toolCallId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("tool_output"),name:s.string().min(1).optional(),toolCallId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("turn_end"),sessionId:s.string().min(1).optional()}).strict(),s.object({kind:s.literal("compaction_started")}).strict(),s.object({kind:s.literal("compaction_finished")}).strict(),s.object({kind:s.literal("error"),message:s.string(),code:s.string().optional(),fatal:s.boolean().optional()}).strict(),s.object({kind:s.literal("unknown"),raw:s.string()}).strict()]),ZA=["session_init","thinking","text","tool_call","tool_output","turn_end","compaction_started","compaction_finished","error","unknown"],xa=s.enum(ZA);var BA=s.enum(["embedded","remote"]),VA=s.object({max_concurrent_per_parent:s.number().int().positive().nullable().default(null),spawn_cooldown_seconds:s.number().int().nonnegative().nullable().default(null),max_depth:s.literal(1).default(1)}),j6=s.object({mode:BA,url:s.string().url(),auth_token:s.string().min(16).optional(),event_ws_allowed_origins:s.array(s.string().url()).optional(),refresh_token:s.string().nullable().default(null),child_sessions:VA.default({max_concurrent_per_parent:null,spawn_cooldown_seconds:null,max_depth:1})});var Dl="daemon-config.json";var b_="authorization",wa=s.object({server_url:s.string().url(),host_id:s.string().min(1),host_token:s.string().min(1),allow_insecure_remote:s.boolean().optional(),profile_version:s.number().int().nonnegative().optional()}).strict(),S_="SILVERHAND_CONVERSATION_ID",x_="SILVERHAND_AGENT_ID",w_="SILVERHAND_SERVER_URL",k_="SILVERHAND_AUTH_TOKEN",R_="SILVERHAND_LAST_DELIVERED_SEQ_FILE",P_="SILVERHAND_DAEMON_SOCKET",KA="SILVERHAND_ALLOW_INSECURE_REMOTE";function E_(t=process.env){return t[KA]==="1"}var Ml="SILVERHAND_LOG_LEVEL",C_=["error","warn","info","debug"],GA="warn";var T_=["payload","chunk","body","text","prompt","line","env","stdout","stderr","soft_directive"],A_=["env_"];function Nl(t){return t==="error"||t==="warn"||t==="info"||t==="debug"?t:GA}function jl(t){let{value:e,redacted:r}=$_(t,new WeakSet);return r>0&&(e.redactedFieldCount=r),e}function I_(t,e){if(Array.isArray(t)){if(e.has(t))return{value:"[Circular]",redacted:0};e.add(t);let r=0,n=t.map(o=>{let i=I_(o,e);return r+=i.redacted,i.value});return e.delete(t),{value:n,redacted:r}}return YA(t)?$_(t,e):{value:t,redacted:0}}function $_(t,e){if(e.has(t))return{value:{_circular:!0},redacted:0};e.add(t);let r={},n=0;for(let[o,i]of Object.entries(t)){if(JA(o)){n+=1;continue}let a=I_(i,e);r[o]=a.value,n+=a.redacted}return e.delete(t),{value:r,redacted:n}}function JA(t){return T_.includes(t)?!0:A_.some(e=>t.startsWith(e))}function YA(t){if(!t||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Ar="mcp.json",XA=/^[A-Za-z0-9_-]{1,64}$/,QA=s.object({type:s.literal("stdio").optional(),command:s.string().min(1),args:s.array(s.string()).optional(),env:s.record(s.string()).optional()}).strict(),eI=s.object({type:s.enum(["http","sse"]),url:s.string().url(),headers:s.record(s.string()).optional()}).strict(),tI=s.union([QA,eI]),rI=s.object({mcpServers:s.record(tI).default({}).superRefine((t,e)=>{for(let r of Object.keys(t))XA.test(r)||e.addIssue({code:s.ZodIssueCode.custom,message:`invalid MCP server name "${r}": use 1-64 chars of [A-Za-z0-9_-]`,path:["mcpServers",r]})})}).strict(),nI={mcpServers:{}};function ao(t){let e=t.trim();if(e.length===0)return{ok:!0,config:nI};let r;try{r=JSON.parse(e)}catch(o){return{ok:!1,error:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}}let n=rI.safeParse(r);if(!n.success){let o=n.error.issues[0];return{ok:!1,error:`invalid MCP config${o?.path.length?` at ${o.path.join(".")}`:""}: ${o?.message??"schema mismatch"}`}}return{ok:!0,config:n.data}}function ka(t,e){return`silverhand_${t}__${e}`}function z_(t,e="profile"){let r=Object.keys(t.mcpServers);if(r.length===0)return null;let n={};for(let o of r)n[ka(e,o)]=t.mcpServers[o];return{mcpServers:n}}function O_(t,e="profile"){let r=[];for(let[n,o]of Object.entries(t.mcpServers)){let i=`mcp_servers.${ka(e,n)}`;r.push(`${i}=${Ll(oI(o))}`)}return r}function oI(t){if("url"in t){let r={url:t.url};return t.headers&&(r.http_headers=t.headers),r}let e={command:t.command};return t.args&&(e.args=t.args),t.env&&(e.env=t.env),e}function Ll(t){if(typeof t=="string")return D_(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`cannot serialize non-finite number to TOML: ${t}`);return String(t)}if(Array.isArray(t))return`[${t.map(Ll).join(", ")}]`;if(t!==null&&typeof t=="object"){let e=[];for(let[r,n]of Object.entries(t))n!==void 0&&e.push(`${cI(r)} = ${Ll(n)}`);return`{${e.join(", ")}}`}throw new Error(`cannot serialize value to TOML: ${String(t)}`)}var sI=["parse","not_found","connect","initialize","tools"],iI=s.enum(sI),aI=s.object({name:s.string(),description:s.string().optional()}).strict(),Ra=s.object({ok:s.boolean(),phase:iI,message:s.string().optional(),server_info:s.object({name:s.string().optional(),version:s.string().optional()}).strict().optional(),tools:s.array(aI).optional()}).strict(),U6=s.object({server_name:s.string().min(1),include_tools:s.boolean().optional()}).strict();function cI(t){return/^[A-Za-z0-9_-]+$/.test(t)?t:D_(t)}function D_(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var W6=Object.freeze({html:"text/html",htm:"text/html",svg:"image/svg+xml",json:"application/json",md:"text/markdown",markdown:"text/markdown",txt:"text/plain",log:"text/plain",csv:"text/csv",pdf:"application/pdf",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"});var Z6=Object.freeze(new Set(["html","htm","pdf","txt","log","md","markdown","json","csv","png","jpg","jpeg","gif","webp"]));var M_={send_message:"`silverhand message send`",react_message:"`silverhand message react`",create_channel:"`silverhand channel create`",list_tasks:"`silverhand task list`",create_tasks:"`silverhand task create`",claim_tasks:"`silverhand task claim`",unclaim_task:"`silverhand task unclaim`",update_task_status:"`silverhand task status`",upload_file:"`silverhand file upload`",view_file:"`silverhand file view`",read_history:"`silverhand message history`",list_workspaces:"`silverhand workspace list`",list_channels:"`silverhand channel list`",search_messages:"`silverhand message search`",add_member:"`silverhand member add`",schedule:"`silverhand schedule create`",list_schedules:"`silverhand schedule list`",cancel_schedule:"`silverhand schedule cancel`"};function uI(t){let e=F=>M_[F],r=e("send_message"),n=e("create_channel"),o=e("add_member"),i=e("list_tasks"),a=e("create_tasks"),c=e("claim_tasks"),u=e("unclaim_task"),l=e("update_task_status"),d=e("upload_file"),p=e("view_file"),m=e("read_history"),f=e("list_workspaces"),_=e("list_channels"),g=e("search_messages"),y=e("schedule"),S=e("list_schedules"),x=e("cancel_schedule"),w=hI(t.sessionContext),T=lI(t.activeProfileDir),v=N_(T,"MEMORY.md"),P=N_(T,"notes"),O=dI({title:"Active Workspace Memory",relPath:v,description:"This is the current workspace's MEMORY.md, auto-loaded for you. Treat it as your recovery index. Edit it to add/update Key Knowledge entries or the current Active Context; keep durable detail in the linked notes/ files.",content:t.currentMemory,missingHint:"No MEMORY.md exists yet. Create one at the path above when you first capture durable knowledge for this workspace."}),J=mI(t.workspaceMemoryIndex);return`You are **@${t.agentName}**, an agent collaborating with humans and
18
18
  other agents in a shared workspace via Silverhand. This is your operating
19
19
  manual; your specific assignment is the **Initial role** section at the end.
20
20
 
@@ -134,7 +134,7 @@ stand alone as your recovery point.
134
134
  unless you are the reviewer or were assigned to verify.
135
135
  - **Skip idle narration.** Send a message only when you have actionable
136
136
  content; don't broadcast that you are waiting or idle.
137
- - **React sparingly.** ${T_.react_message} adds or removes an emoji
137
+ - **React sparingly.** ${M_.react_message} adds or removes an emoji
138
138
  reaction on a message \u2014 a lightweight acknowledgement/follow-up signal like \u{1F440}.
139
139
  Use it sparingly; do not auto-react to every merge, deploy, or task completion
140
140
  with celebratory emoji.
@@ -306,7 +306,7 @@ When a schedule fires you get a system message with
306
306
  \`metadata.subtype = 'schedule_fire'\` \u2014 decide whether work is still needed, do
307
307
  it, and report via ${r} (or a brief no-op reply if not).
308
308
 
309
- ${tI()}
309
+ ${fI()}
310
310
 
311
311
  ## Formatting Reference
312
312
 
@@ -356,37 +356,39 @@ ${J}
356
356
  ## Initial role (your assignment in this workspace/channel)
357
357
 
358
358
  ${t.roleSystemPrompt.trim()||"_(role not yet defined \u2014 wait for the user to shape it during onboarding)_"}
359
- `}function I_(t,e){return JA({agentId:e.agentId,agentName:e.agentName,runtime:t,activeProfileDir:e.activeProfileDir,roleSystemPrompt:e.roleSystemPrompt,currentMemory:e.currentMemory,workspaceMemoryIndex:e.workspaceMemoryIndex,sessionContext:e.sessionContext})}function YA(t){let e=t.trim();if(!e||e===".")return".";let r=e.replace(/\/{2,}/g,"/");return r.startsWith("./")?r.replace(/\/+$/,""):`./${r.replace(/^\/+/,"").replace(/\/+$/,"")}`}function A_(t,e){return t==="."?`./${e}`:`${t}/${e}`}function XA(t){let e=`## ${t.title}
359
+ `}function j_(t,e){return uI({agentId:e.agentId,agentName:e.agentName,runtime:t,activeProfileDir:e.activeProfileDir,roleSystemPrompt:e.roleSystemPrompt,currentMemory:e.currentMemory,workspaceMemoryIndex:e.workspaceMemoryIndex,sessionContext:e.sessionContext})}function lI(t){let e=t.trim();if(!e||e===".")return".";let r=e.replace(/\/{2,}/g,"/");return r.startsWith("./")?r.replace(/\/+$/,""):`./${r.replace(/^\/+/,"").replace(/\/+$/,"")}`}function N_(t,e){return t==="."?`./${e}`:`${t}/${e}`}function dI(t){let e=`## ${t.title}
360
360
 
361
361
  Source: \`${t.relPath}\` \u2014 ${t.description}`,r=t.content;if(r.kind==="missing")return`${e}
362
362
 
363
363
  _${t.missingHint}_`;if(r.kind==="unreadable")return`${e}
364
364
 
365
- _[unable to read ${t.relPath}: ${r.reason}]_`;let n=QA(r.body);return`${e}
365
+ _[unable to read ${t.relPath}: ${r.reason}]_`;let n=pI(r.body);return`${e}
366
366
 
367
367
  ${n}md
368
368
  ${r.body}
369
- ${n}`}function QA(t){let e=0,r=/`+/g,n;for(;(n=r.exec(t))!==null;)n[0].length>e&&(e=n[0].length);let o=Math.max(3,e+1);return"`".repeat(o)}function eI(t){let e=`## Workspace Memory Index
369
+ ${n}`}function pI(t){let e=0,r=/`+/g,n;for(;(n=r.exec(t))!==null;)n[0].length>e&&(e=n[0].length);let o=Math.max(3,e+1);return"`".repeat(o)}function mI(t){let e=`## Workspace Memory Index
370
370
 
371
371
  Every workspace you are a member of, with the absolute path to its MEMORY.md for you. The current workspace's MEMORY.md is already auto-loaded above as **Active Workspace Memory**; the other entries are reference paths \u2014 open one with your file tools only when you have a concrete reason to consult that workspace (the user asked, a hand-off references it, etc.). Do not bulk-read them.`;if(t.length===0)return`${e}
372
372
 
373
373
  _No member workspaces._`;let r=t.map(n=>`- ${n.label} \u2014 \`${n.memoryPath}\``).join(`
374
374
  `);return`${e}
375
375
 
376
- ${r}`}function tI(){return"## Tool Reference (silverhand CLI)\n\nUse the silverhand CLI for all chat / task / workspace / channel / thread /\nattachment / schedule operations.\n\n**CLI contract.** Subcommands default to `--json` (stdout is machine-readable).\nOn failure, stderr is the primary failure context and the command exits\nnon-zero; in JSON mode stderr also carries an error object with a stable\n`code` and `retriable` flag. Treat exit code 1 as a user/input error, 2 as a\ntemporary error that may be retried, and 3 as a failure to stop and report. This\nmanual is a command index plus the few high-risk pitfalls \u2014 flag-level detail is\ndeliberately not duplicated, so treat `silverhand <noun> <verb> --help` as the\nsource of truth for exact flags.\n\n**Run *dependent* silverhand commands one at a time.** When a later command's\ninput depends on an earlier one's result \u2014 claim-then-act, or resending a message\nafter a stale conflict \u2014 issue the first, read its output, then decide the next.\nDon't chain them in one shell command (`a && b`); a mid-chain failure leaves you\nunable to tell which step's state to trust. Independent reads (`--help`, status\nchecks, file lookups) can still run together.\n\n**Capabilities.** Some operations are gated by per-workspace capabilities a\nhuman owner/admin grants you. When you lack one, the command fails with a\n`capability_denied` error whose `details.capability` names the missing bucket\n(e.g. `send_messages`, `create_channels`, `manage_schedules`); task\nclaim/unclaim/status instead return a result entry with\n`code: 'capability_denied'` and a `capability` field. This is **not**\nretriable \u2014 don't loop; report which capability you lack and let the human\ngrant it.\n\n### Command index\n- **`silverhand message send`**: Send a message. With no `--target` it goes to\n the stream that woke this turn (channel main line, or the one thread you are\n replying inside), so the common case needs no flag. `--target channel` forces\n the main line; `--target thread:<message_id>` sends into that message's reply\n cluster (a main-line id opens/targets its thread; a reply id joins the same\n thread, no nesting). If a turn has two or more candidate threads, bare send\n fails with `ambiguous_default_target`; choose from\n `details.candidate_targets`. The result echoes `thread_root_id`.\n- **`silverhand message history`**: Read a history window;\n `--target thread:<root_message_id>` pulls a reply cluster (and advances your\n observed boundary for it).\n- **`silverhand message search`**: Search visible message text (scopes under\n **History and search**).\n- **`silverhand message react`**: Add (or `--remove`) your emoji reaction on a\n message by `--message-id`. A lightweight signal; idempotent. Use sparingly\n (see Collaboration Policy \u2192 React sparingly).\n- **`silverhand task list`**: View the task board (newest-first). Filter with `--status`\n (canonical statuses plus macros `active` / `open` / `pending` / `all`).\n- **`silverhand task create`**: Create a task without auto-claiming;\n optional `--target thread:<message_id>` attributes it to a thread.\n- **`silverhand task claim`**: Claim a task by number, or promote-and-claim a\n message by id.\n- **`silverhand task unclaim`** / **`silverhand task status`**: Release a\n claim / move a task through its status workflow.\n- **`silverhand thread follow`** / **`silverhand thread unfollow`**:\n Subscribe / unsubscribe to a reply cluster by `--root <message_id>`.\n- **`silverhand channel create`** / **`silverhand channel list`**: Create a\n top-level channel when requested / list channels.\n- **`silverhand workspace list`**: List workspaces you can access.\n- **`silverhand schedule create`** / **`silverhand schedule list`** /\n **`silverhand schedule cancel`**: Manage self-wakes.\n- **`silverhand file upload`** / **`silverhand file view`**: Upload a local\n file for an attachment id / resolve an attachment id to a readable location.\n- **`silverhand profile get`** / **`silverhand profile update`**: Read or\n change your own profile (`display_name`, `description`, avatar). Self-only;\n there is no target flag. Avatar updates can use a local file, an http(s)\n image, or clear the current avatar. `avatar_url` in output is read-only.\n Changes are live (not next-spawn).\n- **`silverhand profile mcp get|set|add|remove|clear|validate|probe`**: Manage\n your own custom MCP servers (your global L1 config). `add` merges servers\n from STDIN, keeping the existing ones (`--replace` to overwrite a same-named\n one); `set` replaces the whole config; `remove --server <name>` drops one;\n `clear` removes all; `validate` checks STDIN offline; `probe --server\n <name> [--tools]` live-tests one configured server (connect + initialize).\n Config changes apply on your **next spawn**, not the running session.\n\n### Pitfalls\n- **Message body comes from STDIN**, never a flag. Use a single-quoted heredoc\n for any non-trivial body so `$`, backticks, and `\\` reach the body\n verbatim:\n\n ```bash\n silverhand message send <<'SILVERHAND_EOF'\n GitHub-Flavored Markdown \u2014 headings, lists, tables, fenced code \u2014 is supported.\n Quotes, backticks, $vars, and multi-line Markdown are all safe.\n SILVERHAND_EOF\n ```\n\n For a short single-line body, `printf \"%s\" \"hello\" | silverhand message send`\n is equivalent. An attachment-only send may omit stdin and pass\n `--attachment <id>`; with neither text nor attachment it fails before sending.\n- **Stale sends.** A send may fail with `code: 'conflict'` /\n `details.subkind: 'message_stale'` when the conversation advanced before your\n message was inserted. Don't blindly retry: read `details.newer_messages` and\n decide. Resend a still-valid draft with `--stale-resolution unaffected`, a\n changed one with `--stale-resolution revised`, or drop it with\n `silverhand message stale-resolve --resolution obsolete`. The daemon records\n the stale response's `details.current_seq` as your new boundary, so the retry\n re-checks against what you just inspected. Use `--anyway` (records\n `force_send`; don't combine with `--stale-resolution`) only when a busy\n conversation repeatedly re-holds an unchanged but necessary message."}function rI(t){let e=[];if(e.push("## This Context"),t.channelKind==="dm"?e.push(`- DM channel: \`${t.channelName}\` (1:1 with the user). MEMORY.md /`," notes/ here are this DM's L2 memory and stay private to it."):e.push(`- Workspace: \`${t.channelName}\` (regular workspace). Use this`," workspace's L2 MEMORY.md / notes/ for workspace-scoped collaboration"," and notes; L1 `system_prompt.md` is shared across every workspace."),e.push(`- Channel: "${t.sessionTitle}"`),e.push(`- Conversation id: \`${t.conversationId}\``),t.members.length!==0){e.push("- Members in this conversation:");for(let r of t.members)e.push(` ${oI(r,t.selfAgentId)}`);e.push("- Mention rule: use `@<name>` only. `display_name` is for recognition, not mentioning.")}return e.join(`
377
- `)}function nI(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0085/g,"\\u0085")}function oI(t,e){let r=[`name: ${t.name}`,`display_name: ${nI(t.display_name)}`,`kind: ${t.kind}`];return t.kind==="agent"&&(r.push(`runtime: ${t.runtime}`),t.agent_id===e&&r.push("self: true")),`- ${r.join(", ")}`}function $_(t){let e=t.trim();if(!e)return null;let r=e.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(.+)$/),n=r?r[1].toLowerCase():null,o=r?r[2]:e,i=null,a=null;switch(n){case"http":i=`http://${o}`,a=`socks5://${o}`;break;case"https":i=`http://${o}`,a=`socks5://${o}`;break;case"socks5":case"socks5h":case"socks4":case"socks":a=e;break;case null:i=`http://${o}`,a=`socks5://${o}`;break;default:a=e;break}let c={};return i&&(c.HTTP_PROXY=i,c.http_proxy=i,c.HTTPS_PROXY=i,c.https_proxy=i),a&&(c.ALL_PROXY=a,c.all_proxy=a),Object.keys(c).length>0?c:null}var sI=1,k6=s.object({version:s.number().int().gte(sI),server_url:s.string().min(1),created_at:s.number().int().nonnegative(),updated_at:s.number().int().nonnegative()}),R6=s.object({server_url:s.string().min(1),updated_at:s.number().int().nonnegative()});var iI=new Set(["localhost","127.0.0.1","::1","[::1]"]);function z_(t){return iI.has(t.toLowerCase())}function aI(t){let e=t.indexOf("://");if(e<0)return null;let r=t.slice(e+3),n=r.search(/[/?#]/);if(n>=0&&(r=r.slice(0,n)),r.includes("@"))return null;if(r.startsWith("[")){let i=r.indexOf("]");if(i<0)return null;let a=r.slice(i+1);return a!==""&&!/^:\d*$/.test(a)?null:r.slice(0,i+1)}let o=r.indexOf(":");return o>=0&&(r=r.slice(0,o)),r}function O_(t,e){let r;try{r=new URL(t)}catch(i){return{ok:!1,reason:"malformed_url",message:i instanceof Error?`Invalid URL: ${i.message}`:"Invalid URL"}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{ok:!1,reason:"unsupported_scheme",message:`Unsupported scheme '${r.protocol}'. Use http:// or https://.`};if(!(r.pathname===""||r.pathname==="/")||r.search!==""||r.hash!=="")return{ok:!1,reason:"non_origin_url",message:`Backend URL must be an origin (scheme + host + port). Drop the path / query / fragment from '${t}' \u2014 the wizard tests and persists '${r.origin}', and admitting subpath / query / fragment would let those drift apart.`};let o=aI(t);return o===null?{ok:!1,reason:"malformed_url",message:t.slice(t.indexOf("://")+3).replace(/[/?#].*$/,"").includes("@")?"URL credentials (user@host) are not accepted":"Could not extract authority host from URL"}:z_(o)?{ok:!0,kind:"loopback",url:r}:z_(r.hostname)?{ok:!1,reason:"obfuscated_loopback_disallowed",message:`Backend host '${o}' is a disguised loopback form (URL parser would resolve it to '${r.hostname}'). Use a literal loopback address (127.0.0.1 / localhost / [::1]) if loopback is intended, or a non-loopback hostname for remote.`}:r.protocol==="https:"?{ok:!0,kind:"remote",url:r,insecure:!1}:e?.allowInsecureRemote===!0?{ok:!0,kind:"remote",url:r,insecure:!0}:{ok:!1,reason:"insecure_remote_http_disallowed",message:`Backend host '${o}' is non-loopback over http://. Use https://, or explicitly allow insecure remote HTTP for this client.`}}var D_=["task_create","task_claim","task_unclaim","task_status"];var cI=s.discriminatedUnion("kind",[s.object({kind:s.literal("user"),id:s.string().nullable(),name:s.string()}),s.object({kind:s.literal("agent"),id:s.string(),name:s.string()})]),M_={actor_kind:s.enum(["user","agent","system"]),actor_id:s.string(),actor_name:s.string(),actor_display_name:s.string().nullable(),member_kind:s.enum(["human","agent"]),member_id:s.string(),member_name:s.string(),member_display_name:s.string().nullable()},uI=s.object({subtype:s.literal("conversation_member_added"),...M_}),lI=s.object({subtype:s.literal("conversation_member_removed"),...M_}),I6=s.discriminatedUnion("subtype",[uI,lI]);var $6=s.object({subtype:s.enum(D_),task_number:s.number(),task_status:It,task_message_id:s.string(),task_title:s.string(),task_assignee:oo.nullable(),actor:cI});var z6=s.object({subtype:s.enum(D_),task_number:s.number(),task_status:It});var O6=s.object({subtype:s.literal("session_cleared"),agent_id:s.string(),agent_name:s.string(),actor_user_id:s.string().nullable(),previous_cli_session_id_prefix:s.string().nullable(),was_running:s.boolean()});var D6=s.object({subtype:s.literal("schedule_fire"),schedule_id:s.string(),title:s.string().optional(),spec_kind:s.enum(["once","interval","cron"]),spec_summary:s.string().optional(),body:s.string().optional(),actual_fire_at:s.number(),planned_fire_at:s.number().nullable(),missed_count:s.number(),next_fire_at:s.number().nullable()});var dI=s.enum(["user","agent","system"]),M6=s.object({subtype:s.literal("thread_anchor"),quoted_message_id:s.string(),quoted_conversation_id:s.string(),quoted_channel_name:s.string(),quoted_content:s.string(),quoted_from_kind:dI,quoted_from_agent_id:s.string().nullable(),quoted_from_user_id:s.string().nullable(),quoted_agent_name:s.string().nullable(),quoted_created_at:s.number()});var N6=s.object({subtype:s.literal("child_context"),parent_conversation_id:s.string(),parent_title:s.string(),summary:s.string()});var j6=s.object({subtype:s.literal("channel_context"),source_conversation_id:s.string(),source_conversation_title:s.string().optional(),created_by_agent_id:s.string(),created_by_agent_name:s.string().optional()});var L6=s.object({subtype:s.literal("rename"),old_name:s.string(),new_name:s.string(),scope:s.enum(["workspace","conversation"]).default("workspace")});var F_=3,H_=["runtime.claude","runtime.codex","runtime.cursor","runtime.qoder","transport.unix_socket","fs.local","proxy.env_inherit","agent.freshness_authority"],pI=s.object({}).strict(),ao=s.object({protocol_version:s.number().int().positive(),daemon_version:s.string(),daemon_id:s.string().min(1),instance_id:s.string().min(1),host_descriptor:s.object({name:s.string().min(1),kind:ia}).strict(),capabilities:s.array(s.string())}).strict(),mI=s.object({}).strict(),fI=s.object({pong:s.literal(!0),daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int()}),hI=s.object({}).strict(),gI=s.object({daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int(),uptime_ms:s.number().int(),intent_count:s.number().int(),runtimes:s.array(s.unknown())}),_I=s.object({message:s.string()}).strict(),yI=s.object({echoed:s.string()}).strict(),Nl=s.object({}).strict(),jl=s.object({os:s.string().min(1),os_arch:s.string().optional(),daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int(),uptime_ms:s.number().int(),active_agent_ids:s.array(s.string())}).strict(),vI=s.discriminatedUnion("enabled",[s.object({conversation_id:s.string().min(1),enabled:s.literal(!0),expires_at:s.number().int().positive()}).strict(),s.object({conversation_id:s.string().min(1),enabled:s.literal(!1)}).strict()]),bI=s.object({ok:s.literal(!0),enabled:s.boolean(),expires_at:s.number().int().positive().nullable()}).strict(),U_=s.object({ok:s.literal(!1),status:s.number().int().positive(),body_text:s.string()}).strict(),SI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),content:s.string(),target:kl.optional(),reply_to_message_id:s.string().min(1).optional(),attachment_ids:s.array(s.string().min(1)).optional(),stale_resolution_reason:Rl.optional(),freshness_bypass:s.boolean().optional()}).strict(),xI=s.union([s.object({ok:s.literal(!0),message_id:s.string().min(1),message_seq:s.number().int().nonnegative().optional(),thread_root_id:s.string().min(1).nullable().optional()}).strict(),U_]),wI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),stale_event_id:s.string().min(1).optional(),resolution_reason:s.literal("obsolete")}).strict(),kI=s.union([s.object({ok:s.literal(!0),resolved:s.literal(!0)}).strict(),s.object({ok:s.literal(!0),resolved:s.literal(!1),reason:s.literal("no_pending_stale_event")}).strict(),U_]),RI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),thread_root_id:s.string().min(1),observed_seq:s.number().int().nonnegative(),reply_target_messages:s.array(s.string().min(1)).min(1)}).strict(),PI=s.object({ok:s.literal(!0)}).strict(),Ll=s.string().min(1),EI=s.object({command:s.string().min(1),args:s.array(s.string()),env_vars:s.record(s.string()).optional()}).strict(),N_=s.object({id:s.string().min(1),name:s.string().min(1),kind:Vt}).strict(),CI=s.object({id:s.string().min(1),name:s.string().min(1)}).strict(),TI=s.object({kind:De,cli_session_id:s.string().min(1).nullable(),model:s.string().nullable(),reasoning_effort:ro.nullable(),fast_mode:s.boolean().nullable()}).strict(),AI=s.object({conversation_id:s.string().min(1),kind:_t,title:s.string(),spawned_by_agent_id:s.string().min(1).nullable(),members:s.array(xl)}).strict(),II=s.object({silverhand:s.object({auth_token:s.string().min(1)}).strict(),silverhand_cli:EI.optional()}).strict(),$I=new Set(["cwd","workspace_path","home_dir","system_prompt_path","spawn_dir","system_prompt","system_prompt_text","memory_text","consensus_text","env"]);function Ml(t,e,r=[]){if(!(t===null||typeof t!="object")){if(Array.isArray(t)){t.forEach((n,o)=>Ml(n,e,[...r,o]));return}for(let[n,o]of Object.entries(t)){let i=[...r,n];$I.has(n)&&e.addIssue({code:"custom",path:i,message:`runtime_start.options.${i.join(".")} is forbidden by the D2.0 path/byte boundary; daemon-host must derive cwd/spawn paths/prompt bytes/env locally.`}),Ml(o,e,i)}}}var zI=s.object({agent:CI,workspace:N_,workspace_memory_index:s.array(N_),session:AI,driver:TI,env_policy:II}).strict().superRefine((t,e)=>Ml(t,e)),OI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),pid:s.number().int().nullable(),phase:s.enum(["idle","spawning","startup_pending","ready","draining","exited"]),run_state:no.nullable(),started_at:s.number().int().nullable()}),q_=s.object({delivery_id:s.number().int(),message_id:s.string().min(1),seq:s.number().int().nonnegative(),thread_root_id:s.string().min(1).nullable(),delivery_kind:s.enum(["turn","observe"])}).strict(),Fl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),options:zI,startup_delivery:s.object({delivery_ids:s.array(s.number().int()).min(1),delivered_up_to_seq:s.number().int().nonnegative().optional(),deliveries:s.array(q_).optional(),text:Ll}).strict().optional()}).strict(),Hl=s.discriminatedUnion("started",[s.object({started:s.literal(!0),pid:s.number().int(),started_at:s.number().int(),startup_delivery_accepted:s.boolean().optional()}).strict(),s.object({started:s.literal(!1),reason:s.literal("init_cooldown"),cooldown_until:s.number().int().positive()}).strict()]),Ul=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),mode:s.enum(["soft","hard"]),soft_directive:Ll.optional()}).strict().superRefine((t,e)=>{t.mode==="hard"&&t.soft_directive!==void 0&&e.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is only valid when mode === 'soft'; hard mode kills the process and ignores stdin."}),t.mode==="soft"&&t.soft_directive===void 0&&e.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is required when mode === 'soft'; backend MUST supply the directive bytes (default phrasing is backend's responsibility)."})}),ql=s.discriminatedUnion("mode",[s.object({mode:s.literal("hard"),stopped:s.boolean(),exit_code:s.number().int().nullable()}).strict(),s.object({mode:s.literal("soft"),directive_delivered:s.boolean(),reason:s.enum(["not_running","write_failed","driver_refused"]).optional()}).strict()]).superRefine((t,e)=>{t.mode==="soft"&&(t.directive_delivered===!1&&t.reason===void 0&&e.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=false must carry a typed reason ('not_running' | 'write_failed' | 'driver_refused')"}),t.directive_delivered===!0&&t.reason!==void 0&&e.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=true must not carry a reason"}))}),Wl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),delivered_up_to_seq:s.number().int().nonnegative().optional(),deliveries:s.array(q_).optional(),kind:s.enum(["message","schedule_fire"]),text:Ll}).strict(),DI=s.enum(["not_running","not_initialized","startup_pending","draining","driver_not_ready","driver_refused"]),Zl=s.union([s.object({delivered:s.literal(!0),delivery_ids:s.array(s.number().int()).min(1)}).strict(),s.object({delivered:s.literal(!1),reason:DI,delivery_ids:s.array(s.number().int()).min(1)}).strict()]),Bl=s.object({conversation_id:s.string().min(1).optional(),agent_id:s.string().min(1).optional()}).strict(),Vl=s.object({runtimes:s.array(OI)}).strict(),Kl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),Gl=s.object({cleared:s.boolean()}).strict(),Jl=s.object({}).strict(),Yl=s.object({stopped_count:s.number().int().nonnegative()}).strict(),Xl=s.object({}).strict(),Ql=s.object({flushed:s.boolean()}).strict(),Ra=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),ed=s.object({paused:s.boolean()}).strict(),td=Ra,rd=s.object({resumed:s.boolean()}).strict(),MI=s.object({config_path:s.string().min(1)}).strict(),NI=s.enum(["path_not_absolute","path_not_found","path_not_a_file","parse_failed","invalid_server_url"]),jI=s.discriminatedUnion("attached",[s.object({attached:s.literal(!0),config_path:s.string().min(1),action:s.enum(["started","switched","noop"])}).strict(),s.object({attached:s.literal(!1),reason:NI,message:s.string().optional()}).strict()]),LI=s.object({}).strict(),FI=s.object({detached:s.literal(!0),action:s.enum(["detached","noop"])}).strict(),HI=s.object({}).strict(),UI=s.enum(["not_attached","config_unreadable","parse_failed","invalid_server_url"]),qI=s.discriminatedUnion("reloaded",[s.object({reloaded:s.literal(!0),action:s.enum(["reloaded","unchanged"]),config_path:s.string().min(1),host_id:s.string().min(1)}).strict(),s.object({reloaded:s.literal(!1),reason:UI,message:s.string().optional()}).strict()]),W_=Sl,Pa=s.object({}).strict(),vs=s.object({config:W_}).strict(),Ea=W_,Ca=vs,Ta=s.object({agent_id:s.string().min(1),agent_home_workspace_id:s.string().min(1),name:s.string().min(1).max(64),runtime:De,model:s.string().nullable().optional(),description:s.string().nullable().optional(),template_choice:s.enum(["default","onboarding","minimal"]).default("default")}).strict(),Aa=s.object({ok:s.literal(!0),agent_dir:s.string().min(1),agent_home_workspace_path:s.string().min(1),materialized_at:s.number().int().positive()}).strict().superRefine((t,e)=>{t.agent_home_workspace_path!==t.agent_dir&&e.addIssue({code:"custom",path:["agent_home_workspace_path"],message:"agent_home_workspace_path must equal agent_dir (\xA76.5 invariant: the DM workspace path IS the L1 dir)"})}),Ia=s.enum(["fs_quota_exceeded","fs_unavailable","agent_dir_collision","unsupported_template","unsupported_runtime","internal_error"]),Gt=s.enum(["unknown_intent","invalid_params","internal_error","shutting_down","request_too_large"]),WI=s.object({code:s.union([Gt,Ia]),message:s.string()}).strict(),$a=s.enum(["workspace_not_provisioned","workspace_path_missing","registry_unavailable"]),ZI=s.object({code:s.union([Gt,$a]),message:s.string()}).strict(),za=s.object({workspace_id:s.string().min(1),kind:Vt,requested_path:s.string().min(1).optional()}).strict(),Oa=s.object({ok:s.literal(!0),provisioned:s.boolean(),bound_workspace_path:s.string().min(1)}).strict(),Da=s.enum(["unsupported_kind","invalid_path","path_conflict","fs_quota_exceeded","fs_unavailable","registry_unavailable","internal_error"]),BI=s.object({code:s.union([Gt,Da]),message:s.string()}).strict(),Ma=s.object({agent_id:s.string().min(1),workspace_ids:s.array(s.string().min(1))}).strict(),VI=s.object({workspace_id:s.string().min(1),agent_dir:s.string().min(1)}).strict(),Na=s.object({ok:s.literal(!0),entries:s.array(VI),unresolved:s.array(s.string().min(1))}).strict(),ja=s.enum(["registry_unavailable","internal_error"]),KI=s.object({code:s.union([Gt,ja]),message:s.string()}).strict(),nd=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1).optional()}).strict(),od=s.object({ok:s.literal(!0),tree:Hg}).strict(),sd=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1).optional(),path:s.string().min(1)}).strict(),id=s.object({ok:s.literal(!0),file:Ug}).strict(),ad=s.enum(["forbidden_path","not_found","workspace_not_provisioned","registry_unavailable","fs_unavailable","internal_error"]),j_=s.object({code:s.union([Gt,ad]),message:s.string()}).strict(),La=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1),template_choice:s.enum(["default","onboarding","minimal"]).default("default")}).strict(),Fa=s.object({ok:s.literal(!0),seeded:s.boolean(),l2_present:s.boolean()}).strict(),Ha=s.enum(["workspace_not_provisioned","registry_unavailable","unsupported_template","fs_unavailable","internal_error"]),GI=s.object({code:s.union([Gt,Ha]),message:s.string()}).strict(),Ua=s.object({agent_id:s.string().min(1),scope:s.enum(["all","l2"]),workspace_ids:s.array(s.string().min(1)).default([])}).strict(),qa=s.object({ok:s.literal(!0),purged_count:s.number().int().nonnegative(),skipped_unprovisioned:s.number().int().nonnegative()}).strict(),Wa=s.enum(["partial_purge","registry_unavailable","internal_error"]),JI=s.object({code:s.union([Gt,Wa]),message:s.string()}).strict(),Za=s.object({agent_id:s.string().min(1)}).strict(),Ba=s.object({ok:s.literal(!0),raw:s.string().nullable()}).strict(),Va=s.object({agent_id:s.string().min(1),raw:s.string()}).strict(),Ka=s.object({ok:s.literal(!0),bytes_written:s.number().int().nonnegative()}).strict(),Ga=s.enum(["invalid_config","fs_unavailable","internal_error"]),L_=s.object({code:s.union([Gt,Ga]),message:s.string()}).strict(),YI=s.discriminatedUnion("kind",[s.object({kind:s.literal("profile"),agent_id:s.string().min(1)}).strict()]),cd=s.object({source:YI,server_name:s.string().min(1),include_tools:s.boolean().optional()}).strict(),ud=s.enum(["fs_unavailable","internal_error"]),XI=s.object({code:s.union([Gt,ud]),message:s.string()}).strict(),ld={hello:{params:pI,result:ao},ping:{params:mI,result:fI},status:{params:hI,result:gI},echo:{params:_I,result:yI},host_status:{params:Nl,result:jl},conversation_log_debug:{params:vI,result:bI},agent_message_send:{params:SI,result:xI},agent_stale_resolve:{params:wI,result:kI},agent_stream_observed:{params:RI,result:PI},runtime_start:{params:Fl,result:Hl,error:ZI},runtime_stop:{params:Ul,result:ql},runtime_wake:{params:Wl,result:Zl},runtime_status:{params:Bl,result:Vl},runtime_clear_session:{params:Kl,result:Gl},runtime_stop_all:{params:Jl,result:Yl},runtime_close_activity_log:{params:Xl,result:Ql},runtime_output_pause:{params:Ra,result:ed},runtime_output_resume:{params:td,result:rd},host_outbound_attach:{params:MI,result:jI},host_outbound_detach:{params:LI,result:FI},host_outbound_reload:{params:HI,result:qI},host_proxy_config_get:{params:Pa,result:vs},host_proxy_config_set:{params:Ea,result:Ca},agent_materialize:{params:Ta,result:Aa,error:WI},workspace_provision:{params:za,result:Oa,error:BI},agent_workspace_index:{params:Ma,result:Na,error:KI},agent_workspace_tree:{params:nd,result:od,error:j_},agent_workspace_file_read:{params:sd,result:id,error:j_},agent_l2_seed:{params:La,result:Fa,error:GI},agent_files_purge:{params:Ua,result:qa,error:JI},agent_profile_mcp_read:{params:Za,result:Ba,error:L_},agent_profile_mcp_write:{params:Va,result:Ka,error:L_},mcp_probe:{params:cd,result:ka,error:XI}};function Z_(t){let r=ld[t]?.error;return r||be}var B_=s.object({id:s.string().min(1),intent:s.string().min(1),params:s.unknown()}),be=s.object({code:Gt,message:s.string()}),QI=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:be}).strict()]),e$=s.object({code:s.string().min(1),message:s.string()}).strict(),t$=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:e$}).strict()]),V_=s.discriminatedUnion("event",[ao.extend({event:s.literal("ready"),socket_path:s.string(),daemon_pid:s.number().int(),started_at:s.number().int()}),s.object({event:s.literal("shutting_down"),reason:s.string()}),s.object({event:s.literal("runtime_state"),conversation_id:s.string().min(1),agent_id:s.string().min(1),state:no,ts:s.number().int()}),s.object({event:s.literal("runtime_output"),conversation_id:s.string().min(1),agent_id:s.string().min(1),stream:s.enum(["stdout","stderr"]),chunk:s.string(),ts:s.number().int()}),s.object({event:s.literal("runtime_exit"),conversation_id:s.string().min(1),agent_id:s.string().min(1),code:s.number().int().nullable(),intentional:s.boolean(),ts:s.number().int()}),s.object({event:s.literal("runtime_ready_for_drain"),conversation_id:s.string().min(1),agent_id:s.string().min(1),ts:s.number().int()}),s.object({event:s.literal("runtime_startup_delivery_consumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),ts:s.number().int()}),s.object({event:s.literal("runtime_startup_delivery_failed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),reason:s.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_timeout"),conversation_id:s.string().min(1),agent_id:s.string().min(1),timeout_reason:s.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:s.number().int().nonnegative(),timeout_ms:s.number().int().nonnegative(),retrying:s.boolean(),retry_attempt:s.number().int().nonnegative(),max_retries:s.number().int().nonnegative(),cooldown_until:s.number().int().positive().optional(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_retrying"),conversation_id:s.string().min(1),agent_id:s.string().min(1),retry_attempt:s.number().int().positive(),max_retries:s.number().int().nonnegative(),delay_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_cooldown"),conversation_id:s.string().min(1),agent_id:s.string().min(1),cooldown_until:s.number().int().positive(),attempts_exhausted:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_compaction_stale"),conversation_id:s.string().min(1),agent_id:s.string().min(1),elapsed_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_output_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),dropped_count:s.number().int().nonnegative(),bytes_dropped:s.number().int().nonnegative(),since_ts:s.number().int()}),s.object({event:s.literal("runtime_output_paused"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}),s.object({event:s.literal("runtime_output_resumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}),s.object({event:s.literal("runtime_parsed_event"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed:so,ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_parsed_event_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed_kind:Sa,encoded_bytes:s.number().int().nonnegative(),reason:s.literal("frame_too_large"),ts:s.number().int()}).strict()]),K_=s.union([B_,QI,V_]),lG=s.union([B_,t$,V_]),ur=1*1024*1024;function Jt(t){let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>ur)throw new Error(`host frame exceeds MAX_FRAME_BYTES (${ur})`);return`${e}
378
- `}function Ja(t,e){let r=t+e,n=[],o=0,i=!1;for(;;){let c=r.indexOf(`
379
- `,o);if(c===-1)break;let u=r.slice(o,c);if(o=c+1,u.length!==0){if(Buffer.byteLength(u,"utf8")>ur)return i=!0,{frames:n,leftover:"",overflow:i};n.push(u)}}let a=r.slice(o);return Buffer.byteLength(a,"utf8")>ur?{frames:n,leftover:"",overflow:!0}:{frames:n,leftover:a,overflow:i}}import{existsSync as r$,mkdirSync as n$,readFileSync as o$,renameSync as s$,unlinkSync as i$,writeFileSync as a$}from"node:fs";import{dirname as J_,join as G_}from"node:path";import{homedir as c$}from"node:os";var u$=ao.pick({daemon_id:!0,host_descriptor:!0}).strict(),Ya=Object.freeze({daemon_id:"local",host_descriptor:Object.freeze({name:"local",kind:"local"})});function Y_(t){return t?G_(J_(t),"identity.json"):G_(c$(),".silverhand","daemon","identity.json")}function X_(t){if(!r$(t)){n$(J_(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;try{a$(r,`${JSON.stringify(Ya,null,2)}
380
- `,{mode:384}),s$(r,t)}catch(n){try{i$(r)}catch{}throw n}return Ya}let e=JSON.parse(o$(t,"utf-8"));return u$.parse(e)}var mn="0.0.1-alpha.7";function Xa(t,e=Ya){return{protocol_version:F_,daemon_version:mn,daemon_id:e.daemon_id,instance_id:t,host_descriptor:e.host_descriptor,capabilities:[...H_]}}import{execFileSync as l$}from"node:child_process";import{readFileSync as d$}from"node:fs";import{arch as p$,platform as m$,release as dd}from"node:os";function Q_(){let t=m$();return t==="darwin"?f$():t==="linux"?h$():`${t} ${dd()}`.trim()}function ey(){return p$()}function f$(){try{let t=l$("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim();if(t)return`macOS ${t}`}catch{}return`macOS ${dd()}`}function h$(){try{let t=d$("/etc/os-release","utf8");for(let e of t.split(`
381
- `)){let r=e.match(/^PRETTY_NAME=(.+)$/);if(!r||r[1]===void 0)continue;let o=r[1].trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1");if(o)return o}}catch{}return`Linux ${dd()}`}function pd(t,e){let{status:r,intent:n}=e;t[r==="error"?"warn":n==="host_status"?"debug":"info"]({kind:"intent",...e},`intent ${n} ${r}`)}function md(t,e){t.info({kind:"event",...e},`event ${e.event}`)}function Ar(t,e){let r=e.action==="cli_launcher_unavailable"?"warn":"info";t[r]({kind:"daemon",...e},`daemon ${e.action}`)}function ty(t,e){t.warn({kind:"backpressure",...e},`backpressure ${e.action}`)}var Pe=class extends Error{};var Qa=class{logger;startedAt;now;helloResult;supervisor;hostOutboundAttachHandler;hostOutboundDetachHandler;hostOutboundReloadHandler;hostProxyConfigGetHandler;hostProxyConfigSetHandler;agentMaterializeHandler;workspaceProvisionHandler;agentWorkspaceIndexHandler;agentWorkspaceTreeHandler;agentWorkspaceFileReadHandler;agentL2SeedHandler;agentFilesPurgeHandler;agentProfileMcpReadHandler;agentProfileMcpWriteHandler;mcpProbeHandler;intentCount=0;shuttingDown=!1;constructor(e){this.logger=e.logger,this.now=e.now??Date.now,this.startedAt=e.startedAt??this.now(),this.helloResult=e.helloResult??Xa("__test_instance__"),this.supervisor=e.supervisor,this.hostOutboundAttachHandler=e.hostOutboundAttachHandler,this.hostOutboundDetachHandler=e.hostOutboundDetachHandler,this.hostOutboundReloadHandler=e.hostOutboundReloadHandler,this.hostProxyConfigGetHandler=e.hostProxyConfigGetHandler,this.hostProxyConfigSetHandler=e.hostProxyConfigSetHandler,this.agentMaterializeHandler=e.agentMaterializeHandler,this.workspaceProvisionHandler=e.workspaceProvisionHandler,this.agentWorkspaceIndexHandler=e.agentWorkspaceIndexHandler,this.agentWorkspaceTreeHandler=e.agentWorkspaceTreeHandler,this.agentWorkspaceFileReadHandler=e.agentWorkspaceFileReadHandler,this.agentL2SeedHandler=e.agentL2SeedHandler,this.agentFilesPurgeHandler=e.agentFilesPurgeHandler,this.agentProfileMcpReadHandler=e.agentProfileMcpReadHandler,this.agentProfileMcpWriteHandler=e.agentProfileMcpWriteHandler,this.mcpProbeHandler=e.mcpProbeHandler}markShuttingDown(){this.shuttingDown=!0}isShuttingDown(){return this.shuttingDown}getStartedAt(){return this.startedAt}getIntentCount(){return this.intentCount}getHelloResult(){return{...this.helloResult,host_descriptor:{...this.helloResult.host_descriptor},capabilities:[...this.helloResult.capabilities]}}async dispatch(e,r,n){let o=this.now(),i=typeof n=="object"&&n!==null&&"conversation_id"in n?String(n.conversation_id):void 0,a=typeof n=="object"&&n!==null&&"agent_id"in n?String(n.agent_id):void 0;pd(this.logger,{intent:r,request_id:e,status:"received",conversationId:i,agent_id:a});let c=d=>{let p="error"in d;return pd(this.logger,{intent:r,request_id:e,status:p?"error":"ok",conversationId:i,agent_id:a,error_code:p?d.error.code:void 0,duration_ms:this.now()-o}),d};if(this.shuttingDown)return c(this.errorFrame(e,{code:"shutting_down",message:"daemon is shutting down"}));let u=ld[r];if(!u)return c(this.errorFrame(e,{code:"unknown_intent",message:`unknown intent: ${r}`}));let l=u.params.safeParse(n);if(!l.success)return c(this.errorFrame(e,{code:"invalid_params",message:l.error.errors.map(d=>`${d.path.join(".")}: ${d.message}`).join("; ")}));this.intentCount+=1;try{let d=await this.runHandler(r,l.data),p=u.result.safeParse(d);return p.success?c({id:e,result:p.data}):(this.logger.error({intent:r,issues:p.error.errors.map(m=>`${m.path.join(".")}: ${m.message}`).join("; ")},"daemon emitted result that does not match schema"),c(this.errorFrame(e,{code:"internal_error",message:`daemon result drift for intent ${r}`})))}catch(d){if(d instanceof Pe){let m=Z_(r).safeParse({code:d.code,message:d.message});return m.success?(this.logger.warn({intent:r,err:d.message,code:d.code},"intent handler returned typed error"),c(this.typedErrorFrame(e,d.code,d.message))):(this.logger.error({intent:r,err:d.message,code:d.code,issues:m.error.errors.map(f=>`${f.path.join(".")}: ${f.message}`).join("; ")},"intent handler returned a code not in its IPC error taxonomy; emitting internal_error"),c(this.errorFrame(e,{code:"internal_error",message:`drift: code "${d.code}" not in ${r} error taxonomy`})))}return this.logger.error({intent:r,err:d instanceof Error?d.message:String(d)},"intent handler threw"),c(this.errorFrame(e,{code:"internal_error",message:d instanceof Error?d.message:String(d)}))}}errorFrame(e,r){return{id:e,error:r}}typedErrorFrame(e,r,n){return{id:e,error:{code:r,message:n}}}async runHandler(e,r){switch(e){case"hello":return this.getHelloResult();case"ping":return{pong:!0,daemon_pid:process.pid,daemon_version:mn,started_at:this.startedAt};case"status":return{daemon_pid:process.pid,daemon_version:mn,started_at:this.startedAt,uptime_ms:this.now()-this.startedAt,intent_count:this.intentCount,runtimes:this.supervisor?(await this.supervisor.status({})).runtimes:[]};case"echo":return{echoed:r.message};case"host_status":{let n=new Set(["spawning","startup_pending","ready","draining"]);return{os:Q_(),os_arch:ey(),daemon_pid:process.pid,daemon_version:mn,started_at:this.startedAt,uptime_ms:this.now()-this.startedAt,active_agent_ids:this.supervisor?Array.from(new Set((await this.supervisor.status({})).runtimes.filter(o=>n.has(o.phase)).map(o=>o.agent_id))):[]}}case"conversation_log_debug":{let n=r;return n.enabled?(this.logger.logControl.enableConversationDebug(n.conversation_id,n.expires_at),{ok:!0,enabled:!0,expires_at:n.expires_at}):(this.logger.logControl.disableConversationDebug(n.conversation_id),{ok:!0,enabled:!1,expires_at:null})}case"agent_message_send":return this.requireSupervisor().agentMessageSend(r);case"agent_stale_resolve":return this.requireSupervisor().agentStaleResolve(r);case"agent_stream_observed":return this.requireSupervisor().agentStreamObserved(r);case"runtime_start":return this.requireSupervisor().start(r);case"runtime_stop":return this.requireSupervisor().stop(r);case"runtime_wake":return this.requireSupervisor().wake(r);case"runtime_status":return this.requireSupervisor().status(r);case"runtime_clear_session":return this.requireSupervisor().clearSession(r);case"runtime_stop_all":return this.requireSupervisor().stopAll(r);case"runtime_close_activity_log":return this.requireSupervisor().closeActivityLog(r);case"runtime_output_pause":return this.requireSupervisor().pauseOutput(r);case"runtime_output_resume":return this.requireSupervisor().resumeOutput(r);case"host_outbound_attach":return this.requireHostOutboundAttachHandler()(r);case"host_outbound_detach":return this.requireHostOutboundDetachHandler()();case"host_outbound_reload":return this.requireHostOutboundReloadHandler()();case"host_proxy_config_get":return this.requireHostProxyConfigGetHandler()();case"host_proxy_config_set":return this.requireHostProxyConfigSetHandler()(r);case"agent_materialize":return this.requireAgentMaterializeHandler()(r);case"workspace_provision":return this.requireWorkspaceProvisionHandler()(r);case"agent_workspace_index":return this.requireAgentWorkspaceIndexHandler()(r);case"agent_workspace_tree":return this.requireAgentWorkspaceTreeHandler()(r);case"agent_workspace_file_read":return this.requireAgentWorkspaceFileReadHandler()(r);case"agent_l2_seed":return this.requireAgentL2SeedHandler()(r);case"agent_files_purge":return this.requireAgentFilesPurgeHandler()(r);case"agent_profile_mcp_read":return this.requireAgentProfileMcpReadHandler()(r);case"agent_profile_mcp_write":return this.requireAgentProfileMcpWriteHandler()(r);case"mcp_probe":return this.requireMcpProbeHandler()(r)}}requireSupervisor(){if(!this.supervisor)throw new Error("runtime_* intent reached dispatcher with no supervisor wired");return this.supervisor}requireHostOutboundAttachHandler(){if(!this.hostOutboundAttachHandler)throw new Error("host_outbound_attach intent reached dispatcher with no handler wired");return this.hostOutboundAttachHandler}requireHostOutboundDetachHandler(){if(!this.hostOutboundDetachHandler)throw new Error("host_outbound_detach intent reached dispatcher with no handler wired");return this.hostOutboundDetachHandler}requireHostOutboundReloadHandler(){if(!this.hostOutboundReloadHandler)throw new Error("host_outbound_reload intent reached dispatcher with no handler wired");return this.hostOutboundReloadHandler}requireHostProxyConfigGetHandler(){if(!this.hostProxyConfigGetHandler)throw new Error("host_proxy_config_get intent reached dispatcher with no handler wired");return this.hostProxyConfigGetHandler}requireHostProxyConfigSetHandler(){if(!this.hostProxyConfigSetHandler)throw new Error("host_proxy_config_set intent reached dispatcher with no handler wired");return this.hostProxyConfigSetHandler}requireAgentMaterializeHandler(){if(!this.agentMaterializeHandler)throw new Error("agent_materialize intent reached dispatcher with no handler wired");return this.agentMaterializeHandler}requireWorkspaceProvisionHandler(){if(!this.workspaceProvisionHandler)throw new Error("workspace_provision intent reached dispatcher with no handler wired");return this.workspaceProvisionHandler}requireAgentWorkspaceIndexHandler(){if(!this.agentWorkspaceIndexHandler)throw new Error("agent_workspace_index intent reached dispatcher with no handler wired");return this.agentWorkspaceIndexHandler}requireAgentWorkspaceTreeHandler(){if(!this.agentWorkspaceTreeHandler)throw new Error("agent_workspace_tree intent reached dispatcher with no handler wired");return this.agentWorkspaceTreeHandler}requireAgentWorkspaceFileReadHandler(){if(!this.agentWorkspaceFileReadHandler)throw new Error("agent_workspace_file_read intent reached dispatcher with no handler wired");return this.agentWorkspaceFileReadHandler}requireAgentL2SeedHandler(){if(!this.agentL2SeedHandler)throw new Error("agent_l2_seed intent reached dispatcher with no handler wired");return this.agentL2SeedHandler}requireAgentFilesPurgeHandler(){if(!this.agentFilesPurgeHandler)throw new Error("agent_files_purge intent reached dispatcher with no handler wired");return this.agentFilesPurgeHandler}requireAgentProfileMcpReadHandler(){if(!this.agentProfileMcpReadHandler)throw new Error("agent_profile_mcp_read intent reached dispatcher with no handler wired");return this.agentProfileMcpReadHandler}requireAgentProfileMcpWriteHandler(){if(!this.agentProfileMcpWriteHandler)throw new Error("agent_profile_mcp_write intent reached dispatcher with no handler wired");return this.agentProfileMcpWriteHandler}requireMcpProbeHandler(){if(!this.mcpProbeHandler)throw new Error("mcp_probe intent reached dispatcher with no handler wired");return this.mcpProbeHandler}};import{Server as y$}from"node:net";import{chmodSync as v$,existsSync as ry,unlinkSync as ny}from"node:fs";var g$=4*1024*1024,_$=2*1024*1024,ec=class{now;highWater;lowWater;logDrop;onSummaryEvent;bySocket=new WeakMap;constructor(e={}){if(this.now=e.now??Date.now,this.highWater=e.highWaterBytes??g$,this.lowWater=e.lowWaterBytes??_$,this.lowWater>this.highWater)throw new Error(`OutputBackpressure: lowWaterBytes (${this.lowWater}) must be \u2264 highWaterBytes (${this.highWater})`);this.logDrop=e.logDrop,this.onSummaryEvent=e.onSummaryEvent}emit(e,r){if(e.destroyed||!e.writable)return"closed";let n=Jt(r);if(r.event!=="runtime_output"){try{e.write(n)}catch{return"closed"}return"sent"}let o=r.conversation_id,i=r.agent_id,a=this.getOrCreateKeyState(e,o,i);if(a.bytes_in_node_buffer+n.length>this.highWater&&e.writableNeedDrain)return a.dropping_window||(a.dropping_window={since_ts:this.now(),dropped_count:0,bytes_dropped:0}),a.dropping_window.dropped_count+=1,a.dropping_window.bytes_dropped+=n.length,this.logDrop?.({kind:"drop",conversation_id:o,agent_id:i,buffer_bytes:a.bytes_in_node_buffer,bytes_dropped:a.dropping_window.bytes_dropped,dropped_count:a.dropping_window.dropped_count}),"dropped";a.bytes_in_node_buffer+=n.length;let u=!0;try{e.write(n,()=>{let l=this.peekKeyState(e,o,i);l&&(l.bytes_in_node_buffer=Math.max(0,l.bytes_in_node_buffer-n.length),l.dropping_window&&l.bytes_in_node_buffer<=this.lowWater&&this.emitSummary(e,o,i,l))})}catch{u=!1}return u?"sent":(a.bytes_in_node_buffer=Math.max(0,a.bytes_in_node_buffer-n.length),"closed")}flushSummaries(e){let r=this.bySocket.get(e);if(r)for(let[n,o]of r)for(let[i,a]of o)a.dropping_window&&this.emitSummary(e,n,i,a)}forgetSocket(e){this.bySocket.delete(e)}__peekBytes(e,r,n){return this.peekKeyState(e,r,n)?.bytes_in_node_buffer??0}__peekWindow(e,r,n){return this.peekKeyState(e,r,n)?.dropping_window??null}peekKeyState(e,r,n){return this.bySocket.get(e)?.get(r)?.get(n)}getOrCreateKeyState(e,r,n){let o=this.bySocket.get(e);o||(o=new Map,this.bySocket.set(e,o));let i=o.get(r);i||(i=new Map,o.set(r,i));let a=i.get(n);return a||(a={bytes_in_node_buffer:0,dropping_window:null},i.set(n,a)),a}emitSummary(e,r,n,o){if(!o.dropping_window)return;let i={event:"runtime_output_dropped",conversation_id:r,agent_id:n,dropped_count:o.dropping_window.dropped_count,bytes_dropped:o.dropping_window.bytes_dropped,since_ts:o.dropping_window.since_ts};if(this.logDrop?.({kind:"summary",conversation_id:r,agent_id:n,buffer_bytes:o.bytes_in_node_buffer,bytes_dropped:o.dropping_window.bytes_dropped,dropped_count:o.dropping_window.dropped_count}),this.onSummaryEvent?.(i),o.dropping_window=null,!e.destroyed&&e.writable)try{e.write(Jt(i))}catch{}}};var tc=class{socketPath;dispatcher;logger;server;liveSockets=new Set;backpressure;constructor(e){this.socketPath=e.socketPath,this.dispatcher=e.dispatcher,this.logger=e.logger,this.backpressure=new ec({...e.backpressure,logDrop:e.backpressure?.logDrop??(r=>{r.kind==="drop"&&r.dropped_count!==1||ty(this.logger,{conversationId:r.conversation_id,agent_id:r.agent_id,action:"dropped",buffer_bytes:r.buffer_bytes,dropped_count:r.dropped_count,bytes_dropped:r.bytes_dropped})}),onSummaryEvent:e.backpressure?.onSummaryEvent??(r=>{md(this.logger,{event:r.event,conversationId:"conversation_id"in r?r.conversation_id:void 0,agent_id:"agent_id"in r?r.agent_id:void 0,dropped_count:"dropped_count"in r?r.dropped_count:void 0,bytes_dropped:"bytes_dropped"in r?r.bytes_dropped:void 0})})}),this.server=new y$(r=>this.handleConnection(r))}async start(){if(ry(this.socketPath))try{ny(this.socketPath)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"failed to remove stale socket file; listen may fail")}await new Promise((e,r)=>{let n=i=>{this.server.off("listening",o),r(i)},o=()=>{this.server.off("error",n),e()};this.server.once("error",n),this.server.once("listening",o),this.server.listen(this.socketPath)});try{v$(this.socketPath,384)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"failed to chmod socket; peers may have wider access than intended")}this.logger.info({socketPath:this.socketPath},"daemon socket listening")}async stop(e){this.dispatcher.markShuttingDown();let r={event:"shutting_down",reason:e};if(this.broadcast(r),await new Promise(n=>{this.server.close(()=>n());for(let o of this.liveSockets)o.end()}),ry(this.socketPath))try{ny(this.socketPath)}catch{}this.logger.info({reason:e},"daemon socket closed")}handleConnection(e){this.liveSockets.add(e);let r="";e.setEncoding("utf8"),e.on("data",n=>{let o=typeof n=="string"?n:n.toString("utf8"),{frames:i,leftover:a,overflow:c}=Ja(r,o);if(r=a,c){this.logger.warn({},"connection sent oversize frame; closing"),e.destroy();return}for(let u of i)this.handleLine(e,u)}),e.on("error",n=>{this.logger.warn({err:n.message,code:n.code},"connection error")}),e.on("close",()=>{this.liveSockets.delete(e),this.backpressure.forgetSocket(e)}),e.write(Jt({event:"ready",...this.dispatcher.getHelloResult(),socket_path:this.socketPath,daemon_pid:process.pid,started_at:this.dispatcher.getStartedAt()}))}async handleLine(e,r){let n;try{n=JSON.parse(r)}catch(c){this.logger.warn({kind:"connection",action:"frame_parse_failed",line_bytes:Buffer.byteLength(r,"utf8"),parse_error:c.message},"failed to parse frame as JSON; closing connection"),e.destroy();return}let o=K_.safeParse(n);if(!o.success||!("intent"in o.data)){this.logger.warn({kind:"connection",action:"frame_invalid",err:o.success?"expected_request_frame":"schema_mismatch",issue_count:o.success?0:o.error.errors.length,issue_paths:o.success?void 0:o.error.errors.map(c=>c.path.join("."))},"invalid frame; ignoring");return}let i=o.data,a=await this.dispatcher.dispatch(i.id,i.intent,i.params);try{e.write(Jt(a))}catch(c){this.logger.warn({err:c.message,id:i.id},"failed to write response; peer likely closed")}}liveConnectionCount(){return this.liveSockets.size}broadcast(e){md(this.logger,{event:e.event,conversationId:"conversation_id"in e?e.conversation_id:void 0,agent_id:"agent_id"in e?e.agent_id:void 0,delivery_ids:"delivery_ids"in e?e.delivery_ids:void 0,dropped_count:"dropped_count"in e?e.dropped_count:void 0,bytes_dropped:"bytes_dropped"in e?e.bytes_dropped:void 0});for(let r of this.liveSockets)this.backpressure.emit(r,e)}};import{createWriteStream as b$,mkdirSync as S$}from"node:fs";import{join as x$}from"node:path";function sy(t){S$(t.dir,{recursive:!0});let e=new Date().toISOString().replace(/[:.]/g,"-"),r=x$(t.dir,`daemon-${e}.log`),n=b$(r,{flags:"a"}),o=t.alsoStderr??!1,i={pid:process.pid,...t.base??{}},a=t.logControl??P$(R$()),c=Ol(i),u=(l,d,p)=>{let m=d&&typeof d=="object"&&!(d instanceof Error)?d:{data:C$(d)},f=Ol(m),_=new Date,g={ts:w$(_),ts_unix_ms:_.getTime(),level:l,msg:p??"",...c,...f};if(!E$(l,g,a))return;let y=T$(g);n.write(y+`
376
+ ${r}`}function fI(){return"## Tool Reference (silverhand CLI)\n\nUse the silverhand CLI for all chat / task / workspace / channel / thread /\nattachment / schedule operations.\n\n**CLI contract.** Subcommands default to `--json` (stdout is machine-readable).\nOn failure, stderr is the primary failure context and the command exits\nnon-zero; in JSON mode stderr also carries an error object with a stable\n`code` and `retriable` flag. Treat exit code 1 as a user/input error, 2 as a\ntemporary error that may be retried, and 3 as a failure to stop and report. This\nmanual is a command index plus the few high-risk pitfalls \u2014 flag-level detail is\ndeliberately not duplicated, so treat `silverhand <noun> <verb> --help` as the\nsource of truth for exact flags.\n\n**Run *dependent* silverhand commands one at a time.** When a later command's\ninput depends on an earlier one's result \u2014 claim-then-act, or resending a message\nafter a stale conflict \u2014 issue the first, read its output, then decide the next.\nDon't chain them in one shell command (`a && b`); a mid-chain failure leaves you\nunable to tell which step's state to trust. Independent reads (`--help`, status\nchecks, file lookups) can still run together.\n\n**Capabilities.** Some operations are gated by per-workspace capabilities a\nhuman owner/admin grants you. When you lack one, the command fails with a\n`capability_denied` error whose `details.capability` names the missing bucket\n(e.g. `send_messages`, `create_channels`, `manage_schedules`); task\nclaim/unclaim/status instead return a result entry with\n`code: 'capability_denied'` and a `capability` field. This is **not**\nretriable \u2014 don't loop; report which capability you lack and let the human\ngrant it.\n\n### Command index\n- **`silverhand message send`**: Send a message. With no `--target` it goes to\n the stream that woke this turn (channel main line, or the one thread you are\n replying inside), so the common case needs no flag. `--target channel` forces\n the main line; `--target thread:<message_id>` sends into that message's reply\n cluster (a main-line id opens/targets its thread; a reply id joins the same\n thread, no nesting). If a turn has two or more candidate threads, bare send\n fails with `ambiguous_default_target`; choose from\n `details.candidate_targets`. The result echoes `thread_root_id`.\n- **`silverhand message history`**: Read a history window;\n `--target thread:<root_message_id>` pulls a reply cluster (and advances your\n observed boundary for it).\n- **`silverhand message search`**: Search visible message text (scopes under\n **History and search**).\n- **`silverhand message react`**: Add (or `--remove`) your emoji reaction on a\n message by `--message-id`. A lightweight signal; idempotent. Use sparingly\n (see Collaboration Policy \u2192 React sparingly).\n- **`silverhand task list`**: View the task board (newest-first). Filter with `--status`\n (canonical statuses plus macros `active` / `open` / `pending` / `all`).\n- **`silverhand task create`**: Create a task without auto-claiming;\n optional `--target thread:<message_id>` attributes it to a thread.\n- **`silverhand task claim`**: Claim a task by number, or promote-and-claim a\n message by id.\n- **`silverhand task unclaim`** / **`silverhand task status`**: Release a\n claim / move a task through its status workflow.\n- **`silverhand thread follow`** / **`silverhand thread unfollow`**:\n Subscribe / unsubscribe to a reply cluster by `--root <message_id>`.\n- **`silverhand channel create`** / **`silverhand channel list`**: Create a\n top-level channel when requested / list channels.\n- **`silverhand workspace list`**: List workspaces you can access.\n- **`silverhand schedule create`** / **`silverhand schedule list`** /\n **`silverhand schedule cancel`**: Manage self-wakes.\n- **`silverhand file upload`** / **`silverhand file view`**: Upload a local\n file for an attachment id / resolve an attachment id to a readable location.\n- **`silverhand profile get`** / **`silverhand profile update`**: Read or\n change your own profile (`display_name`, `description`, avatar). Self-only;\n there is no target flag. Avatar updates can use a local file, an http(s)\n image, or clear the current avatar. `avatar_url` in output is read-only.\n Changes are live (not next-spawn).\n- **`silverhand profile mcp get|set|add|remove|clear|validate|probe`**: Manage\n your own custom MCP servers (your global L1 config). `add` merges servers\n from STDIN, keeping the existing ones (`--replace` to overwrite a same-named\n one); `set` replaces the whole config; `remove --server <name>` drops one;\n `clear` removes all; `validate` checks STDIN offline; `probe --server\n <name> [--tools]` live-tests one configured server (connect + initialize).\n Config changes apply on your **next spawn**, not the running session.\n\n### Pitfalls\n- **Message body comes from STDIN**, never a flag. Use a single-quoted heredoc\n for any non-trivial body so `$`, backticks, and `\\` reach the body\n verbatim:\n\n ```bash\n silverhand message send <<'SILVERHAND_EOF'\n GitHub-Flavored Markdown \u2014 headings, lists, tables, fenced code \u2014 is supported.\n Quotes, backticks, $vars, and multi-line Markdown are all safe.\n SILVERHAND_EOF\n ```\n\n For a short single-line body, `printf \"%s\" \"hello\" | silverhand message send`\n is equivalent. An attachment-only send may omit stdin and pass\n `--attachment <id>`; with neither text nor attachment it fails before sending.\n- **Stale sends.** A send may fail with `code: 'conflict'` /\n `details.subkind: 'message_stale'` when the conversation advanced before your\n message was inserted. Don't blindly retry: read `details.newer_messages` and\n decide. Resend a still-valid draft with `--stale-resolution unaffected`, a\n changed one with `--stale-resolution revised`, or drop it with\n `silverhand message stale-resolve --resolution obsolete`. The daemon records\n the stale response's `details.current_seq` as your new boundary, so the retry\n re-checks against what you just inspected. Use `--anyway` (records\n `force_send`; don't combine with `--stale-resolution`) only when a busy\n conversation repeatedly re-holds an unchanged but necessary message."}function hI(t){let e=[];if(e.push("## This Context"),t.channelKind==="dm"?e.push(`- DM channel: \`${t.channelName}\` (1:1 with the user). MEMORY.md /`," notes/ here are this DM's L2 memory and stay private to it."):e.push(`- Workspace: \`${t.channelName}\` (regular workspace). Use this`," workspace's L2 MEMORY.md / notes/ for workspace-scoped collaboration"," and notes; L1 `system_prompt.md` is shared across every workspace."),e.push(`- Channel: "${t.sessionTitle}"`),e.push(`- Conversation id: \`${t.conversationId}\``),t.members.length!==0){e.push("- Members in this conversation:");for(let r of t.members)e.push(` ${_I(r,t.selfAgentId)}`);e.push("- Mention rule: use `@<name>` only. `display_name` is for recognition, not mentioning.")}return e.join(`
377
+ `)}function gI(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0085/g,"\\u0085")}function _I(t,e){let r=[`name: ${t.name}`,`display_name: ${gI(t.display_name)}`,`kind: ${t.kind}`];return t.kind==="agent"&&(r.push(`runtime: ${t.runtime}`),t.agent_id===e&&r.push("self: true")),`- ${r.join(", ")}`}function L_(t){let e=t.trim();if(!e)return null;let r=e.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(.+)$/),n=r?r[1].toLowerCase():null,o=r?r[2]:e,i=null,a=null;switch(n){case"http":i=`http://${o}`,a=`socks5://${o}`;break;case"https":i=`http://${o}`,a=`socks5://${o}`;break;case"socks5":case"socks5h":case"socks4":case"socks":a=e;break;case null:i=`http://${o}`,a=`socks5://${o}`;break;default:a=e;break}let c={};return i&&(c.HTTP_PROXY=i,c.http_proxy=i,c.HTTPS_PROXY=i,c.https_proxy=i),a&&(c.ALL_PROXY=a,c.all_proxy=a),Object.keys(c).length>0?c:null}var yI=1,J6=s.object({version:s.number().int().gte(yI),server_url:s.string().min(1),created_at:s.number().int().nonnegative(),updated_at:s.number().int().nonnegative()}),Y6=s.object({server_url:s.string().min(1),updated_at:s.number().int().nonnegative()});var vI=new Set(["localhost","127.0.0.1","::1","[::1]"]);function F_(t){return vI.has(t.toLowerCase())}function bI(t){let e=t.indexOf("://");if(e<0)return null;let r=t.slice(e+3),n=r.search(/[/?#]/);if(n>=0&&(r=r.slice(0,n)),r.includes("@"))return null;if(r.startsWith("[")){let i=r.indexOf("]");if(i<0)return null;let a=r.slice(i+1);return a!==""&&!/^:\d*$/.test(a)?null:r.slice(0,i+1)}let o=r.indexOf(":");return o>=0&&(r=r.slice(0,o)),r}function H_(t,e){let r;try{r=new URL(t)}catch(i){return{ok:!1,reason:"malformed_url",message:i instanceof Error?`Invalid URL: ${i.message}`:"Invalid URL"}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{ok:!1,reason:"unsupported_scheme",message:`Unsupported scheme '${r.protocol}'. Use http:// or https://.`};if(!(r.pathname===""||r.pathname==="/")||r.search!==""||r.hash!=="")return{ok:!1,reason:"non_origin_url",message:`Backend URL must be an origin (scheme + host + port). Drop the path / query / fragment from '${t}' \u2014 the wizard tests and persists '${r.origin}', and admitting subpath / query / fragment would let those drift apart.`};let o=bI(t);return o===null?{ok:!1,reason:"malformed_url",message:t.slice(t.indexOf("://")+3).replace(/[/?#].*$/,"").includes("@")?"URL credentials (user@host) are not accepted":"Could not extract authority host from URL"}:F_(o)?{ok:!0,kind:"loopback",url:r}:F_(r.hostname)?{ok:!1,reason:"obfuscated_loopback_disallowed",message:`Backend host '${o}' is a disguised loopback form (URL parser would resolve it to '${r.hostname}'). Use a literal loopback address (127.0.0.1 / localhost / [::1]) if loopback is intended, or a non-loopback hostname for remote.`}:r.protocol==="https:"?{ok:!0,kind:"remote",url:r,insecure:!1}:e?.allowInsecureRemote===!0?{ok:!0,kind:"remote",url:r,insecure:!0}:{ok:!1,reason:"insecure_remote_http_disallowed",message:`Backend host '${o}' is non-loopback over http://. Use https://, or explicitly allow insecure remote HTTP for this client.`}}var U_=["task_create","task_claim","task_unclaim","task_status"];var SI=s.discriminatedUnion("kind",[s.object({kind:s.literal("user"),id:s.string().nullable(),name:s.string()}),s.object({kind:s.literal("agent"),id:s.string(),name:s.string()})]),q_={actor_kind:s.enum(["user","agent","system"]),actor_id:s.string(),actor_name:s.string(),actor_display_name:s.string().nullable(),member_kind:s.enum(["human","agent"]),member_id:s.string(),member_name:s.string(),member_display_name:s.string().nullable()},xI=s.object({subtype:s.literal("conversation_member_added"),...q_}),wI=s.object({subtype:s.literal("conversation_member_removed"),...q_}),nG=s.discriminatedUnion("subtype",[xI,wI]);var oG=s.object({subtype:s.enum(U_),task_number:s.number(),task_status:$t,task_message_id:s.string(),task_title:s.string(),task_assignee:so.nullable(),actor:SI});var sG=s.object({subtype:s.enum(U_),task_number:s.number(),task_status:$t});var iG=s.object({subtype:s.literal("session_cleared"),agent_id:s.string(),agent_name:s.string(),actor_user_id:s.string().nullable(),previous_cli_session_id_prefix:s.string().nullable(),was_running:s.boolean()});var aG=s.object({subtype:s.literal("schedule_fire"),schedule_id:s.string(),title:s.string().optional(),spec_kind:s.enum(["once","interval","cron"]),spec_summary:s.string().optional(),body:s.string().optional(),actual_fire_at:s.number(),planned_fire_at:s.number().nullable(),missed_count:s.number(),next_fire_at:s.number().nullable()});var kI=s.enum(["user","agent","system"]),cG=s.object({subtype:s.literal("thread_anchor"),quoted_message_id:s.string(),quoted_conversation_id:s.string(),quoted_channel_name:s.string(),quoted_content:s.string(),quoted_from_kind:kI,quoted_from_agent_id:s.string().nullable(),quoted_from_user_id:s.string().nullable(),quoted_agent_name:s.string().nullable(),quoted_created_at:s.number()});var uG=s.object({subtype:s.literal("child_context"),parent_conversation_id:s.string(),parent_title:s.string(),summary:s.string()});var lG=s.object({subtype:s.literal("channel_context"),source_conversation_id:s.string(),source_conversation_title:s.string().optional(),created_by_agent_id:s.string(),created_by_agent_name:s.string().optional()});var dG=s.object({subtype:s.literal("rename"),old_name:s.string(),new_name:s.string(),scope:s.enum(["workspace","conversation"]).default("workspace")});var V_=3,K_=["runtime.claude","runtime.codex","runtime.cursor","runtime.qoder","transport.unix_socket","fs.local","proxy.env_inherit","agent.freshness_authority"],RI=s.object({}).strict(),co=s.object({protocol_version:s.number().int().positive(),daemon_version:s.string(),daemon_id:s.string().min(1),instance_id:s.string().min(1),host_descriptor:s.object({name:s.string().min(1),kind:aa}).strict(),capabilities:s.array(s.string())}).strict(),PI=s.object({}).strict(),EI=s.object({pong:s.literal(!0),daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int()}),CI=s.object({}).strict(),TI=s.object({daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int(),uptime_ms:s.number().int(),intent_count:s.number().int(),runtimes:s.array(s.unknown())}),AI=s.object({message:s.string()}).strict(),II=s.object({echoed:s.string()}).strict(),Hl=s.object({}).strict(),Ul=s.object({os:s.string().min(1),os_arch:s.string().optional(),daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int(),uptime_ms:s.number().int(),active_agent_ids:s.array(s.string())}).strict(),Pa=s.object({force:s.boolean().optional()}).strict(),Ea=Qg,$I=s.discriminatedUnion("enabled",[s.object({conversation_id:s.string().min(1),enabled:s.literal(!0),expires_at:s.number().int().positive()}).strict(),s.object({conversation_id:s.string().min(1),enabled:s.literal(!1)}).strict()]),zI=s.object({ok:s.literal(!0),enabled:s.boolean(),expires_at:s.number().int().positive().nullable()}).strict(),G_=s.object({ok:s.literal(!1),status:s.number().int().positive(),body_text:s.string()}).strict(),OI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),content:s.string(),target:Cl.optional(),reply_to_message_id:s.string().min(1).optional(),attachment_ids:s.array(s.string().min(1)).optional(),stale_resolution_reason:Tl.optional(),freshness_bypass:s.boolean().optional()}).strict(),DI=s.union([s.object({ok:s.literal(!0),message_id:s.string().min(1),message_seq:s.number().int().nonnegative().optional(),thread_root_id:s.string().min(1).nullable().optional()}).strict(),G_]),MI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),stale_event_id:s.string().min(1).optional(),resolution_reason:s.literal("obsolete")}).strict(),NI=s.union([s.object({ok:s.literal(!0),resolved:s.literal(!0)}).strict(),s.object({ok:s.literal(!0),resolved:s.literal(!1),reason:s.literal("no_pending_stale_event")}).strict(),G_]),jI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),thread_root_id:s.string().min(1),observed_seq:s.number().int().nonnegative(),reply_target_messages:s.array(s.string().min(1)).min(1)}).strict(),LI=s.object({ok:s.literal(!0)}).strict(),ql=s.string().min(1),FI=s.object({command:s.string().min(1),args:s.array(s.string()),env_vars:s.record(s.string()).optional()}).strict(),W_=s.object({id:s.string().min(1),name:s.string().min(1),kind:Kt}).strict(),HI=s.object({id:s.string().min(1),name:s.string().min(1)}).strict(),UI=s.object({kind:De,cli_session_id:s.string().min(1).nullable(),model:s.string().nullable(),reasoning_effort:no.nullable(),fast_mode:s.boolean().nullable()}).strict(),qI=s.object({conversation_id:s.string().min(1),kind:yt,title:s.string(),spawned_by_agent_id:s.string().min(1).nullable(),members:s.array(Pl)}).strict(),WI=s.object({silverhand:s.object({auth_token:s.string().min(1)}).strict(),silverhand_cli:FI.optional()}).strict(),ZI=new Set(["cwd","workspace_path","home_dir","system_prompt_path","spawn_dir","system_prompt","system_prompt_text","memory_text","consensus_text","env"]);function Fl(t,e,r=[]){if(!(t===null||typeof t!="object")){if(Array.isArray(t)){t.forEach((n,o)=>Fl(n,e,[...r,o]));return}for(let[n,o]of Object.entries(t)){let i=[...r,n];ZI.has(n)&&e.addIssue({code:"custom",path:i,message:`runtime_start.options.${i.join(".")} is forbidden by the D2.0 path/byte boundary; daemon-host must derive cwd/spawn paths/prompt bytes/env locally.`}),Fl(o,e,i)}}}var BI=s.object({agent:HI,workspace:W_,workspace_memory_index:s.array(W_),session:qI,driver:UI,env_policy:WI}).strict().superRefine((t,e)=>Fl(t,e)),VI=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),pid:s.number().int().nullable(),phase:s.enum(["idle","spawning","startup_pending","ready","draining","exited"]),run_state:oo.nullable(),started_at:s.number().int().nullable()}),J_=s.object({delivery_id:s.number().int(),message_id:s.string().min(1),seq:s.number().int().nonnegative(),thread_root_id:s.string().min(1).nullable(),delivery_kind:s.enum(["turn","observe"])}).strict(),Wl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),options:BI,startup_delivery:s.object({delivery_ids:s.array(s.number().int()).min(1),delivered_up_to_seq:s.number().int().nonnegative().optional(),deliveries:s.array(J_).optional(),text:ql}).strict().optional()}).strict(),Zl=s.discriminatedUnion("started",[s.object({started:s.literal(!0),pid:s.number().int(),started_at:s.number().int(),startup_delivery_accepted:s.boolean().optional()}).strict(),s.object({started:s.literal(!1),reason:s.literal("init_cooldown"),cooldown_until:s.number().int().positive()}).strict()]),Bl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),mode:s.enum(["soft","hard"]),soft_directive:ql.optional()}).strict().superRefine((t,e)=>{t.mode==="hard"&&t.soft_directive!==void 0&&e.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is only valid when mode === 'soft'; hard mode kills the process and ignores stdin."}),t.mode==="soft"&&t.soft_directive===void 0&&e.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is required when mode === 'soft'; backend MUST supply the directive bytes (default phrasing is backend's responsibility)."})}),Vl=s.discriminatedUnion("mode",[s.object({mode:s.literal("hard"),stopped:s.boolean(),exit_code:s.number().int().nullable()}).strict(),s.object({mode:s.literal("soft"),directive_delivered:s.boolean(),reason:s.enum(["not_running","write_failed","driver_refused"]).optional()}).strict()]).superRefine((t,e)=>{t.mode==="soft"&&(t.directive_delivered===!1&&t.reason===void 0&&e.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=false must carry a typed reason ('not_running' | 'write_failed' | 'driver_refused')"}),t.directive_delivered===!0&&t.reason!==void 0&&e.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=true must not carry a reason"}))}),Kl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),delivered_up_to_seq:s.number().int().nonnegative().optional(),deliveries:s.array(J_).optional(),kind:s.enum(["message","schedule_fire"]),text:ql}).strict(),KI=s.enum(["not_running","not_initialized","startup_pending","draining","driver_not_ready","driver_refused"]),Gl=s.union([s.object({delivered:s.literal(!0),delivery_ids:s.array(s.number().int()).min(1)}).strict(),s.object({delivered:s.literal(!1),reason:KI,delivery_ids:s.array(s.number().int()).min(1)}).strict()]),Jl=s.object({conversation_id:s.string().min(1).optional(),agent_id:s.string().min(1).optional()}).strict(),Yl=s.object({runtimes:s.array(VI)}).strict(),Xl=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),Ql=s.object({cleared:s.boolean()}).strict(),ed=s.object({}).strict(),td=s.object({stopped_count:s.number().int().nonnegative()}).strict(),rd=s.object({}).strict(),nd=s.object({flushed:s.boolean()}).strict(),Ca=s.object({conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),od=s.object({paused:s.boolean()}).strict(),sd=Ca,id=s.object({resumed:s.boolean()}).strict(),GI=s.object({config_path:s.string().min(1)}).strict(),JI=s.enum(["path_not_absolute","path_not_found","path_not_a_file","parse_failed","invalid_server_url"]),YI=s.discriminatedUnion("attached",[s.object({attached:s.literal(!0),config_path:s.string().min(1),action:s.enum(["started","switched","noop"])}).strict(),s.object({attached:s.literal(!1),reason:JI,message:s.string().optional()}).strict()]),XI=s.object({}).strict(),QI=s.object({detached:s.literal(!0),action:s.enum(["detached","noop"])}).strict(),e$=s.object({}).strict(),t$=s.enum(["not_attached","config_unreadable","parse_failed","invalid_server_url"]),r$=s.discriminatedUnion("reloaded",[s.object({reloaded:s.literal(!0),action:s.enum(["reloaded","unchanged"]),config_path:s.string().min(1),host_id:s.string().min(1)}).strict(),s.object({reloaded:s.literal(!1),reason:t$,message:s.string().optional()}).strict()]),Y_=Rl,Ta=s.object({}).strict(),bs=s.object({config:Y_}).strict(),Aa=Y_,Ia=bs,$a=s.object({agent_id:s.string().min(1),agent_home_workspace_id:s.string().min(1),name:s.string().min(1).max(64),runtime:De,model:s.string().nullable().optional(),description:s.string().nullable().optional(),template_choice:s.enum(["default","onboarding","minimal"]).default("default")}).strict(),za=s.object({ok:s.literal(!0),agent_dir:s.string().min(1),agent_home_workspace_path:s.string().min(1),materialized_at:s.number().int().positive()}).strict().superRefine((t,e)=>{t.agent_home_workspace_path!==t.agent_dir&&e.addIssue({code:"custom",path:["agent_home_workspace_path"],message:"agent_home_workspace_path must equal agent_dir (\xA76.5 invariant: the DM workspace path IS the L1 dir)"})}),Oa=s.enum(["fs_quota_exceeded","fs_unavailable","agent_dir_collision","unsupported_template","unsupported_runtime","internal_error"]),Jt=s.enum(["unknown_intent","invalid_params","internal_error","shutting_down","request_too_large"]),n$=s.object({code:s.union([Jt,Oa]),message:s.string()}).strict(),Da=s.enum(["workspace_not_provisioned","workspace_path_missing","registry_unavailable"]),o$=s.object({code:s.union([Jt,Da]),message:s.string()}).strict(),Ma=s.object({workspace_id:s.string().min(1),kind:Kt,requested_path:s.string().min(1).optional()}).strict(),Na=s.object({ok:s.literal(!0),provisioned:s.boolean(),bound_workspace_path:s.string().min(1)}).strict(),ja=s.enum(["unsupported_kind","invalid_path","path_conflict","fs_quota_exceeded","fs_unavailable","registry_unavailable","internal_error"]),s$=s.object({code:s.union([Jt,ja]),message:s.string()}).strict(),La=s.object({agent_id:s.string().min(1),workspace_ids:s.array(s.string().min(1))}).strict(),i$=s.object({workspace_id:s.string().min(1),agent_dir:s.string().min(1)}).strict(),Fa=s.object({ok:s.literal(!0),entries:s.array(i$),unresolved:s.array(s.string().min(1))}).strict(),Ha=s.enum(["registry_unavailable","internal_error"]),a$=s.object({code:s.union([Jt,Ha]),message:s.string()}).strict(),ad=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1).optional()}).strict(),cd=s.object({ok:s.literal(!0),tree:Vg}).strict(),ud=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1).optional(),path:s.string().min(1)}).strict(),ld=s.object({ok:s.literal(!0),file:Kg}).strict(),dd=s.enum(["forbidden_path","not_found","workspace_not_provisioned","registry_unavailable","fs_unavailable","internal_error"]),Z_=s.object({code:s.union([Jt,dd]),message:s.string()}).strict(),Ua=s.object({agent_id:s.string().min(1),workspace_id:s.string().min(1),template_choice:s.enum(["default","onboarding","minimal"]).default("default")}).strict(),qa=s.object({ok:s.literal(!0),seeded:s.boolean(),l2_present:s.boolean()}).strict(),Wa=s.enum(["workspace_not_provisioned","registry_unavailable","unsupported_template","fs_unavailable","internal_error"]),c$=s.object({code:s.union([Jt,Wa]),message:s.string()}).strict(),Za=s.object({agent_id:s.string().min(1),scope:s.enum(["all","l2"]),workspace_ids:s.array(s.string().min(1)).default([])}).strict(),Ba=s.object({ok:s.literal(!0),purged_count:s.number().int().nonnegative(),skipped_unprovisioned:s.number().int().nonnegative()}).strict(),Va=s.enum(["partial_purge","registry_unavailable","internal_error"]),u$=s.object({code:s.union([Jt,Va]),message:s.string()}).strict(),Ka=s.object({agent_id:s.string().min(1)}).strict(),Ga=s.object({ok:s.literal(!0),raw:s.string().nullable()}).strict(),Ja=s.object({agent_id:s.string().min(1),raw:s.string()}).strict(),Ya=s.object({ok:s.literal(!0),bytes_written:s.number().int().nonnegative()}).strict(),Xa=s.enum(["invalid_config","fs_unavailable","internal_error"]),B_=s.object({code:s.union([Jt,Xa]),message:s.string()}).strict(),l$=s.discriminatedUnion("kind",[s.object({kind:s.literal("profile"),agent_id:s.string().min(1)}).strict()]),pd=s.object({source:l$,server_name:s.string().min(1),include_tools:s.boolean().optional()}).strict(),md=s.enum(["fs_unavailable","internal_error"]),d$=s.object({code:s.union([Jt,md]),message:s.string()}).strict(),fd={hello:{params:RI,result:co},ping:{params:PI,result:EI},status:{params:CI,result:TI},echo:{params:AI,result:II},host_status:{params:Hl,result:Ul},host_runtime_catalog:{params:Pa,result:Ea},conversation_log_debug:{params:$I,result:zI},agent_message_send:{params:OI,result:DI},agent_stale_resolve:{params:MI,result:NI},agent_stream_observed:{params:jI,result:LI},runtime_start:{params:Wl,result:Zl,error:o$},runtime_stop:{params:Bl,result:Vl},runtime_wake:{params:Kl,result:Gl},runtime_status:{params:Jl,result:Yl},runtime_clear_session:{params:Xl,result:Ql},runtime_stop_all:{params:ed,result:td},runtime_close_activity_log:{params:rd,result:nd},runtime_output_pause:{params:Ca,result:od},runtime_output_resume:{params:sd,result:id},host_outbound_attach:{params:GI,result:YI},host_outbound_detach:{params:XI,result:QI},host_outbound_reload:{params:e$,result:r$},host_proxy_config_get:{params:Ta,result:bs},host_proxy_config_set:{params:Aa,result:Ia},agent_materialize:{params:$a,result:za,error:n$},workspace_provision:{params:Ma,result:Na,error:s$},agent_workspace_index:{params:La,result:Fa,error:a$},agent_workspace_tree:{params:ad,result:cd,error:Z_},agent_workspace_file_read:{params:ud,result:ld,error:Z_},agent_l2_seed:{params:Ua,result:qa,error:c$},agent_files_purge:{params:Za,result:Ba,error:u$},agent_profile_mcp_read:{params:Ka,result:Ga,error:B_},agent_profile_mcp_write:{params:Ja,result:Ya,error:B_},mcp_probe:{params:pd,result:Ra,error:d$}};function X_(t){let r=fd[t]?.error;return r||ge}var Q_=s.object({id:s.string().min(1),intent:s.string().min(1),params:s.unknown()}),ge=s.object({code:Jt,message:s.string()}),p$=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:ge}).strict()]),m$=s.object({code:s.string().min(1),message:s.string()}).strict(),f$=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:m$}).strict()]),ey=s.discriminatedUnion("event",[co.extend({event:s.literal("ready"),socket_path:s.string(),daemon_pid:s.number().int(),started_at:s.number().int()}),s.object({event:s.literal("shutting_down"),reason:s.string()}),s.object({event:s.literal("runtime_state"),conversation_id:s.string().min(1),agent_id:s.string().min(1),state:oo,ts:s.number().int()}),s.object({event:s.literal("runtime_output"),conversation_id:s.string().min(1),agent_id:s.string().min(1),stream:s.enum(["stdout","stderr"]),chunk:s.string(),ts:s.number().int()}),s.object({event:s.literal("runtime_exit"),conversation_id:s.string().min(1),agent_id:s.string().min(1),code:s.number().int().nullable(),intentional:s.boolean(),ts:s.number().int()}),s.object({event:s.literal("runtime_ready_for_drain"),conversation_id:s.string().min(1),agent_id:s.string().min(1),ts:s.number().int()}),s.object({event:s.literal("runtime_startup_delivery_consumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),ts:s.number().int()}),s.object({event:s.literal("runtime_startup_delivery_failed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),reason:s.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_timeout"),conversation_id:s.string().min(1),agent_id:s.string().min(1),timeout_reason:s.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:s.number().int().nonnegative(),timeout_ms:s.number().int().nonnegative(),retrying:s.boolean(),retry_attempt:s.number().int().nonnegative(),max_retries:s.number().int().nonnegative(),cooldown_until:s.number().int().positive().optional(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_retrying"),conversation_id:s.string().min(1),agent_id:s.string().min(1),retry_attempt:s.number().int().positive(),max_retries:s.number().int().nonnegative(),delay_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_init_cooldown"),conversation_id:s.string().min(1),agent_id:s.string().min(1),cooldown_until:s.number().int().positive(),attempts_exhausted:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_compaction_stale"),conversation_id:s.string().min(1),agent_id:s.string().min(1),elapsed_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_output_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),dropped_count:s.number().int().nonnegative(),bytes_dropped:s.number().int().nonnegative(),since_ts:s.number().int()}),s.object({event:s.literal("runtime_output_paused"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}),s.object({event:s.literal("runtime_output_resumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}),s.object({event:s.literal("runtime_parsed_event"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed:io,ts:s.number().int()}).strict(),s.object({event:s.literal("runtime_parsed_event_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed_kind:xa,encoded_bytes:s.number().int().nonnegative(),reason:s.literal("frame_too_large"),ts:s.number().int()}).strict()]),ty=s.union([Q_,p$,ey]),MG=s.union([Q_,f$,ey]),lr=1*1024*1024;function Yt(t){let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>lr)throw new Error(`host frame exceeds MAX_FRAME_BYTES (${lr})`);return`${e}
378
+ `}function Qa(t,e){let r=t+e,n=[],o=0,i=!1;for(;;){let c=r.indexOf(`
379
+ `,o);if(c===-1)break;let u=r.slice(o,c);if(o=c+1,u.length!==0){if(Buffer.byteLength(u,"utf8")>lr)return i=!0,{frames:n,leftover:"",overflow:i};n.push(u)}}let a=r.slice(o);return Buffer.byteLength(a,"utf8")>lr?{frames:n,leftover:"",overflow:!0}:{frames:n,leftover:a,overflow:i}}import{spawn as oy}from"node:child_process";import{constants as h$}from"node:fs";import{access as g$,readdir as _$,stat as y$}from"node:fs/promises";import{delimiter as v$,join as qe}from"node:path";import{homedir as b$}from"node:os";var S$={claude:"claude",codex:"codex",cursor:"cursor-agent",gemini:"gemini",qoder:"qodercli"},x$=3e4,w$=5e3,k$={codex:{darwin:["/Applications/Codex.app/Contents/Resources/codex"]}};async function ry(t){try{return(await y$(t)).isFile()?(await g$(t,h$.X_OK),!0):!1}catch{return!1}}async function sy(t,e,r=w$){return new Promise(n=>{let o=oy(t,[...e],{stdio:["ignore","pipe","pipe"]}),i="",a="",c=!1,u=d=>{c||(c=!0,clearTimeout(l),n(d))},l=setTimeout(()=>{o.kill(),u(null)},r);o.stdout.on("data",d=>{i+=d.toString()}),o.stderr.on("data",d=>{a+=d.toString()}),o.on("error",()=>u(null)),o.on("close",d=>{u({code:d,stdout:i,stderr:a})})})}function hd(t){return t?t.split(v$).map(e=>e.trim()).filter(Boolean):[]}function R$(t){return[...new Set(t)]}async function ny(t,e){try{return(await _$(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>qe(t,n.name,e))}catch{return[]}}async function P$(t){let e=[qe(t,".volta/bin"),qe(t,".asdf/shims"),qe(t,".local/share/mise/shims"),qe(t,".nvm/current/bin"),qe(t,".fnm/aliases/default/bin")];return e.push(...await ny(qe(t,".nvm/versions/node"),"bin")),e.push(...await ny(qe(t,".fnm/node-versions"),"installation/bin")),e}function E$(t){return[qe(t,".local/bin"),qe(t,".npm-global/bin"),qe(t,".npm/bin"),qe(t,".bun/bin"),qe(t,"Library/pnpm"),qe(t,".yarn/bin"),qe(t,".config/yarn/global/node_modules/.bin"),"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/local/sbin","/opt/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"]}async function C$(t){if(!t)return[];let e=await sy(t,["-s"],2e3);if(!e||e.code!==0)return[];let r=e.stdout.match(/PATH="([^"]+)"/);return hd(r?.[1])}async function T$(t){if(!t)return[];let e="__silverhand_path_start__",r="__silverhand_path_end__",n=[`printf '%s\\n' ${e}`,`printf '%s\\n' "$PATH"`,`printf '%s\\n' ${r}`].join("; "),o=await sy(t,["-ilc",n],5e3);if(!o||o.code!==0)return[];let i=o.stdout.indexOf(e),a=o.stdout.indexOf(r);if(i<0||a<=i)return[];let c=o.stdout.slice(i+e.length,a).trim();return hd(c.split(`
380
+ `).find(Boolean))}var ec=null;function A$(t){return t.detectKinds===void 0&&t.pathEnv===void 0&&t.platform===void 0&&t.homeDir===void 0&&t.shellPath===void 0&&t.pathHelperPath===void 0&&t.extraCandidateDirs===void 0&&t.includeDefaultCandidateDirs===void 0}async function I$(t){let e=t.platform??process.platform,r=t.homeDir??b$(),n=t.shellPath===void 0?e==="darwin"?process.env.SHELL??null:null:t.shellPath,o=t.pathHelperPath===void 0?e==="darwin"?"/usr/libexec/path_helper":null:t.pathHelperPath,i=[...hd(t.pathEnv===void 0?process.env.PATH:t.pathEnv),...await T$(n),...await C$(o),...t.extraCandidateDirs??[],...t.includeDefaultCandidateDirs===!1?[]:[...E$(r),...await P$(r)]];return R$(i)}async function $$(t,e,r,n){let o=k$[t]?.[n]??[];for(let i of o)if(await ry(i))return i;for(let i of r){let a=qe(i,e);if(await ry(a))return a}return null}async function z$(t){return new Promise(e=>{let r=oy(t,["--version"],{stdio:["ignore","pipe","pipe"]}),n="",o="",i=!1,a=u=>{i||(i=!0,clearTimeout(c),e(u))};r.stdout.on("data",u=>{n+=u.toString()}),r.stderr.on("data",u=>{o+=u.toString()}),r.on("error",()=>a(null));let c=setTimeout(()=>{r.kill(),a(null)},3e4);r.on("close",()=>{let u=(n||o).trim(),l=u.match(/\d+\.\d+(?:\.\d+)?/),d=u.split(`
381
+ `)[0]?.trim();a(l?l[0]:d||null)})})}function O$(){return Wg.filter(t=>t.selectable).map(t=>t.kind)}async function D$(t,e,r){try{let n=S$[t],o=await $$(t,n,e,r);if(!o)return{kind:t,state:"absent",reason:"not_found",installed:!1,binary:null,version:null};let i=await z$(o);return{kind:t,state:i?"present":"present_unverified",reason:i?"resolved":"version_unavailable",installed:!0,binary:o,version:i}}catch{return{kind:t,state:"unknown",reason:"probe_failed",installed:!1,binary:null,version:null}}}async function gd(t={}){let e=t.now?.()??Date.now(),r=A$(t);if(r&&!t.force&&ec&&ec.expiresAt>e)return ec.response;let n=t.platform??process.platform,o=[...t.detectKinds??O$()],i=await I$(t),c={runtimes:await Promise.all(o.map(u=>D$(u,i,n))),detected_at:e};return r&&(ec={response:c,expiresAt:e+(t.cacheTtlMs??x$)}),c}async function iy(t={}){return(await gd(t)).runtimes}import{existsSync as M$,mkdirSync as N$,readFileSync as j$,renameSync as L$,unlinkSync as F$,writeFileSync as H$}from"node:fs";import{dirname as cy,join as ay}from"node:path";import{homedir as U$}from"node:os";var q$=co.pick({daemon_id:!0,host_descriptor:!0}).strict(),tc=Object.freeze({daemon_id:"local",host_descriptor:Object.freeze({name:"local",kind:"local"})});function uy(t){return t?ay(cy(t),"identity.json"):ay(U$(),".silverhand","daemon","identity.json")}function ly(t){if(!M$(t)){N$(cy(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;try{H$(r,`${JSON.stringify(tc,null,2)}
382
+ `,{mode:384}),L$(r,t)}catch(n){try{F$(r)}catch{}throw n}return tc}let e=JSON.parse(j$(t,"utf-8"));return q$.parse(e)}var fn="0.0.1-alpha.8";function rc(t,e=tc){return{protocol_version:V_,daemon_version:fn,daemon_id:e.daemon_id,instance_id:t,host_descriptor:e.host_descriptor,capabilities:[...K_]}}import{execFileSync as W$}from"node:child_process";import{readFileSync as Z$}from"node:fs";import{arch as B$,platform as V$,release as _d}from"node:os";function dy(){let t=V$();return t==="darwin"?K$():t==="linux"?G$():`${t} ${_d()}`.trim()}function py(){return B$()}function K$(){try{let t=W$("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim();if(t)return`macOS ${t}`}catch{}return`macOS ${_d()}`}function G$(){try{let t=Z$("/etc/os-release","utf8");for(let e of t.split(`
383
+ `)){let r=e.match(/^PRETTY_NAME=(.+)$/);if(!r||r[1]===void 0)continue;let o=r[1].trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1");if(o)return o}}catch{}return`Linux ${_d()}`}function yd(t,e){let{status:r,intent:n}=e;t[r==="error"?"warn":n==="host_status"?"debug":"info"]({kind:"intent",...e},`intent ${n} ${r}`)}function vd(t,e){t.info({kind:"event",...e},`event ${e.event}`)}function Ir(t,e){let r=e.action==="cli_launcher_unavailable"?"warn":"info";t[r]({kind:"daemon",...e},`daemon ${e.action}`)}function my(t,e){t.warn({kind:"backpressure",...e},`backpressure ${e.action}`)}var Pe=class extends Error{};var nc=class{logger;startedAt;now;helloResult;supervisor;hostOutboundAttachHandler;hostOutboundDetachHandler;hostOutboundReloadHandler;hostProxyConfigGetHandler;hostProxyConfigSetHandler;agentMaterializeHandler;workspaceProvisionHandler;agentWorkspaceIndexHandler;agentWorkspaceTreeHandler;agentWorkspaceFileReadHandler;agentL2SeedHandler;agentFilesPurgeHandler;agentProfileMcpReadHandler;agentProfileMcpWriteHandler;mcpProbeHandler;intentCount=0;shuttingDown=!1;constructor(e){this.logger=e.logger,this.now=e.now??Date.now,this.startedAt=e.startedAt??this.now(),this.helloResult=e.helloResult??rc("__test_instance__"),this.supervisor=e.supervisor,this.hostOutboundAttachHandler=e.hostOutboundAttachHandler,this.hostOutboundDetachHandler=e.hostOutboundDetachHandler,this.hostOutboundReloadHandler=e.hostOutboundReloadHandler,this.hostProxyConfigGetHandler=e.hostProxyConfigGetHandler,this.hostProxyConfigSetHandler=e.hostProxyConfigSetHandler,this.agentMaterializeHandler=e.agentMaterializeHandler,this.workspaceProvisionHandler=e.workspaceProvisionHandler,this.agentWorkspaceIndexHandler=e.agentWorkspaceIndexHandler,this.agentWorkspaceTreeHandler=e.agentWorkspaceTreeHandler,this.agentWorkspaceFileReadHandler=e.agentWorkspaceFileReadHandler,this.agentL2SeedHandler=e.agentL2SeedHandler,this.agentFilesPurgeHandler=e.agentFilesPurgeHandler,this.agentProfileMcpReadHandler=e.agentProfileMcpReadHandler,this.agentProfileMcpWriteHandler=e.agentProfileMcpWriteHandler,this.mcpProbeHandler=e.mcpProbeHandler}markShuttingDown(){this.shuttingDown=!0}isShuttingDown(){return this.shuttingDown}getStartedAt(){return this.startedAt}getIntentCount(){return this.intentCount}getHelloResult(){return{...this.helloResult,host_descriptor:{...this.helloResult.host_descriptor},capabilities:[...this.helloResult.capabilities]}}async dispatch(e,r,n){let o=this.now(),i=typeof n=="object"&&n!==null&&"conversation_id"in n?String(n.conversation_id):void 0,a=typeof n=="object"&&n!==null&&"agent_id"in n?String(n.agent_id):void 0;yd(this.logger,{intent:r,request_id:e,status:"received",conversationId:i,agent_id:a});let c=d=>{let p="error"in d;return yd(this.logger,{intent:r,request_id:e,status:p?"error":"ok",conversationId:i,agent_id:a,error_code:p?d.error.code:void 0,duration_ms:this.now()-o}),d};if(this.shuttingDown)return c(this.errorFrame(e,{code:"shutting_down",message:"daemon is shutting down"}));let u=fd[r];if(!u)return c(this.errorFrame(e,{code:"unknown_intent",message:`unknown intent: ${r}`}));let l=u.params.safeParse(n);if(!l.success)return c(this.errorFrame(e,{code:"invalid_params",message:l.error.errors.map(d=>`${d.path.join(".")}: ${d.message}`).join("; ")}));this.intentCount+=1;try{let d=await this.runHandler(r,l.data),p=u.result.safeParse(d);return p.success?c({id:e,result:p.data}):(this.logger.error({intent:r,issues:p.error.errors.map(m=>`${m.path.join(".")}: ${m.message}`).join("; ")},"daemon emitted result that does not match schema"),c(this.errorFrame(e,{code:"internal_error",message:`daemon result drift for intent ${r}`})))}catch(d){if(d instanceof Pe){let m=X_(r).safeParse({code:d.code,message:d.message});return m.success?(this.logger.warn({intent:r,err:d.message,code:d.code},"intent handler returned typed error"),c(this.typedErrorFrame(e,d.code,d.message))):(this.logger.error({intent:r,err:d.message,code:d.code,issues:m.error.errors.map(f=>`${f.path.join(".")}: ${f.message}`).join("; ")},"intent handler returned a code not in its IPC error taxonomy; emitting internal_error"),c(this.errorFrame(e,{code:"internal_error",message:`drift: code "${d.code}" not in ${r} error taxonomy`})))}return this.logger.error({intent:r,err:d instanceof Error?d.message:String(d)},"intent handler threw"),c(this.errorFrame(e,{code:"internal_error",message:d instanceof Error?d.message:String(d)}))}}errorFrame(e,r){return{id:e,error:r}}typedErrorFrame(e,r,n){return{id:e,error:{code:r,message:n}}}async runHandler(e,r){switch(e){case"hello":return this.getHelloResult();case"ping":return{pong:!0,daemon_pid:process.pid,daemon_version:fn,started_at:this.startedAt};case"status":return{daemon_pid:process.pid,daemon_version:fn,started_at:this.startedAt,uptime_ms:this.now()-this.startedAt,intent_count:this.intentCount,runtimes:this.supervisor?(await this.supervisor.status({})).runtimes:[]};case"echo":return{echoed:r.message};case"host_status":{let n=new Set(["spawning","startup_pending","ready","draining"]);return{os:dy(),os_arch:py(),daemon_pid:process.pid,daemon_version:fn,started_at:this.startedAt,uptime_ms:this.now()-this.startedAt,active_agent_ids:this.supervisor?Array.from(new Set((await this.supervisor.status({})).runtimes.filter(o=>n.has(o.phase)).map(o=>o.agent_id))):[]}}case"host_runtime_catalog":return gd({force:r.force===!0});case"conversation_log_debug":{let n=r;return n.enabled?(this.logger.logControl.enableConversationDebug(n.conversation_id,n.expires_at),{ok:!0,enabled:!0,expires_at:n.expires_at}):(this.logger.logControl.disableConversationDebug(n.conversation_id),{ok:!0,enabled:!1,expires_at:null})}case"agent_message_send":return this.requireSupervisor().agentMessageSend(r);case"agent_stale_resolve":return this.requireSupervisor().agentStaleResolve(r);case"agent_stream_observed":return this.requireSupervisor().agentStreamObserved(r);case"runtime_start":return this.requireSupervisor().start(r);case"runtime_stop":return this.requireSupervisor().stop(r);case"runtime_wake":return this.requireSupervisor().wake(r);case"runtime_status":return this.requireSupervisor().status(r);case"runtime_clear_session":return this.requireSupervisor().clearSession(r);case"runtime_stop_all":return this.requireSupervisor().stopAll(r);case"runtime_close_activity_log":return this.requireSupervisor().closeActivityLog(r);case"runtime_output_pause":return this.requireSupervisor().pauseOutput(r);case"runtime_output_resume":return this.requireSupervisor().resumeOutput(r);case"host_outbound_attach":return this.requireHostOutboundAttachHandler()(r);case"host_outbound_detach":return this.requireHostOutboundDetachHandler()();case"host_outbound_reload":return this.requireHostOutboundReloadHandler()();case"host_proxy_config_get":return this.requireHostProxyConfigGetHandler()();case"host_proxy_config_set":return this.requireHostProxyConfigSetHandler()(r);case"agent_materialize":return this.requireAgentMaterializeHandler()(r);case"workspace_provision":return this.requireWorkspaceProvisionHandler()(r);case"agent_workspace_index":return this.requireAgentWorkspaceIndexHandler()(r);case"agent_workspace_tree":return this.requireAgentWorkspaceTreeHandler()(r);case"agent_workspace_file_read":return this.requireAgentWorkspaceFileReadHandler()(r);case"agent_l2_seed":return this.requireAgentL2SeedHandler()(r);case"agent_files_purge":return this.requireAgentFilesPurgeHandler()(r);case"agent_profile_mcp_read":return this.requireAgentProfileMcpReadHandler()(r);case"agent_profile_mcp_write":return this.requireAgentProfileMcpWriteHandler()(r);case"mcp_probe":return this.requireMcpProbeHandler()(r)}}requireSupervisor(){if(!this.supervisor)throw new Error("runtime_* intent reached dispatcher with no supervisor wired");return this.supervisor}requireHostOutboundAttachHandler(){if(!this.hostOutboundAttachHandler)throw new Error("host_outbound_attach intent reached dispatcher with no handler wired");return this.hostOutboundAttachHandler}requireHostOutboundDetachHandler(){if(!this.hostOutboundDetachHandler)throw new Error("host_outbound_detach intent reached dispatcher with no handler wired");return this.hostOutboundDetachHandler}requireHostOutboundReloadHandler(){if(!this.hostOutboundReloadHandler)throw new Error("host_outbound_reload intent reached dispatcher with no handler wired");return this.hostOutboundReloadHandler}requireHostProxyConfigGetHandler(){if(!this.hostProxyConfigGetHandler)throw new Error("host_proxy_config_get intent reached dispatcher with no handler wired");return this.hostProxyConfigGetHandler}requireHostProxyConfigSetHandler(){if(!this.hostProxyConfigSetHandler)throw new Error("host_proxy_config_set intent reached dispatcher with no handler wired");return this.hostProxyConfigSetHandler}requireAgentMaterializeHandler(){if(!this.agentMaterializeHandler)throw new Error("agent_materialize intent reached dispatcher with no handler wired");return this.agentMaterializeHandler}requireWorkspaceProvisionHandler(){if(!this.workspaceProvisionHandler)throw new Error("workspace_provision intent reached dispatcher with no handler wired");return this.workspaceProvisionHandler}requireAgentWorkspaceIndexHandler(){if(!this.agentWorkspaceIndexHandler)throw new Error("agent_workspace_index intent reached dispatcher with no handler wired");return this.agentWorkspaceIndexHandler}requireAgentWorkspaceTreeHandler(){if(!this.agentWorkspaceTreeHandler)throw new Error("agent_workspace_tree intent reached dispatcher with no handler wired");return this.agentWorkspaceTreeHandler}requireAgentWorkspaceFileReadHandler(){if(!this.agentWorkspaceFileReadHandler)throw new Error("agent_workspace_file_read intent reached dispatcher with no handler wired");return this.agentWorkspaceFileReadHandler}requireAgentL2SeedHandler(){if(!this.agentL2SeedHandler)throw new Error("agent_l2_seed intent reached dispatcher with no handler wired");return this.agentL2SeedHandler}requireAgentFilesPurgeHandler(){if(!this.agentFilesPurgeHandler)throw new Error("agent_files_purge intent reached dispatcher with no handler wired");return this.agentFilesPurgeHandler}requireAgentProfileMcpReadHandler(){if(!this.agentProfileMcpReadHandler)throw new Error("agent_profile_mcp_read intent reached dispatcher with no handler wired");return this.agentProfileMcpReadHandler}requireAgentProfileMcpWriteHandler(){if(!this.agentProfileMcpWriteHandler)throw new Error("agent_profile_mcp_write intent reached dispatcher with no handler wired");return this.agentProfileMcpWriteHandler}requireMcpProbeHandler(){if(!this.mcpProbeHandler)throw new Error("mcp_probe intent reached dispatcher with no handler wired");return this.mcpProbeHandler}};import{Server as X$}from"node:net";import{chmodSync as Q$,existsSync as fy,unlinkSync as hy}from"node:fs";var J$=4*1024*1024,Y$=2*1024*1024,oc=class{now;highWater;lowWater;logDrop;onSummaryEvent;bySocket=new WeakMap;constructor(e={}){if(this.now=e.now??Date.now,this.highWater=e.highWaterBytes??J$,this.lowWater=e.lowWaterBytes??Y$,this.lowWater>this.highWater)throw new Error(`OutputBackpressure: lowWaterBytes (${this.lowWater}) must be \u2264 highWaterBytes (${this.highWater})`);this.logDrop=e.logDrop,this.onSummaryEvent=e.onSummaryEvent}emit(e,r){if(e.destroyed||!e.writable)return"closed";let n=Yt(r);if(r.event!=="runtime_output"){try{e.write(n)}catch{return"closed"}return"sent"}let o=r.conversation_id,i=r.agent_id,a=this.getOrCreateKeyState(e,o,i);if(a.bytes_in_node_buffer+n.length>this.highWater&&e.writableNeedDrain)return a.dropping_window||(a.dropping_window={since_ts:this.now(),dropped_count:0,bytes_dropped:0}),a.dropping_window.dropped_count+=1,a.dropping_window.bytes_dropped+=n.length,this.logDrop?.({kind:"drop",conversation_id:o,agent_id:i,buffer_bytes:a.bytes_in_node_buffer,bytes_dropped:a.dropping_window.bytes_dropped,dropped_count:a.dropping_window.dropped_count}),"dropped";a.bytes_in_node_buffer+=n.length;let u=!0;try{e.write(n,()=>{let l=this.peekKeyState(e,o,i);l&&(l.bytes_in_node_buffer=Math.max(0,l.bytes_in_node_buffer-n.length),l.dropping_window&&l.bytes_in_node_buffer<=this.lowWater&&this.emitSummary(e,o,i,l))})}catch{u=!1}return u?"sent":(a.bytes_in_node_buffer=Math.max(0,a.bytes_in_node_buffer-n.length),"closed")}flushSummaries(e){let r=this.bySocket.get(e);if(r)for(let[n,o]of r)for(let[i,a]of o)a.dropping_window&&this.emitSummary(e,n,i,a)}forgetSocket(e){this.bySocket.delete(e)}__peekBytes(e,r,n){return this.peekKeyState(e,r,n)?.bytes_in_node_buffer??0}__peekWindow(e,r,n){return this.peekKeyState(e,r,n)?.dropping_window??null}peekKeyState(e,r,n){return this.bySocket.get(e)?.get(r)?.get(n)}getOrCreateKeyState(e,r,n){let o=this.bySocket.get(e);o||(o=new Map,this.bySocket.set(e,o));let i=o.get(r);i||(i=new Map,o.set(r,i));let a=i.get(n);return a||(a={bytes_in_node_buffer:0,dropping_window:null},i.set(n,a)),a}emitSummary(e,r,n,o){if(!o.dropping_window)return;let i={event:"runtime_output_dropped",conversation_id:r,agent_id:n,dropped_count:o.dropping_window.dropped_count,bytes_dropped:o.dropping_window.bytes_dropped,since_ts:o.dropping_window.since_ts};if(this.logDrop?.({kind:"summary",conversation_id:r,agent_id:n,buffer_bytes:o.bytes_in_node_buffer,bytes_dropped:o.dropping_window.bytes_dropped,dropped_count:o.dropping_window.dropped_count}),this.onSummaryEvent?.(i),o.dropping_window=null,!e.destroyed&&e.writable)try{e.write(Yt(i))}catch{}}};var sc=class{socketPath;dispatcher;logger;server;liveSockets=new Set;backpressure;constructor(e){this.socketPath=e.socketPath,this.dispatcher=e.dispatcher,this.logger=e.logger,this.backpressure=new oc({...e.backpressure,logDrop:e.backpressure?.logDrop??(r=>{r.kind==="drop"&&r.dropped_count!==1||my(this.logger,{conversationId:r.conversation_id,agent_id:r.agent_id,action:"dropped",buffer_bytes:r.buffer_bytes,dropped_count:r.dropped_count,bytes_dropped:r.bytes_dropped})}),onSummaryEvent:e.backpressure?.onSummaryEvent??(r=>{vd(this.logger,{event:r.event,conversationId:"conversation_id"in r?r.conversation_id:void 0,agent_id:"agent_id"in r?r.agent_id:void 0,dropped_count:"dropped_count"in r?r.dropped_count:void 0,bytes_dropped:"bytes_dropped"in r?r.bytes_dropped:void 0})})}),this.server=new X$(r=>this.handleConnection(r))}async start(){if(fy(this.socketPath))try{hy(this.socketPath)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"failed to remove stale socket file; listen may fail")}await new Promise((e,r)=>{let n=i=>{this.server.off("listening",o),r(i)},o=()=>{this.server.off("error",n),e()};this.server.once("error",n),this.server.once("listening",o),this.server.listen(this.socketPath)});try{Q$(this.socketPath,384)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"failed to chmod socket; peers may have wider access than intended")}this.logger.info({socketPath:this.socketPath},"daemon socket listening")}async stop(e){this.dispatcher.markShuttingDown();let r={event:"shutting_down",reason:e};if(this.broadcast(r),await new Promise(n=>{this.server.close(()=>n());for(let o of this.liveSockets)o.end()}),fy(this.socketPath))try{hy(this.socketPath)}catch{}this.logger.info({reason:e},"daemon socket closed")}handleConnection(e){this.liveSockets.add(e);let r="";e.setEncoding("utf8"),e.on("data",n=>{let o=typeof n=="string"?n:n.toString("utf8"),{frames:i,leftover:a,overflow:c}=Qa(r,o);if(r=a,c){this.logger.warn({},"connection sent oversize frame; closing"),e.destroy();return}for(let u of i)this.handleLine(e,u)}),e.on("error",n=>{this.logger.warn({err:n.message,code:n.code},"connection error")}),e.on("close",()=>{this.liveSockets.delete(e),this.backpressure.forgetSocket(e)}),e.write(Yt({event:"ready",...this.dispatcher.getHelloResult(),socket_path:this.socketPath,daemon_pid:process.pid,started_at:this.dispatcher.getStartedAt()}))}async handleLine(e,r){let n;try{n=JSON.parse(r)}catch(c){this.logger.warn({kind:"connection",action:"frame_parse_failed",line_bytes:Buffer.byteLength(r,"utf8"),parse_error:c.message},"failed to parse frame as JSON; closing connection"),e.destroy();return}let o=ty.safeParse(n);if(!o.success||!("intent"in o.data)){this.logger.warn({kind:"connection",action:"frame_invalid",err:o.success?"expected_request_frame":"schema_mismatch",issue_count:o.success?0:o.error.errors.length,issue_paths:o.success?void 0:o.error.errors.map(c=>c.path.join("."))},"invalid frame; ignoring");return}let i=o.data,a=await this.dispatcher.dispatch(i.id,i.intent,i.params);try{e.write(Yt(a))}catch(c){this.logger.warn({err:c.message,id:i.id},"failed to write response; peer likely closed")}}liveConnectionCount(){return this.liveSockets.size}broadcast(e){vd(this.logger,{event:e.event,conversationId:"conversation_id"in e?e.conversation_id:void 0,agent_id:"agent_id"in e?e.agent_id:void 0,delivery_ids:"delivery_ids"in e?e.delivery_ids:void 0,dropped_count:"dropped_count"in e?e.dropped_count:void 0,bytes_dropped:"bytes_dropped"in e?e.bytes_dropped:void 0});for(let r of this.liveSockets)this.backpressure.emit(r,e)}};import{createWriteStream as ez,mkdirSync as tz}from"node:fs";import{join as rz}from"node:path";function _y(t){tz(t.dir,{recursive:!0});let e=new Date().toISOString().replace(/[:.]/g,"-"),r=rz(t.dir,`daemon-${e}.log`),n=ez(r,{flags:"a"}),o=t.alsoStderr??!1,i={pid:process.pid,...t.base??{}},a=t.logControl??iz(sz()),c=jl(i),u=(l,d,p)=>{let m=d&&typeof d=="object"&&!(d instanceof Error)?d:{data:cz(d)},f=jl(m),_=new Date,g={ts:nz(_),ts_unix_ms:_.getTime(),level:l,msg:p??"",...c,...f};if(!az(l,g,a))return;let y=uz(g);n.write(y+`
382
384
  `),o&&process.stderr.write(y+`
383
- `)};return{filePath:r,logControl:a,debug:(l,d)=>u("debug",l,d),info:(l,d)=>u("info",l,d),warn:(l,d)=>u("warn",l,d),error:(l,d)=>u("error",l,d),close:()=>new Promise(l=>{n.end(()=>l())})}}function w$(t){let e=-t.getTimezoneOffset(),r=e>=0?"+":"-",n=Math.abs(e);return`${t.getFullYear()}-${fn(t.getMonth()+1)}-${fn(t.getDate())} ${fn(t.getHours())}:${fn(t.getMinutes())}:${fn(t.getSeconds())}.${k$(t.getMilliseconds())} ${r}${fn(Math.floor(n/60))}:${fn(n%60)}`}function fn(t){return String(t).padStart(2,"0")}function k$(t){return String(t).padStart(3,"0")}function R$(){let t=process.env[$l];return t===void 0?"info":S_.includes(t)?t:zl(t)}function P$(t=zl(process.env[$l])){let e=t,r=new Map,n=i=>{let a=r.get(i);a&&clearTimeout(a.timer),r.delete(i)},o=(i,a=Date.now())=>{let c=r.get(i);c&&c.expiresAt<=a&&n(i)};return{getGlobalLevel:()=>e,setGlobalLevel:i=>{e=i},enableConversationDebug:(i,a)=>{n(i);let c=a-Date.now();if(c<=0)return;let u=setTimeout(()=>{r.delete(i)},c);u.unref?.(),r.set(i,{expiresAt:a,timer:u})},disableConversationDebug:i=>{n(i)},getConversationDebugStatus:i=>{o(i);let a=r.get(i);return a?{enabled:!0,expiresAt:a.expiresAt}:{enabled:!1,expiresAt:null}}}}function E$(t,e,r){if(t==="error")return!0;let n=typeof e.conversationId=="string"?e.conversationId:null,o=n&&r.getConversationDebugStatus(n).enabled?"debug":r.getGlobalLevel();return oy[t]>=oy[o]}var oy={debug:10,info:20,warn:30,error:40};function C$(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}function T$(t){try{return JSON.stringify(t,A$)}catch{return JSON.stringify({ts:t.ts,level:t.level,msg:t.msg,_stringify_error:!0})}}function A$(t,e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e}import{statSync as QO}from"node:fs";import{isAbsolute as eD}from"node:path";import{chmodSync as OO,mkdirSync as DO,readFileSync as MO,renameSync as NO,statSync as jO,unlinkSync as LO,writeFileSync as FO}from"node:fs";import{randomUUID as HO}from"node:crypto";import{dirname as UO,join as E3}from"node:path";var Jz=Tt(ev(),1),Yz=Tt(lc(),1),Xz=Tt(lo(),1),Qz=Tt(kd(),1),eO=Tt(Ed(),1),tO=Tt(zd(),1),Ve=Tt(fc(),1),rO=Tt(cv(),1);var Dd=s.string().min(1),Nd=2,nO=s.object({host_id:s.string().min(1),host_token:s.string().min(1),issued_at:s.number().int().nonnegative(),grace_until:s.number().int().positive()}).strict().superRefine((t,e)=>{t.grace_until<=t.issued_at&&e.addIssue({code:"custom",path:["grace_until"],message:"grace_until must be after issued_at"})}),oO=s.discriminatedUnion("rotated",[s.object({rotated:s.literal(!0),host_id:s.string().min(1),config_refreshed_at:s.number().int().nonnegative()}).strict(),s.object({rotated:s.literal(!1),reason:s.enum(["host_mismatch","invalid_config","write_failed"]),message:s.string().optional()}).strict()]),sO=s.object({code:s.union([be.shape.code,Ia]),message:s.string()}).strict(),iO=s.object({code:s.union([be.shape.code,Da]),message:s.string()}).strict(),aO=s.object({code:s.union([be.shape.code,ja]),message:s.string()}).strict(),uv=s.object({code:s.union([be.shape.code,ad]),message:s.string()}).strict(),cO=s.object({code:s.union([be.shape.code,Ha]),message:s.string()}).strict(),uO=s.object({code:s.union([be.shape.code,Wa]),message:s.string()}).strict(),lv=s.object({code:s.union([be.shape.code,Ga]),message:s.string()}).strict(),lO=s.object({code:s.union([be.shape.code,ud]),message:s.string()}).strict(),dO=s.object({code:s.union([be.shape.code,$a]),message:s.string()}).strict(),gc={runtime_start:{params:Fl,result:Hl,error:dO},runtime_stop:{params:Ul,result:ql,error:be},runtime_wake:{params:Wl,result:Zl,error:be},runtime_status:{params:Bl,result:Vl,error:be},runtime_clear_session:{params:Kl,result:Gl,error:be},runtime_stop_all:{params:Jl,result:Yl,error:be},runtime_close_activity_log:{params:Xl,result:Ql,error:be},runtime_output_pause:{params:Ra,result:ed,error:be},runtime_output_resume:{params:td,result:rd,error:be},rotate_token:{params:nO,result:oO,error:be},agent_materialize:{params:Ta,result:Aa,error:sO},workspace_provision:{params:za,result:Oa,error:iO},agent_workspace_index:{params:Ma,result:Na,error:aO},agent_workspace_tree:{params:nd,result:od,error:uv},agent_workspace_file_read:{params:sd,result:id,error:uv},agent_l2_seed:{params:La,result:Fa,error:cO},agent_files_purge:{params:Ua,result:qa,error:uO},agent_profile_mcp_read:{params:Za,result:Ba,error:lv},agent_profile_mcp_write:{params:Va,result:Ka,error:lv},mcp_probe:{params:cd,result:ka,error:lO},host_status:{params:Nl,result:jl,error:be},host_proxy_config_get:{params:Pa,result:vs,error:be},host_proxy_config_set:{params:Ea,result:Ca,error:be}},dv=Object.keys(gc),pO=dv.map(t=>s.object({direction:s.literal("server_to_daemon"),type:s.literal("command"),id:Dd,kind:s.literal(t),params:gc[t].params}).strict()),Es=s.discriminatedUnion("kind",pO),mO=dv.flatMap(t=>[s.object({direction:s.literal("daemon_to_server"),type:s.literal("command_response"),id:Dd,kind:s.literal(t),result:gc[t].result}).strict(),s.object({direction:s.literal("daemon_to_server"),type:s.literal("command_response"),id:Dd,kind:s.literal(t),error:gc[t].error}).strict()]),jd=s.union(mO),Md=s.number().int().nonnegative(),fO=s.object({direction:s.enum(["server_to_daemon","daemon_to_server"]),type:s.literal("heartbeat"),kind:s.literal("ping"),ts:Md}).strict(),hO=s.object({direction:s.enum(["server_to_daemon","daemon_to_server"]),type:s.literal("heartbeat"),kind:s.literal("pong"),ts:Md,echo_ts:Md}).strict(),Cs=s.discriminatedUnion("kind",[fO,hO]),gO=ao.extend({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("ready"),protocol_version:s.literal(Nd),daemon_pid:s.number().int(),started_at:s.number().int()}).strict(),_O=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("shutting_down"),reason:s.string()}).strict(),yO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_state"),conversation_id:s.string().min(1),agent_id:s.string().min(1),state:no,ts:s.number().int()}).strict(),vO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output"),conversation_id:s.string().min(1),agent_id:s.string().min(1),stream:s.enum(["stdout","stderr"]),chunk:s.string(),ts:s.number().int()}).strict(),bO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_exit"),conversation_id:s.string().min(1),agent_id:s.string().min(1),code:s.number().int().nullable(),intentional:s.boolean(),ts:s.number().int()}).strict(),SO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_ready_for_drain"),conversation_id:s.string().min(1),agent_id:s.string().min(1),ts:s.number().int()}).strict(),xO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_startup_delivery_consumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),ts:s.number().int()}).strict(),wO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_startup_delivery_failed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),reason:s.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:s.number().int()}).strict(),kO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_timeout"),conversation_id:s.string().min(1),agent_id:s.string().min(1),timeout_reason:s.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:s.number().int().nonnegative(),timeout_ms:s.number().int().nonnegative(),retrying:s.boolean(),retry_attempt:s.number().int().nonnegative(),max_retries:s.number().int().nonnegative(),cooldown_until:s.number().int().positive().optional(),ts:s.number().int()}).strict(),RO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_retrying"),conversation_id:s.string().min(1),agent_id:s.string().min(1),retry_attempt:s.number().int().positive(),max_retries:s.number().int().nonnegative(),delay_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),PO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_cooldown"),conversation_id:s.string().min(1),agent_id:s.string().min(1),cooldown_until:s.number().int().positive(),attempts_exhausted:s.number().int().nonnegative(),ts:s.number().int()}).strict(),EO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_compaction_stale"),conversation_id:s.string().min(1),agent_id:s.string().min(1),elapsed_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),CO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),dropped_count:s.number().int().nonnegative(),bytes_dropped:s.number().int().nonnegative(),since_ts:s.number().int()}).strict(),TO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_paused"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),AO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_resumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),IO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_parsed_event"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed:so,ts:s.number().int()}).strict(),$O=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_parsed_event_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed_kind:Sa,encoded_bytes:s.number().int().nonnegative(),reason:s.literal("frame_too_large"),ts:s.number().int()}).strict(),pv=s.discriminatedUnion("kind",[gO,_O,yO,vO,bO,SO,xO,wO,kO,RO,PO,EO,CO,TO,AO,IO,$O]),f3=pv.options.map(t=>t.shape.kind.value),_c=s.union([Es,jd,Cs,pv]);function bn(t){let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>ur)throw new Error(`encoded outbound frame exceeds MAX_FRAME_BYTES=${ur}`);return e}function yc(t,e){let r="error"in e?{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,error:e.error}:{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,result:e.result},n=jd.safeParse(r);return n.success?{frame:n.data}:{frame:{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,error:{code:"internal_error",message:`daemon outbound command response drift for ${t.kind}`}},drift:{summary:zO(e),issues:n.error.errors.map(o=>`${o.path.join(".")}: ${o.message}`)}}}function zO(t){if("error"in t)return{arm:"error",id:t.id,error_code:t.error.code};let e=t.result;return{arm:"result",id:t.id,result_type:Array.isArray(e)?"array":typeof e,result_keys:e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).slice(0,10):void 0}}function Ts(t){switch(t.event){case"ready":{let{event:e,socket_path:r,protocol_version:n,...o}=t;return{direction:"daemon_to_server",type:"event",kind:"ready",protocol_version:Nd,...o}}case"shutting_down":{let{event:e,...r}=t;return{direction:"daemon_to_server",type:"event",kind:t.event,...r}}default:{let{event:e,...r}=t;return{direction:"daemon_to_server",type:"event",kind:t.event,...r}}}}var vc={maxFrames:1024,maxBytes:4*1024*1024};function mv(t){return{bufferedAmount:()=>t.bufferedAmount,send:(e,r)=>t.send(e,r)}}function fv(t){return{bufferedAmount:()=>t.writableLength,send:(e,r)=>{t.write(`${e}
384
- `,r)}}}function As(t){return{kind:t.event,conversation_id:"conversation_id"in t?t.conversation_id:void 0,agent_id:"agent_id"in t?t.agent_id:void 0,ts:"ts"in t&&typeof t.ts=="number"?t.ts:void 0}}var _o=class{constructor(e,r="outbound_ws"){this.opts=e;this.logKind=r}opts;pendingFrames=0;pendingBytes=0;droppedRuntimeOutput=0;logKind;send(e){let r;try{r=bn(e.frame)}catch(a){return e.metadata.kind==="runtime_output"?(this.logRuntimeOutputDrop(e,0,a.message),"dropped"):(this.logOverflow(e,0,a.message),"overflow")}let n=Buffer.byteLength(r,"utf8"),o=this.pendingBytes+n+Math.max(0,e.writer.bufferedAmount()),i=this.pendingFrames+1;if(o>this.opts.maxBytes||i>this.opts.maxFrames)return e.metadata.kind==="runtime_output"?(this.logRuntimeOutputDrop(e,n,"buffer_limit"),"dropped"):(this.logOverflow(e,n,"buffer_limit"),"overflow");this.pendingFrames++,this.pendingBytes+=n;try{return e.writer.send(r,a=>{this.pendingFrames=Math.max(0,this.pendingFrames-1),this.pendingBytes=Math.max(0,this.pendingBytes-n),a&&e.logger.warn({kind:this.logKind,action:"event_send_callback_error",err:a.message,event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts},"daemon outbound event send callback failed")}),"sent"}catch(a){return this.pendingFrames=Math.max(0,this.pendingFrames-1),this.pendingBytes=Math.max(0,this.pendingBytes-n),e.logger.warn({kind:this.logKind,action:"event_send_failed",err:a.message,event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts},"daemon outbound event send failed"),"failed"}}reset(){this.pendingFrames=0,this.pendingBytes=0}logRuntimeOutputDrop(e,r,n){this.droppedRuntimeOutput++,e.logger.warn({kind:this.logKind,action:"runtime_output_dropped",event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts,encoded_bytes:r,pending_frames:this.pendingFrames,pending_bytes:this.pendingBytes,dropped_count:this.droppedRuntimeOutput,reason:n},"daemon outbound runtime_output dropped under write-buffer pressure")}logOverflow(e,r,n){e.logger.warn({kind:this.logKind,action:"non_droppable_overflow",event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts,encoded_bytes:r,pending_frames:this.pendingFrames,pending_bytes:this.pendingBytes,reason:n},"daemon outbound non-droppable event exceeded write-buffer cap")}};var qO=1e3,WO={minDelayMs:1e3,maxDelayMs:6e4,factor:2,jitterRatio:.25},ZO={pingIntervalMs:3e4,pongTimeoutMs:5e3},yo=class{constructor(e){this.opts=e;this.configPollMs=e.configPollMs??qO,this.backoff={...WO,...e.backoff??{}},this.heartbeat={...ZO,...e.heartbeat??{}},this.random=e.random??Math.random,this.now=e.now??Date.now,this.writeHostConfig=e.writeHostConfig??VO,this.writeBuffer=new _o({...vc,...e.buffer??{}})}opts;configPollMs;backoff;heartbeat;random;now;writeHostConfig;writeBuffer;configTimer=null;reconnectTimer=null;pingTimer=null;pongTimer=null;ws=null;desiredConfig=null;terminalCloseConfigKey=null;reconnectAttempt=0;started=!1;stopping=!1;start(){this.started||(this.started=!0,this.stopping=!1,this.pollConfig(),!this.opts.config&&this.configPollMs>0&&(this.configTimer=setInterval(()=>this.pollConfig(),this.configPollMs),this.configTimer.unref?.()))}stop(e="daemon_shutdown"){this.stopping=!0,this.clearConfigTimer(),this.clearReconnectTimer(),this.clearHeartbeatTimers();let r=this.ws;this.ws=null,r&&(r.readyState===Ve.default.OPEN||r.readyState===Ve.default.CONNECTING)&&r.close(1e3,e)}sendEvent(e){let r=Ts(e),n=As(e),o=this.ws;if(!o||o.readyState!==Ve.default.OPEN)return this.handleUnavailableSend(n),n.kind==="runtime_output"?"dropped":"failed";let i=this.writeBuffer.send({writer:mv(o),frame:r,metadata:n,logger:this.opts.logger});return i==="overflow"&&(this.opts.logger.warn({kind:"outbound_ws",action:"buffer_overflow_close",event_kind:n.kind,conversation_id:n.conversation_id,agent_id:n.agent_id,ts:n.ts,pending_frames:this.writeBuffer.pendingFrames,pending_bytes:this.writeBuffer.pendingBytes},"daemon outbound ws buffer overflow on non-droppable event; closing connection"),o.close(1013,"outbound_buffer_overflow")),i}state(){return{connected:this.ws?.readyState===Ve.default.OPEN,desiredConfigLoaded:this.desiredConfig!==null,reconnectAttempt:this.reconnectAttempt,pendingFrames:this.writeBuffer.pendingFrames,pendingBytes:this.writeBuffer.pendingBytes}}pollConfig(){if(this.stopping)return;let e=this.readConfig();if(!e.ok){(this.desiredConfig!==null||this.ws!==null)&&this.opts.logger.warn({kind:"outbound_ws",action:"config_unavailable",config_path:this.configLabel(),reason:e.reason},"daemon outbound config unavailable; disconnecting"),this.desiredConfig=null,this.closeForConfigChange("config_unavailable");return}let r;try{r=vo(e.config.server_url,{allowInsecureRemote:e.config.allow_insecure_remote===!0})}catch(o){this.opts.logger.warn({kind:"outbound_ws",action:"config_invalid",config_path:this.configLabel(),reason:o.message},"daemon outbound config rejected"),this.desiredConfig=null,this.closeForConfigChange("config_invalid");return}let n=hv(e.config);if(this.desiredConfig?.key===n){if(this.terminalCloseConfigKey===n)return;(!this.ws||this.ws.readyState===Ve.default.CLOSED)&&this.scheduleReconnect("config_poll");return}this.desiredConfig={raw:e.config,key:n,wsUrl:r},this.terminalCloseConfigKey=null,this.reconnectAttempt=0,this.opts.logger.info({kind:"outbound_ws",action:"config_loaded",host_id:e.config.host_id,server_origin:new URL(e.config.server_url).origin},"daemon outbound config loaded"),this.closeForConfigChange("config_changed"),this.connectNow()}connectNow(){if(this.stopping)return;let e=this.desiredConfig;if(!e||this.ws&&(this.ws.readyState===Ve.default.OPEN||this.ws.readyState===Ve.default.CONNECTING))return;this.clearReconnectTimer();let r=new Ve.default(e.wsUrl,{headers:{Authorization:`Bearer ${e.raw.host_token}`}});this.ws=r,this.opts.logger.info({kind:"outbound_ws",action:"connect_attempt",host_id:e.raw.host_id,server_origin:new URL(e.raw.server_url).origin},"daemon outbound ws connecting"),r.on("open",()=>{this.reconnectAttempt=0,this.writeBuffer.reset(),this.opts.logger.info({kind:"outbound_ws",action:"connected",host_id:e.raw.host_id},"daemon outbound ws connected"),this.sendEvent(this.opts.readyEvent()),this.startHeartbeat()}),r.on("message",n=>this.handleMessage(n)),r.on("error",n=>{this.opts.logger.warn({kind:"outbound_ws",action:"socket_error",err:n.message,host_id:e.raw.host_id},"daemon outbound ws error")}),r.on("close",(n,o)=>{this.clearHeartbeatTimers(),this.writeBuffer.reset();let i=o.toString(),a=this.ws===r;if(a&&(this.ws=null),this.opts.logger.warn({kind:"outbound_ws",action:"closed",code:n,reason:i,close_class:gv(n),host_id:e.raw.host_id},"daemon outbound ws closed"),!this.stopping&&a){if(YO(i)){this.terminalCloseConfigKey=e.key,this.clearReconnectTimer(),this.opts.logger.info({kind:"outbound_ws",action:"reconnect_suppressed",reason:i,host_id:e.raw.host_id},"daemon outbound ws reconnect suppressed after terminal close");return}this.scheduleReconnect(`close_${gv(n)}`)}})}handleMessage(e){let r=GO(e);if(!r){this.closeProtocolError("invalid_json");return}let n=Cs.safeParse(r);if(n.success){this.handleHeartbeat(n.data);return}let o=Es.safeParse(r);if(o.success){this.handleCommand(o.data);return}if(!_c.safeParse(r).success){this.closeProtocolError("invalid_frame");return}this.closeProtocolError("wrong_direction")}async handleCommand(e){let r=this.opts.dispatchCommand??BO,n=this.now(),o=e.kind==="host_status"?"debug":"info";this.opts.logger[o]({kind:"outbound_ws",action:"command_received",command_kind:e.kind,request_id:e.id},"daemon outbound command received");let i;try{if(e.kind==="rotate_token")i={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,result:this.handleRotateToken(e.params)};else{let u=await r(e),l=yc(e,u);i=l.frame,l.drift&&this.opts.logger.warn({kind:"outbound_ws",action:"command_response_shape_drift",command_kind:e.kind,request_id:e.id,response_summary:l.drift.summary,issues:l.drift.issues},"daemon outbound command response shape drift; returning internal_error")}}catch(u){i={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,error:{code:"internal_error",message:u instanceof Error?u.message:String(u)}}}let a;try{a=bn(i)}catch(u){this.opts.logger.warn({kind:"outbound_ws",action:"command_response_encode_failed",command_kind:e.kind,request_id:e.id,err:u.message},"daemon outbound command response encode failed; closing connection"),this.ws?.close(1011,"command_response_encode_failed");return}let c=this.ws;if(!c||c.readyState!==Ve.default.OPEN){this.opts.logger.warn({kind:"outbound_ws",action:"command_response_disconnected",command_kind:e.kind,request_id:e.id},"daemon outbound command response dropped because socket is disconnected");return}c.send(a,u=>{this.opts.logger[u?"warn":o]({kind:"outbound_ws",action:u?"command_response_send_failed":"command_response_sent",command_kind:e.kind,request_id:e.id,duration_ms:this.now()-n,err:u?.message},u?"daemon outbound command response send failed":"daemon outbound command response sent")})}handleRotateToken(e){let r=this.desiredConfig;if(!r||r.raw.host_id!==e.host_id)return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_host_mismatch",expected_host_id:r?.raw.host_id,command_host_id:e.host_id},"daemon outbound rotate_token rejected: host mismatch"),{rotated:!1,reason:"host_mismatch"};let n=xa.safeParse({...r.raw,host_token:e.host_token});if(!n.success)return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_invalid_config",issues:n.error.errors.map(i=>`${i.path.join(".")}: ${i.message}`)},"daemon outbound rotate_token rejected: generated config invalid"),{rotated:!1,reason:"invalid_config"};try{if(!this.opts.configPath)throw new Error("static connect command config cannot be rewritten");this.writeHostConfig(this.opts.configPath,n.data)}catch(i){return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_write_failed",err:i.message},"daemon outbound rotate_token failed to refresh config"),{rotated:!1,reason:"write_failed",message:i.message}}let o={raw:n.data,key:hv(n.data),wsUrl:r.wsUrl};return this.desiredConfig=o,this.opts.logger.info({kind:"outbound_ws",action:"rotate_token_refreshed",host_id:n.data.host_id,grace_until:e.grace_until},"daemon outbound host token refreshed in config and memory"),{rotated:!0,host_id:n.data.host_id,config_refreshed_at:this.now()}}readConfig(){return this.opts.config?{ok:!0,config:this.opts.config}:this.opts.configPath?bc(this.opts.configPath):{ok:!1,reason:"missing"}}configLabel(){return this.opts.configPath?XO(this.opts.configPath):"<memory>"}handleHeartbeat(e){if(e.direction!=="server_to_daemon"){this.closeProtocolError("wrong_direction_heartbeat");return}if(e.kind==="ping"){this.sendControlFrame({direction:"daemon_to_server",type:"heartbeat",kind:"pong",ts:this.now(),echo_ts:e.ts});return}this.clearPongTimer()}startHeartbeat(){this.clearHeartbeatTimers(),!(this.heartbeat.pingIntervalMs<=0)&&(this.pingTimer=setInterval(()=>{if(!this.ws||this.ws.readyState!==Ve.default.OPEN)return;let e=this.now();this.sendControlFrame({direction:"daemon_to_server",type:"heartbeat",kind:"ping",ts:e})&&(this.clearPongTimer(),this.pongTimer=setTimeout(()=>{this.opts.logger.warn({kind:"outbound_ws",action:"heartbeat_timeout",timeout_ms:this.heartbeat.pongTimeoutMs},"daemon outbound heartbeat timeout; closing connection"),this.ws?.close(1008,"heartbeat_timeout")},this.heartbeat.pongTimeoutMs),this.pongTimer.unref?.())},this.heartbeat.pingIntervalMs),this.pingTimer.unref?.())}sendControlFrame(e){let r=this.ws;if(!r||r.readyState!==Ve.default.OPEN)return!1;try{return r.send(bn(e)),!0}catch(n){return this.opts.logger.warn({kind:"outbound_ws",action:"control_send_failed",err:n.message},"daemon outbound control frame send failed; closing connection"),r.close(1011,"control_send_failed"),!1}}scheduleReconnect(e){if(this.stopping||!this.desiredConfig||this.reconnectTimer)return;let r=KO(this.reconnectAttempt++,this.backoff,this.random);this.opts.logger.info({kind:"outbound_ws",action:"reconnect_scheduled",reason:e,delay_ms:r,attempt:this.reconnectAttempt},"daemon outbound ws reconnect scheduled"),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectNow()},r),this.reconnectTimer.unref?.()}closeProtocolError(e){this.ws?.close(1002,e)}closeForConfigChange(e){this.clearReconnectTimer(),this.clearHeartbeatTimers();let r=this.ws;this.ws=null,r&&(r.readyState===Ve.default.OPEN||r.readyState===Ve.default.CONNECTING)&&r.close(1e3,e)}handleUnavailableSend(e){let r=e.kind==="runtime_output"?"debug":"warn";this.opts.logger[r]({kind:"outbound_ws",action:e.kind==="runtime_output"?"drop_disconnected":"event_disconnected",event_kind:e.kind,conversation_id:e.conversation_id,agent_id:e.agent_id,ts:e.ts},"daemon outbound event emitted while disconnected")}clearConfigTimer(){this.configTimer&&(clearInterval(this.configTimer),this.configTimer=null)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}clearHeartbeatTimers(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),this.clearPongTimer()}clearPongTimer(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}};async function BO(t){return{id:t.id,error:{code:"internal_error",message:"daemon outbound command dispatcher is not wired"}}}function bc(t){let e;try{e=jO(t)}catch(i){return i.code==="ENOENT"?{ok:!1,reason:"missing"}:{ok:!1,reason:"io_error"}}if(!e.isFile())return{ok:!1,reason:"not_a_file"};let r;try{r=MO(t,"utf8")}catch{return{ok:!1,reason:"io_error"}}let n;try{n=JSON.parse(r)}catch{return{ok:!1,reason:"invalid_json"}}let o=xa.safeParse(n);return o.success?{ok:!0,config:o.data}:{ok:!1,reason:"invalid_shape"}}function VO(t,e){let r=xa.parse(e);DO(UO(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${HO()}`;try{FO(n,`${JSON.stringify(r,null,2)}
385
- `,{mode:384}),NO(n,t),OO(t,384)}catch(o){try{LO(n)}catch{}throw o}}function Sc(t){let e=t.profile_version===void 0?"<none>":String(t.profile_version),r=t.allow_insecure_remote===!0?"1":"0";return`${t.server_url}\0${t.host_id}\0${t.host_token}\0allow_insecure_remote=${r}\0pv=${e}`}function vo(t,e){let r=O_(t,{allowInsecureRemote:e?.allowInsecureRemote===!0});if(!r.ok)throw r.reason==="insecure_remote_http_disallowed"?new Error("tls_required_for_non_loopback_host_ws"):r.reason==="obfuscated_loopback_disallowed"?new Error("tls_required_for_non_loopback_host_ws"):r.reason==="unsupported_scheme"?new Error(`unsupported_server_url_protocol:${t}`):new Error(`invalid_server_url:${r.reason}`);let n=new URL(va.hostConnect,r.url);return n.protocol==="http:"?(n.protocol="ws:",n.toString()):(n.protocol="wss:",n.toString())}function KO(t,e,r){let n=e.minDelayMs*Math.pow(e.factor,t),o=Math.min(e.maxDelayMs,n);if(e.jitterRatio<=0)return Math.round(o);let i=o*e.jitterRatio,a=o-i+r()*i*2;return Math.max(0,Math.round(Math.min(e.maxDelayMs,a)))}function hv(t){return Sc(t)}function GO(t){try{let e=JSON.parse(JO(t));return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}catch{return null}}function JO(t){return typeof t=="string"?t:Array.isArray(t)?Buffer.concat(t).toString("utf8"):t instanceof ArrayBuffer?Buffer.from(t).toString("utf8"):t.toString("utf8")}function gv(t){return t===1e3?"normal":t===1001?"going_away":t===1006?"abnormal":"other"}function YO(t){return t===Dg||t===Mg}function XO(t){return t.endsWith(`/${Il}`)?`.../${Il}`:".../daemon-config"}function Ld(t){return{server_origin:new URL(t.server_url).origin,host_id:t.host_id}}var kc=class{constructor(e){this.deps=e}deps;current=null;stopped=!1;attach(e){if(this.stopped)return bo("parse_failed","supervisor stopped");let{config_path:r}=e;if(!eD(r))return bo("path_not_absolute",`config_path must be absolute: ${r}`);if(this.current&&this.current.configPath===r)return Fd(r,"noop");let n;try{n=QO(r)}catch(c){return bo("path_not_found",c.message)}if(!n.isFile())return bo("path_not_a_file",`config_path is not a regular file: ${r}`);let o=bc(r);if(!o.ok)return bo("parse_failed",o.reason);try{vo(o.config.server_url,{allowInsecureRemote:o.config.allow_insecure_remote===!0})}catch(c){return bo("invalid_server_url",c.message)}let i=Sc(o.config);if(this.current){this.current.client.stop("config_path_changed"),this.current=null;let c=this.spawnClient(r);return this.current={configPath:r,fingerprint:i,binding:Ld(o.config),client:c},c.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"switched",config_path:wc(r)},"daemon outbound switched to new config path"),Fd(r,"switched")}let a=this.spawnClient(r);return this.current={configPath:r,fingerprint:i,binding:Ld(o.config),client:a},a.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"started",config_path:wc(r)},"daemon outbound started from host config"),Fd(r,"started")}reload(){if(this.stopped)return xc("not_attached","supervisor stopped");let e=this.current;if(!e)return xc("not_attached","no current outbound client; use host_outbound_attach to bootstrap");let r=bc(e.configPath);if(!r.ok){let i=r.reason==="missing"||r.reason==="not_a_file"||r.reason==="io_error"?"config_unreadable":"parse_failed";return xc(i,r.reason)}try{vo(r.config.server_url,{allowInsecureRemote:r.config.allow_insecure_remote===!0})}catch(i){return xc("invalid_server_url",i.message)}let n=Sc(r.config);if(n===e.fingerprint)return this.deps.logger.info({kind:"outbound_supervisor",action:"reload_unchanged",config_path:wc(e.configPath),host_id:r.config.host_id},"daemon outbound reload no-op (config bytes unchanged)"),{reloaded:!0,action:"unchanged",config_path:e.configPath,host_id:r.config.host_id};e.client.stop("config_reload"),this.current=null;let o=this.spawnClient(e.configPath);return this.current={configPath:e.configPath,fingerprint:n,binding:Ld(r.config),client:o},o.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"reload_swapped",config_path:wc(e.configPath),host_id:r.config.host_id},"daemon outbound reloaded with fresh config bytes"),{reloaded:!0,action:"reloaded",config_path:e.configPath,host_id:r.config.host_id}}sendEvent(e){this.current?.client.sendEvent(e)}currentBinding(){return this.current?{...this.current.binding}:null}detach(){return this.current?(this.current.client.stop("host_outbound_detach"),this.current=null,this.deps.logger.info({kind:"outbound_supervisor",action:"detached"},"daemon outbound detached on host_outbound_detach hint"),{detached:!0,action:"detached"}):{detached:!0,action:"noop"}}stop(e="daemon_shutdown"){this.stopped||(this.stopped=!0,this.current&&(this.current.client.stop(e),this.current=null))}currentConfigPath(){return this.current?.configPath??null}spawnClient(e){let r=this.deps.outboundClientFactory;return r?r(e,{logger:this.deps.logger,readyEvent:this.deps.readyEvent,dispatchCommand:this.deps.dispatchCommand}):new yo({configPath:e,logger:this.deps.logger,readyEvent:this.deps.readyEvent,dispatchCommand:this.deps.dispatchCommand})}};function Fd(t,e){return{attached:!0,config_path:t,action:e}}function bo(t,e){return{attached:!1,reason:t,message:e}}function xc(t,e){return{reloaded:!1,reason:t,message:e}}function wc(t){let e=t.lastIndexOf("/");return e<0?t:`\u2026/${t.slice(e+1)}`}import{Server as tD}from"node:net";import{chmodSync as rD,existsSync as _v,unlinkSync as yv}from"node:fs";var Rc=class{socketPath;dispatchCommand;logger;readyEvent;server;liveSockets=new Set;writeBuffers=new WeakMap;writeBufferOptions;constructor(e){this.socketPath=e.socketPath,this.dispatchCommand=e.dispatchCommand,this.logger=e.logger,this.readyEvent=e.readyEvent,this.writeBufferOptions={...vc,...e.writeBuffer??{}},this.server=new tD(r=>this.handleConnection(r))}async start(){if(_v(this.socketPath))try{yv(this.socketPath)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"local outbound: failed to remove stale socket file; listen may fail")}await new Promise((e,r)=>{let n=i=>{this.server.off("listening",o),r(i)},o=()=>{this.server.off("error",n),e()};this.server.once("error",n),this.server.once("listening",o),this.server.listen(this.socketPath)});try{rD(this.socketPath,384)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"local outbound: failed to chmod socket; peers may have wider access than intended")}this.logger.info({socketPath:this.socketPath},"local outbound frame socket listening")}async stop(){if(await new Promise(e=>{this.server.close(()=>e());for(let r of this.liveSockets)r.end()}),_v(this.socketPath))try{yv(this.socketPath)}catch{}this.logger.info({socketPath:this.socketPath},"local outbound frame socket closed")}liveConnectionCount(){return this.liveSockets.size}broadcast(e){if(this.liveSockets.size===0)return;let r=Ts(e),n=As(e);for(let o of this.liveSockets)o.destroyed||this.sendEventToSocket(o,r,n)}sendEventToSocket(e,r,n){let o=this.writeBuffers.get(e);if(!o)return;o.send({writer:fv(e),frame:r,metadata:n,logger:this.logger})==="overflow"&&(this.logger.warn({kind:"local_outbound",action:"buffer_overflow_close",event_kind:n.kind,conversation_id:n.conversation_id,agent_id:n.agent_id,ts:n.ts,pending_frames:o.pendingFrames,pending_bytes:o.pendingBytes},"local outbound buffer overflow on non-droppable event; closing connection"),e.destroy())}handleConnection(e){if(this.liveSockets.add(e),this.writeBuffers.set(e,new _o(this.writeBufferOptions,"local_outbound")),this.readyEvent){let n=this.readyEvent();this.sendEventToSocket(e,Ts(n),As(n))}let r="";e.setEncoding("utf8"),e.on("data",n=>{let o=typeof n=="string"?n:n.toString("utf8"),{frames:i,leftover:a,overflow:c}=Ja(r,o);if(r=a,c){this.logger.warn({socketPath:this.socketPath},`local outbound: inbound frame exceeded MAX_FRAME_BYTES=${ur}; closing`),e.destroy();return}for(let u of i)if(!this.handleLine(e,u)||e.destroyed)break}),e.on("error",n=>{this.logger.warn({err:n.message,code:n.code},"local outbound: connection error")}),e.on("close",()=>{this.liveSockets.delete(e),this.writeBuffers.delete(e)})}handleLine(e,r){let n;try{n=JSON.parse(r)}catch(a){return this.logger.warn({kind:"local_outbound",action:"frame_parse_failed",line_bytes:Buffer.byteLength(r,"utf8"),parse_error:a.message},"local outbound: failed to parse frame as JSON; closing connection"),e.destroy(),!1}let o=Es.safeParse(n);if(o.success)return this.handleCommand(e,o.data),!0;if(Cs.safeParse(n).success)return!0;let i=_c.safeParse(n);return this.logger.warn({kind:"local_outbound",action:"frame_invalid",err:i.success?"wrong_direction_or_type":"schema_mismatch",issue_count:o.error.errors.length,issue_paths:o.error.errors.map(a=>a.path.join("."))},"local outbound: invalid inbound frame; closing connection"),e.destroy(),!1}async handleCommand(e,r){let n=r.kind==="host_status"?"debug":"info";this.logger[n]({kind:"local_outbound",action:"command_received",command_kind:r.kind,request_id:r.id},"local outbound command received");let o;try{let a=await this.dispatchCommand(r),c=yc(r,a);o=c.frame,c.drift&&this.logger.warn({kind:"local_outbound",action:"command_response_shape_drift",command_kind:r.kind,request_id:r.id,response_summary:c.drift.summary,issues:c.drift.issues},"local outbound command response shape drift; returning internal_error")}catch(a){o={direction:"daemon_to_server",type:"command_response",id:r.id,kind:r.kind,error:{code:"internal_error",message:a instanceof Error?a.message:String(a)}}}let i;try{i=`${bn(o)}
386
- `}catch(a){this.logger.warn({kind:"local_outbound",action:"command_response_encode_failed",command_kind:r.kind,request_id:r.id,err:a.message},"local outbound command response encode failed; closing connection"),e.destroy();return}if(e.destroyed){this.logger.warn({kind:"local_outbound",action:"command_response_disconnected",command_kind:r.kind,request_id:r.id},"local outbound command response dropped because socket is disconnected");return}e.write(i)}};import{linkSync as vD,mkdirSync as Vd,readdirSync as wv,unlinkSync as bD,writeFileSync as SD}from"node:fs";import{randomUUID as xD}from"node:crypto";import{homedir as wD}from"node:os";import{basename as kD,dirname as xv,join as Sn}from"node:path";var Is=".materialized",nD=`# Global role
385
+ `)};return{filePath:r,logControl:a,debug:(l,d)=>u("debug",l,d),info:(l,d)=>u("info",l,d),warn:(l,d)=>u("warn",l,d),error:(l,d)=>u("error",l,d),close:()=>new Promise(l=>{n.end(()=>l())})}}function nz(t){let e=-t.getTimezoneOffset(),r=e>=0?"+":"-",n=Math.abs(e);return`${t.getFullYear()}-${hn(t.getMonth()+1)}-${hn(t.getDate())} ${hn(t.getHours())}:${hn(t.getMinutes())}:${hn(t.getSeconds())}.${oz(t.getMilliseconds())} ${r}${hn(Math.floor(n/60))}:${hn(n%60)}`}function hn(t){return String(t).padStart(2,"0")}function oz(t){return String(t).padStart(3,"0")}function sz(){let t=process.env[Ml];return t===void 0?"info":C_.includes(t)?t:Nl(t)}function iz(t=Nl(process.env[Ml])){let e=t,r=new Map,n=i=>{let a=r.get(i);a&&clearTimeout(a.timer),r.delete(i)},o=(i,a=Date.now())=>{let c=r.get(i);c&&c.expiresAt<=a&&n(i)};return{getGlobalLevel:()=>e,setGlobalLevel:i=>{e=i},enableConversationDebug:(i,a)=>{n(i);let c=a-Date.now();if(c<=0)return;let u=setTimeout(()=>{r.delete(i)},c);u.unref?.(),r.set(i,{expiresAt:a,timer:u})},disableConversationDebug:i=>{n(i)},getConversationDebugStatus:i=>{o(i);let a=r.get(i);return a?{enabled:!0,expiresAt:a.expiresAt}:{enabled:!1,expiresAt:null}}}}function az(t,e,r){if(t==="error")return!0;let n=typeof e.conversationId=="string"?e.conversationId:null,o=n&&r.getConversationDebugStatus(n).enabled?"debug":r.getGlobalLevel();return gy[t]>=gy[o]}var gy={debug:10,info:20,warn:30,error:40};function cz(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}function uz(t){try{return JSON.stringify(t,lz)}catch{return JSON.stringify({ts:t.ts,level:t.level,msg:t.msg,_stringify_error:!0})}}function lz(t,e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e}import{statSync as zD}from"node:fs";import{isAbsolute as OD}from"node:path";import{chmodSync as fD,mkdirSync as hD,readFileSync as gD,renameSync as _D,statSync as yD,unlinkSync as vD,writeFileSync as bD}from"node:fs";import{randomUUID as SD}from"node:crypto";import{dirname as xD,join as a5}from"node:path";var AO=At(pv(),1),IO=At(fc(),1),$O=At(po(),1),zO=At(Ad(),1),OO=At(zd(),1),DO=At(Ld(),1),Ke=At(yc(),1),MO=At(bv(),1);var Hd=s.string().min(1),qd=2,NO=s.object({host_id:s.string().min(1),host_token:s.string().min(1),issued_at:s.number().int().nonnegative(),grace_until:s.number().int().positive()}).strict().superRefine((t,e)=>{t.grace_until<=t.issued_at&&e.addIssue({code:"custom",path:["grace_until"],message:"grace_until must be after issued_at"})}),jO=s.discriminatedUnion("rotated",[s.object({rotated:s.literal(!0),host_id:s.string().min(1),config_refreshed_at:s.number().int().nonnegative()}).strict(),s.object({rotated:s.literal(!1),reason:s.enum(["host_mismatch","invalid_config","write_failed"]),message:s.string().optional()}).strict()]),LO=s.object({code:s.union([ge.shape.code,Oa]),message:s.string()}).strict(),FO=s.object({code:s.union([ge.shape.code,ja]),message:s.string()}).strict(),HO=s.object({code:s.union([ge.shape.code,Ha]),message:s.string()}).strict(),Sv=s.object({code:s.union([ge.shape.code,dd]),message:s.string()}).strict(),UO=s.object({code:s.union([ge.shape.code,Wa]),message:s.string()}).strict(),qO=s.object({code:s.union([ge.shape.code,Va]),message:s.string()}).strict(),xv=s.object({code:s.union([ge.shape.code,Xa]),message:s.string()}).strict(),WO=s.object({code:s.union([ge.shape.code,md]),message:s.string()}).strict(),ZO=s.object({code:s.union([ge.shape.code,Da]),message:s.string()}).strict(),bc={runtime_start:{params:Wl,result:Zl,error:ZO},runtime_stop:{params:Bl,result:Vl,error:ge},runtime_wake:{params:Kl,result:Gl,error:ge},runtime_status:{params:Jl,result:Yl,error:ge},runtime_clear_session:{params:Xl,result:Ql,error:ge},runtime_stop_all:{params:ed,result:td,error:ge},runtime_close_activity_log:{params:rd,result:nd,error:ge},runtime_output_pause:{params:Ca,result:od,error:ge},runtime_output_resume:{params:sd,result:id,error:ge},rotate_token:{params:NO,result:jO,error:ge},agent_materialize:{params:$a,result:za,error:LO},workspace_provision:{params:Ma,result:Na,error:FO},agent_workspace_index:{params:La,result:Fa,error:HO},agent_workspace_tree:{params:ad,result:cd,error:Sv},agent_workspace_file_read:{params:ud,result:ld,error:Sv},agent_l2_seed:{params:Ua,result:qa,error:UO},agent_files_purge:{params:Za,result:Ba,error:qO},agent_profile_mcp_read:{params:Ka,result:Ga,error:xv},agent_profile_mcp_write:{params:Ja,result:Ya,error:xv},mcp_probe:{params:pd,result:Ra,error:WO},host_status:{params:Hl,result:Ul,error:ge},host_runtime_catalog:{params:Pa,result:Ea,error:ge},host_proxy_config_get:{params:Ta,result:bs,error:ge},host_proxy_config_set:{params:Aa,result:Ia,error:ge}},wv=Object.keys(bc),BO=wv.map(t=>s.object({direction:s.literal("server_to_daemon"),type:s.literal("command"),id:Hd,kind:s.literal(t),params:bc[t].params}).strict()),Cs=s.discriminatedUnion("kind",BO),VO=wv.flatMap(t=>[s.object({direction:s.literal("daemon_to_server"),type:s.literal("command_response"),id:Hd,kind:s.literal(t),result:bc[t].result}).strict(),s.object({direction:s.literal("daemon_to_server"),type:s.literal("command_response"),id:Hd,kind:s.literal(t),error:bc[t].error}).strict()]),Wd=s.union(VO),Ud=s.number().int().nonnegative(),KO=s.object({direction:s.enum(["server_to_daemon","daemon_to_server"]),type:s.literal("heartbeat"),kind:s.literal("ping"),ts:Ud}).strict(),GO=s.object({direction:s.enum(["server_to_daemon","daemon_to_server"]),type:s.literal("heartbeat"),kind:s.literal("pong"),ts:Ud,echo_ts:Ud}).strict(),Ts=s.discriminatedUnion("kind",[KO,GO]),JO=co.extend({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("ready"),protocol_version:s.literal(qd),daemon_pid:s.number().int(),started_at:s.number().int()}).strict(),YO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("shutting_down"),reason:s.string()}).strict(),XO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_state"),conversation_id:s.string().min(1),agent_id:s.string().min(1),state:oo,ts:s.number().int()}).strict(),QO=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output"),conversation_id:s.string().min(1),agent_id:s.string().min(1),stream:s.enum(["stdout","stderr"]),chunk:s.string(),ts:s.number().int()}).strict(),eD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_exit"),conversation_id:s.string().min(1),agent_id:s.string().min(1),code:s.number().int().nullable(),intentional:s.boolean(),ts:s.number().int()}).strict(),tD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_ready_for_drain"),conversation_id:s.string().min(1),agent_id:s.string().min(1),ts:s.number().int()}).strict(),rD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_startup_delivery_consumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),ts:s.number().int()}).strict(),nD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_startup_delivery_failed"),conversation_id:s.string().min(1),agent_id:s.string().min(1),delivery_ids:s.array(s.number().int()).min(1),reason:s.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:s.number().int()}).strict(),oD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_timeout"),conversation_id:s.string().min(1),agent_id:s.string().min(1),timeout_reason:s.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:s.number().int().nonnegative(),timeout_ms:s.number().int().nonnegative(),retrying:s.boolean(),retry_attempt:s.number().int().nonnegative(),max_retries:s.number().int().nonnegative(),cooldown_until:s.number().int().positive().optional(),ts:s.number().int()}).strict(),sD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_retrying"),conversation_id:s.string().min(1),agent_id:s.string().min(1),retry_attempt:s.number().int().positive(),max_retries:s.number().int().nonnegative(),delay_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),iD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_init_cooldown"),conversation_id:s.string().min(1),agent_id:s.string().min(1),cooldown_until:s.number().int().positive(),attempts_exhausted:s.number().int().nonnegative(),ts:s.number().int()}).strict(),aD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_compaction_stale"),conversation_id:s.string().min(1),agent_id:s.string().min(1),elapsed_ms:s.number().int().nonnegative(),ts:s.number().int()}).strict(),cD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),dropped_count:s.number().int().nonnegative(),bytes_dropped:s.number().int().nonnegative(),since_ts:s.number().int()}).strict(),uD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_paused"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),lD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_output_resumed"),conversation_id:s.string().min(1),agent_id:s.string().min(1)}).strict(),dD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_parsed_event"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed:io,ts:s.number().int()}).strict(),pD=s.object({direction:s.literal("daemon_to_server"),type:s.literal("event"),kind:s.literal("runtime_parsed_event_dropped"),conversation_id:s.string().min(1),agent_id:s.string().min(1),parsed_kind:xa,encoded_bytes:s.number().int().nonnegative(),reason:s.literal("frame_too_large"),ts:s.number().int()}).strict(),kv=s.discriminatedUnion("kind",[JO,YO,XO,QO,eD,tD,rD,nD,oD,sD,iD,aD,cD,uD,lD,dD,pD]),K3=kv.options.map(t=>t.shape.kind.value),Sc=s.union([Cs,Wd,Ts,kv]);function Sn(t){let e=JSON.stringify(t);if(Buffer.byteLength(e,"utf8")>lr)throw new Error(`encoded outbound frame exceeds MAX_FRAME_BYTES=${lr}`);return e}function xc(t,e){let r="error"in e?{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,error:e.error}:{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,result:e.result},n=Wd.safeParse(r);return n.success?{frame:n.data}:{frame:{direction:"daemon_to_server",type:"command_response",id:t.id,kind:t.kind,error:{code:"internal_error",message:`daemon outbound command response drift for ${t.kind}`}},drift:{summary:mD(e),issues:n.error.errors.map(o=>`${o.path.join(".")}: ${o.message}`)}}}function mD(t){if("error"in t)return{arm:"error",id:t.id,error_code:t.error.code};let e=t.result;return{arm:"result",id:t.id,result_type:Array.isArray(e)?"array":typeof e,result_keys:e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).slice(0,10):void 0}}function As(t){switch(t.event){case"ready":{let{event:e,socket_path:r,protocol_version:n,...o}=t;return{direction:"daemon_to_server",type:"event",kind:"ready",protocol_version:qd,...o}}case"shutting_down":{let{event:e,...r}=t;return{direction:"daemon_to_server",type:"event",kind:t.event,...r}}default:{let{event:e,...r}=t;return{direction:"daemon_to_server",type:"event",kind:t.event,...r}}}}var wc={maxFrames:1024,maxBytes:4*1024*1024};function Rv(t){return{bufferedAmount:()=>t.bufferedAmount,send:(e,r)=>t.send(e,r)}}function Pv(t){return{bufferedAmount:()=>t.writableLength,send:(e,r)=>{t.write(`${e}
386
+ `,r)}}}function Is(t){return{kind:t.event,conversation_id:"conversation_id"in t?t.conversation_id:void 0,agent_id:"agent_id"in t?t.agent_id:void 0,ts:"ts"in t&&typeof t.ts=="number"?t.ts:void 0}}var yo=class{constructor(e,r="outbound_ws"){this.opts=e;this.logKind=r}opts;pendingFrames=0;pendingBytes=0;droppedRuntimeOutput=0;logKind;send(e){let r;try{r=Sn(e.frame)}catch(a){return e.metadata.kind==="runtime_output"?(this.logRuntimeOutputDrop(e,0,a.message),"dropped"):(this.logOverflow(e,0,a.message),"overflow")}let n=Buffer.byteLength(r,"utf8"),o=this.pendingBytes+n+Math.max(0,e.writer.bufferedAmount()),i=this.pendingFrames+1;if(o>this.opts.maxBytes||i>this.opts.maxFrames)return e.metadata.kind==="runtime_output"?(this.logRuntimeOutputDrop(e,n,"buffer_limit"),"dropped"):(this.logOverflow(e,n,"buffer_limit"),"overflow");this.pendingFrames++,this.pendingBytes+=n;try{return e.writer.send(r,a=>{this.pendingFrames=Math.max(0,this.pendingFrames-1),this.pendingBytes=Math.max(0,this.pendingBytes-n),a&&e.logger.warn({kind:this.logKind,action:"event_send_callback_error",err:a.message,event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts},"daemon outbound event send callback failed")}),"sent"}catch(a){return this.pendingFrames=Math.max(0,this.pendingFrames-1),this.pendingBytes=Math.max(0,this.pendingBytes-n),e.logger.warn({kind:this.logKind,action:"event_send_failed",err:a.message,event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts},"daemon outbound event send failed"),"failed"}}reset(){this.pendingFrames=0,this.pendingBytes=0}logRuntimeOutputDrop(e,r,n){this.droppedRuntimeOutput++,e.logger.warn({kind:this.logKind,action:"runtime_output_dropped",event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts,encoded_bytes:r,pending_frames:this.pendingFrames,pending_bytes:this.pendingBytes,dropped_count:this.droppedRuntimeOutput,reason:n},"daemon outbound runtime_output dropped under write-buffer pressure")}logOverflow(e,r,n){e.logger.warn({kind:this.logKind,action:"non_droppable_overflow",event_kind:e.metadata.kind,conversation_id:e.metadata.conversation_id,agent_id:e.metadata.agent_id,ts:e.metadata.ts,encoded_bytes:r,pending_frames:this.pendingFrames,pending_bytes:this.pendingBytes,reason:n},"daemon outbound non-droppable event exceeded write-buffer cap")}};var wD=1e3,kD={minDelayMs:1e3,maxDelayMs:6e4,factor:2,jitterRatio:.25},RD={pingIntervalMs:3e4,pongTimeoutMs:5e3},vo=class{constructor(e){this.opts=e;this.configPollMs=e.configPollMs??wD,this.backoff={...kD,...e.backoff??{}},this.heartbeat={...RD,...e.heartbeat??{}},this.random=e.random??Math.random,this.now=e.now??Date.now,this.writeHostConfig=e.writeHostConfig??ED,this.writeBuffer=new yo({...wc,...e.buffer??{}})}opts;configPollMs;backoff;heartbeat;random;now;writeHostConfig;writeBuffer;configTimer=null;reconnectTimer=null;pingTimer=null;pongTimer=null;ws=null;desiredConfig=null;terminalCloseConfigKey=null;reconnectAttempt=0;started=!1;stopping=!1;start(){this.started||(this.started=!0,this.stopping=!1,this.pollConfig(),!this.opts.config&&this.configPollMs>0&&(this.configTimer=setInterval(()=>this.pollConfig(),this.configPollMs),this.configTimer.unref?.()))}stop(e="daemon_shutdown"){this.stopping=!0,this.clearConfigTimer(),this.clearReconnectTimer(),this.clearHeartbeatTimers();let r=this.ws;this.ws=null,r&&(r.readyState===Ke.default.OPEN||r.readyState===Ke.default.CONNECTING)&&r.close(1e3,e)}sendEvent(e){let r=As(e),n=Is(e),o=this.ws;if(!o||o.readyState!==Ke.default.OPEN)return this.handleUnavailableSend(n),n.kind==="runtime_output"?"dropped":"failed";let i=this.writeBuffer.send({writer:Rv(o),frame:r,metadata:n,logger:this.opts.logger});return i==="overflow"&&(this.opts.logger.warn({kind:"outbound_ws",action:"buffer_overflow_close",event_kind:n.kind,conversation_id:n.conversation_id,agent_id:n.agent_id,ts:n.ts,pending_frames:this.writeBuffer.pendingFrames,pending_bytes:this.writeBuffer.pendingBytes},"daemon outbound ws buffer overflow on non-droppable event; closing connection"),o.close(1013,"outbound_buffer_overflow")),i}state(){return{connected:this.ws?.readyState===Ke.default.OPEN,desiredConfigLoaded:this.desiredConfig!==null,reconnectAttempt:this.reconnectAttempt,pendingFrames:this.writeBuffer.pendingFrames,pendingBytes:this.writeBuffer.pendingBytes}}pollConfig(){if(this.stopping)return;let e=this.readConfig();if(!e.ok){(this.desiredConfig!==null||this.ws!==null)&&this.opts.logger.warn({kind:"outbound_ws",action:"config_unavailable",config_path:this.configLabel(),reason:e.reason},"daemon outbound config unavailable; disconnecting"),this.desiredConfig=null,this.closeForConfigChange("config_unavailable");return}let r;try{r=bo(e.config.server_url,{allowInsecureRemote:e.config.allow_insecure_remote===!0})}catch(o){this.opts.logger.warn({kind:"outbound_ws",action:"config_invalid",config_path:this.configLabel(),reason:o.message},"daemon outbound config rejected"),this.desiredConfig=null,this.closeForConfigChange("config_invalid");return}let n=Ev(e.config);if(this.desiredConfig?.key===n){if(this.terminalCloseConfigKey===n)return;(!this.ws||this.ws.readyState===Ke.default.CLOSED)&&this.scheduleReconnect("config_poll");return}this.desiredConfig={raw:e.config,key:n,wsUrl:r},this.terminalCloseConfigKey=null,this.reconnectAttempt=0,this.opts.logger.info({kind:"outbound_ws",action:"config_loaded",host_id:e.config.host_id,server_origin:new URL(e.config.server_url).origin},"daemon outbound config loaded"),this.closeForConfigChange("config_changed"),this.connectNow()}connectNow(){if(this.stopping)return;let e=this.desiredConfig;if(!e||this.ws&&(this.ws.readyState===Ke.default.OPEN||this.ws.readyState===Ke.default.CONNECTING))return;this.clearReconnectTimer();let r=new Ke.default(e.wsUrl,{headers:{Authorization:`Bearer ${e.raw.host_token}`}});this.ws=r,this.opts.logger.info({kind:"outbound_ws",action:"connect_attempt",host_id:e.raw.host_id,server_origin:new URL(e.raw.server_url).origin},"daemon outbound ws connecting"),r.on("open",()=>{this.reconnectAttempt=0,this.writeBuffer.reset(),this.opts.logger.info({kind:"outbound_ws",action:"connected",host_id:e.raw.host_id},"daemon outbound ws connected"),this.sendEvent(this.opts.readyEvent()),this.startHeartbeat()}),r.on("message",n=>this.handleMessage(n)),r.on("error",n=>{this.opts.logger.warn({kind:"outbound_ws",action:"socket_error",err:n.message,host_id:e.raw.host_id},"daemon outbound ws error")}),r.on("close",(n,o)=>{this.clearHeartbeatTimers(),this.writeBuffer.reset();let i=o.toString(),a=this.ws===r;if(a&&(this.ws=null),this.opts.logger.warn({kind:"outbound_ws",action:"closed",code:n,reason:i,close_class:Cv(n),host_id:e.raw.host_id},"daemon outbound ws closed"),!this.stopping&&a){if(ID(i)){this.terminalCloseConfigKey=e.key,this.clearReconnectTimer(),this.opts.logger.info({kind:"outbound_ws",action:"reconnect_suppressed",reason:i,host_id:e.raw.host_id},"daemon outbound ws reconnect suppressed after terminal close");return}this.scheduleReconnect(`close_${Cv(n)}`)}})}handleMessage(e){let r=TD(e);if(!r){this.closeProtocolError("invalid_json");return}let n=Ts.safeParse(r);if(n.success){this.handleHeartbeat(n.data);return}let o=Cs.safeParse(r);if(o.success){this.handleCommand(o.data);return}if(!Sc.safeParse(r).success){this.closeProtocolError("invalid_frame");return}this.closeProtocolError("wrong_direction")}async handleCommand(e){let r=this.opts.dispatchCommand??PD,n=this.now(),o=e.kind==="host_status"?"debug":"info";this.opts.logger[o]({kind:"outbound_ws",action:"command_received",command_kind:e.kind,request_id:e.id},"daemon outbound command received");let i;try{if(e.kind==="rotate_token")i={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,result:this.handleRotateToken(e.params)};else{let u=await r(e),l=xc(e,u);i=l.frame,l.drift&&this.opts.logger.warn({kind:"outbound_ws",action:"command_response_shape_drift",command_kind:e.kind,request_id:e.id,response_summary:l.drift.summary,issues:l.drift.issues},"daemon outbound command response shape drift; returning internal_error")}}catch(u){i={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,error:{code:"internal_error",message:u instanceof Error?u.message:String(u)}}}let a;try{a=Sn(i)}catch(u){this.opts.logger.warn({kind:"outbound_ws",action:"command_response_encode_failed",command_kind:e.kind,request_id:e.id,err:u.message},"daemon outbound command response encode failed; closing connection"),this.ws?.close(1011,"command_response_encode_failed");return}let c=this.ws;if(!c||c.readyState!==Ke.default.OPEN){this.opts.logger.warn({kind:"outbound_ws",action:"command_response_disconnected",command_kind:e.kind,request_id:e.id},"daemon outbound command response dropped because socket is disconnected");return}c.send(a,u=>{this.opts.logger[u?"warn":o]({kind:"outbound_ws",action:u?"command_response_send_failed":"command_response_sent",command_kind:e.kind,request_id:e.id,duration_ms:this.now()-n,err:u?.message},u?"daemon outbound command response send failed":"daemon outbound command response sent")})}handleRotateToken(e){let r=this.desiredConfig;if(!r||r.raw.host_id!==e.host_id)return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_host_mismatch",expected_host_id:r?.raw.host_id,command_host_id:e.host_id},"daemon outbound rotate_token rejected: host mismatch"),{rotated:!1,reason:"host_mismatch"};let n=wa.safeParse({...r.raw,host_token:e.host_token});if(!n.success)return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_invalid_config",issues:n.error.errors.map(i=>`${i.path.join(".")}: ${i.message}`)},"daemon outbound rotate_token rejected: generated config invalid"),{rotated:!1,reason:"invalid_config"};try{if(!this.opts.configPath)throw new Error("static connect command config cannot be rewritten");this.writeHostConfig(this.opts.configPath,n.data)}catch(i){return this.opts.logger.warn({kind:"outbound_ws",action:"rotate_token_write_failed",err:i.message},"daemon outbound rotate_token failed to refresh config"),{rotated:!1,reason:"write_failed",message:i.message}}let o={raw:n.data,key:Ev(n.data),wsUrl:r.wsUrl};return this.desiredConfig=o,this.opts.logger.info({kind:"outbound_ws",action:"rotate_token_refreshed",host_id:n.data.host_id,grace_until:e.grace_until},"daemon outbound host token refreshed in config and memory"),{rotated:!0,host_id:n.data.host_id,config_refreshed_at:this.now()}}readConfig(){return this.opts.config?{ok:!0,config:this.opts.config}:this.opts.configPath?kc(this.opts.configPath):{ok:!1,reason:"missing"}}configLabel(){return this.opts.configPath?$D(this.opts.configPath):"<memory>"}handleHeartbeat(e){if(e.direction!=="server_to_daemon"){this.closeProtocolError("wrong_direction_heartbeat");return}if(e.kind==="ping"){this.sendControlFrame({direction:"daemon_to_server",type:"heartbeat",kind:"pong",ts:this.now(),echo_ts:e.ts});return}this.clearPongTimer()}startHeartbeat(){this.clearHeartbeatTimers(),!(this.heartbeat.pingIntervalMs<=0)&&(this.pingTimer=setInterval(()=>{if(!this.ws||this.ws.readyState!==Ke.default.OPEN)return;let e=this.now();this.sendControlFrame({direction:"daemon_to_server",type:"heartbeat",kind:"ping",ts:e})&&(this.clearPongTimer(),this.pongTimer=setTimeout(()=>{this.opts.logger.warn({kind:"outbound_ws",action:"heartbeat_timeout",timeout_ms:this.heartbeat.pongTimeoutMs},"daemon outbound heartbeat timeout; closing connection"),this.ws?.close(1008,"heartbeat_timeout")},this.heartbeat.pongTimeoutMs),this.pongTimer.unref?.())},this.heartbeat.pingIntervalMs),this.pingTimer.unref?.())}sendControlFrame(e){let r=this.ws;if(!r||r.readyState!==Ke.default.OPEN)return!1;try{return r.send(Sn(e)),!0}catch(n){return this.opts.logger.warn({kind:"outbound_ws",action:"control_send_failed",err:n.message},"daemon outbound control frame send failed; closing connection"),r.close(1011,"control_send_failed"),!1}}scheduleReconnect(e){if(this.stopping||!this.desiredConfig||this.reconnectTimer)return;let r=CD(this.reconnectAttempt++,this.backoff,this.random);this.opts.logger.info({kind:"outbound_ws",action:"reconnect_scheduled",reason:e,delay_ms:r,attempt:this.reconnectAttempt},"daemon outbound ws reconnect scheduled"),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectNow()},r),this.reconnectTimer.unref?.()}closeProtocolError(e){this.ws?.close(1002,e)}closeForConfigChange(e){this.clearReconnectTimer(),this.clearHeartbeatTimers();let r=this.ws;this.ws=null,r&&(r.readyState===Ke.default.OPEN||r.readyState===Ke.default.CONNECTING)&&r.close(1e3,e)}handleUnavailableSend(e){let r=e.kind==="runtime_output"?"debug":"warn";this.opts.logger[r]({kind:"outbound_ws",action:e.kind==="runtime_output"?"drop_disconnected":"event_disconnected",event_kind:e.kind,conversation_id:e.conversation_id,agent_id:e.agent_id,ts:e.ts},"daemon outbound event emitted while disconnected")}clearConfigTimer(){this.configTimer&&(clearInterval(this.configTimer),this.configTimer=null)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}clearHeartbeatTimers(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),this.clearPongTimer()}clearPongTimer(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}};async function PD(t){return{id:t.id,error:{code:"internal_error",message:"daemon outbound command dispatcher is not wired"}}}function kc(t){let e;try{e=yD(t)}catch(i){return i.code==="ENOENT"?{ok:!1,reason:"missing"}:{ok:!1,reason:"io_error"}}if(!e.isFile())return{ok:!1,reason:"not_a_file"};let r;try{r=gD(t,"utf8")}catch{return{ok:!1,reason:"io_error"}}let n;try{n=JSON.parse(r)}catch{return{ok:!1,reason:"invalid_json"}}let o=wa.safeParse(n);return o.success?{ok:!0,config:o.data}:{ok:!1,reason:"invalid_shape"}}function ED(t,e){let r=wa.parse(e);hD(xD(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${SD()}`;try{bD(n,`${JSON.stringify(r,null,2)}
387
+ `,{mode:384}),_D(n,t),fD(t,384)}catch(o){try{vD(n)}catch{}throw o}}function Rc(t){let e=t.profile_version===void 0?"<none>":String(t.profile_version),r=t.allow_insecure_remote===!0?"1":"0";return`${t.server_url}\0${t.host_id}\0${t.host_token}\0allow_insecure_remote=${r}\0pv=${e}`}function bo(t,e){let r=H_(t,{allowInsecureRemote:e?.allowInsecureRemote===!0});if(!r.ok)throw r.reason==="insecure_remote_http_disallowed"?new Error("tls_required_for_non_loopback_host_ws"):r.reason==="obfuscated_loopback_disallowed"?new Error("tls_required_for_non_loopback_host_ws"):r.reason==="unsupported_scheme"?new Error(`unsupported_server_url_protocol:${t}`):new Error(`invalid_server_url:${r.reason}`);let n=new URL(ba.hostConnect,r.url);return n.protocol==="http:"?(n.protocol="ws:",n.toString()):(n.protocol="wss:",n.toString())}function CD(t,e,r){let n=e.minDelayMs*Math.pow(e.factor,t),o=Math.min(e.maxDelayMs,n);if(e.jitterRatio<=0)return Math.round(o);let i=o*e.jitterRatio,a=o-i+r()*i*2;return Math.max(0,Math.round(Math.min(e.maxDelayMs,a)))}function Ev(t){return Rc(t)}function TD(t){try{let e=JSON.parse(AD(t));return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}catch{return null}}function AD(t){return typeof t=="string"?t:Array.isArray(t)?Buffer.concat(t).toString("utf8"):t instanceof ArrayBuffer?Buffer.from(t).toString("utf8"):t.toString("utf8")}function Cv(t){return t===1e3?"normal":t===1001?"going_away":t===1006?"abnormal":"other"}function ID(t){return t===Fg||t===Hg}function $D(t){return t.endsWith(`/${Dl}`)?`.../${Dl}`:".../daemon-config"}function Zd(t){return{server_origin:new URL(t.server_url).origin,host_id:t.host_id}}var Cc=class{constructor(e){this.deps=e}deps;current=null;stopped=!1;attach(e){if(this.stopped)return So("parse_failed","supervisor stopped");let{config_path:r}=e;if(!OD(r))return So("path_not_absolute",`config_path must be absolute: ${r}`);if(this.current&&this.current.configPath===r)return Bd(r,"noop");let n;try{n=zD(r)}catch(c){return So("path_not_found",c.message)}if(!n.isFile())return So("path_not_a_file",`config_path is not a regular file: ${r}`);let o=kc(r);if(!o.ok)return So("parse_failed",o.reason);try{bo(o.config.server_url,{allowInsecureRemote:o.config.allow_insecure_remote===!0})}catch(c){return So("invalid_server_url",c.message)}let i=Rc(o.config);if(this.current){this.current.client.stop("config_path_changed"),this.current=null;let c=this.spawnClient(r);return this.current={configPath:r,fingerprint:i,binding:Zd(o.config),client:c},c.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"switched",config_path:Ec(r)},"daemon outbound switched to new config path"),Bd(r,"switched")}let a=this.spawnClient(r);return this.current={configPath:r,fingerprint:i,binding:Zd(o.config),client:a},a.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"started",config_path:Ec(r)},"daemon outbound started from host config"),Bd(r,"started")}reload(){if(this.stopped)return Pc("not_attached","supervisor stopped");let e=this.current;if(!e)return Pc("not_attached","no current outbound client; use host_outbound_attach to bootstrap");let r=kc(e.configPath);if(!r.ok){let i=r.reason==="missing"||r.reason==="not_a_file"||r.reason==="io_error"?"config_unreadable":"parse_failed";return Pc(i,r.reason)}try{bo(r.config.server_url,{allowInsecureRemote:r.config.allow_insecure_remote===!0})}catch(i){return Pc("invalid_server_url",i.message)}let n=Rc(r.config);if(n===e.fingerprint)return this.deps.logger.info({kind:"outbound_supervisor",action:"reload_unchanged",config_path:Ec(e.configPath),host_id:r.config.host_id},"daemon outbound reload no-op (config bytes unchanged)"),{reloaded:!0,action:"unchanged",config_path:e.configPath,host_id:r.config.host_id};e.client.stop("config_reload"),this.current=null;let o=this.spawnClient(e.configPath);return this.current={configPath:e.configPath,fingerprint:n,binding:Zd(r.config),client:o},o.start(),this.deps.logger.info({kind:"outbound_supervisor",action:"reload_swapped",config_path:Ec(e.configPath),host_id:r.config.host_id},"daemon outbound reloaded with fresh config bytes"),{reloaded:!0,action:"reloaded",config_path:e.configPath,host_id:r.config.host_id}}sendEvent(e){this.current?.client.sendEvent(e)}currentBinding(){return this.current?{...this.current.binding}:null}detach(){return this.current?(this.current.client.stop("host_outbound_detach"),this.current=null,this.deps.logger.info({kind:"outbound_supervisor",action:"detached"},"daemon outbound detached on host_outbound_detach hint"),{detached:!0,action:"detached"}):{detached:!0,action:"noop"}}stop(e="daemon_shutdown"){this.stopped||(this.stopped=!0,this.current&&(this.current.client.stop(e),this.current=null))}currentConfigPath(){return this.current?.configPath??null}spawnClient(e){let r=this.deps.outboundClientFactory;return r?r(e,{logger:this.deps.logger,readyEvent:this.deps.readyEvent,dispatchCommand:this.deps.dispatchCommand}):new vo({configPath:e,logger:this.deps.logger,readyEvent:this.deps.readyEvent,dispatchCommand:this.deps.dispatchCommand})}};function Bd(t,e){return{attached:!0,config_path:t,action:e}}function So(t,e){return{attached:!1,reason:t,message:e}}function Pc(t,e){return{reloaded:!1,reason:t,message:e}}function Ec(t){let e=t.lastIndexOf("/");return e<0?t:`\u2026/${t.slice(e+1)}`}import{Server as DD}from"node:net";import{chmodSync as MD,existsSync as Tv,unlinkSync as Av}from"node:fs";var Tc=class{socketPath;dispatchCommand;logger;readyEvent;server;liveSockets=new Set;writeBuffers=new WeakMap;writeBufferOptions;constructor(e){this.socketPath=e.socketPath,this.dispatchCommand=e.dispatchCommand,this.logger=e.logger,this.readyEvent=e.readyEvent,this.writeBufferOptions={...wc,...e.writeBuffer??{}},this.server=new DD(r=>this.handleConnection(r))}async start(){if(Tv(this.socketPath))try{Av(this.socketPath)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"local outbound: failed to remove stale socket file; listen may fail")}await new Promise((e,r)=>{let n=i=>{this.server.off("listening",o),r(i)},o=()=>{this.server.off("error",n),e()};this.server.once("error",n),this.server.once("listening",o),this.server.listen(this.socketPath)});try{MD(this.socketPath,384)}catch(e){this.logger.warn({socketPath:this.socketPath,err:e.message},"local outbound: failed to chmod socket; peers may have wider access than intended")}this.logger.info({socketPath:this.socketPath},"local outbound frame socket listening")}async stop(){if(await new Promise(e=>{this.server.close(()=>e());for(let r of this.liveSockets)r.end()}),Tv(this.socketPath))try{Av(this.socketPath)}catch{}this.logger.info({socketPath:this.socketPath},"local outbound frame socket closed")}liveConnectionCount(){return this.liveSockets.size}broadcast(e){if(this.liveSockets.size===0)return;let r=As(e),n=Is(e);for(let o of this.liveSockets)o.destroyed||this.sendEventToSocket(o,r,n)}sendEventToSocket(e,r,n){let o=this.writeBuffers.get(e);if(!o)return;o.send({writer:Pv(e),frame:r,metadata:n,logger:this.logger})==="overflow"&&(this.logger.warn({kind:"local_outbound",action:"buffer_overflow_close",event_kind:n.kind,conversation_id:n.conversation_id,agent_id:n.agent_id,ts:n.ts,pending_frames:o.pendingFrames,pending_bytes:o.pendingBytes},"local outbound buffer overflow on non-droppable event; closing connection"),e.destroy())}handleConnection(e){if(this.liveSockets.add(e),this.writeBuffers.set(e,new yo(this.writeBufferOptions,"local_outbound")),this.readyEvent){let n=this.readyEvent();this.sendEventToSocket(e,As(n),Is(n))}let r="";e.setEncoding("utf8"),e.on("data",n=>{let o=typeof n=="string"?n:n.toString("utf8"),{frames:i,leftover:a,overflow:c}=Qa(r,o);if(r=a,c){this.logger.warn({socketPath:this.socketPath},`local outbound: inbound frame exceeded MAX_FRAME_BYTES=${lr}; closing`),e.destroy();return}for(let u of i)if(!this.handleLine(e,u)||e.destroyed)break}),e.on("error",n=>{this.logger.warn({err:n.message,code:n.code},"local outbound: connection error")}),e.on("close",()=>{this.liveSockets.delete(e),this.writeBuffers.delete(e)})}handleLine(e,r){let n;try{n=JSON.parse(r)}catch(a){return this.logger.warn({kind:"local_outbound",action:"frame_parse_failed",line_bytes:Buffer.byteLength(r,"utf8"),parse_error:a.message},"local outbound: failed to parse frame as JSON; closing connection"),e.destroy(),!1}let o=Cs.safeParse(n);if(o.success)return this.handleCommand(e,o.data),!0;if(Ts.safeParse(n).success)return!0;let i=Sc.safeParse(n);return this.logger.warn({kind:"local_outbound",action:"frame_invalid",err:i.success?"wrong_direction_or_type":"schema_mismatch",issue_count:o.error.errors.length,issue_paths:o.error.errors.map(a=>a.path.join("."))},"local outbound: invalid inbound frame; closing connection"),e.destroy(),!1}async handleCommand(e,r){let n=r.kind==="host_status"?"debug":"info";this.logger[n]({kind:"local_outbound",action:"command_received",command_kind:r.kind,request_id:r.id},"local outbound command received");let o;try{let a=await this.dispatchCommand(r),c=xc(r,a);o=c.frame,c.drift&&this.logger.warn({kind:"local_outbound",action:"command_response_shape_drift",command_kind:r.kind,request_id:r.id,response_summary:c.drift.summary,issues:c.drift.issues},"local outbound command response shape drift; returning internal_error")}catch(a){o={direction:"daemon_to_server",type:"command_response",id:r.id,kind:r.kind,error:{code:"internal_error",message:a instanceof Error?a.message:String(a)}}}let i;try{i=`${Sn(o)}
388
+ `}catch(a){this.logger.warn({kind:"local_outbound",action:"command_response_encode_failed",command_kind:r.kind,request_id:r.id,err:a.message},"local outbound command response encode failed; closing connection"),e.destroy();return}if(e.destroyed){this.logger.warn({kind:"local_outbound",action:"command_response_disconnected",command_kind:r.kind,request_id:r.id},"local outbound command response dropped because socket is disconnected");return}e.write(i)}};import{linkSync as QD,mkdirSync as Qd,readdirSync as Dv,unlinkSync as eM,writeFileSync as tM}from"node:fs";import{randomUUID as rM}from"node:crypto";import{homedir as nM}from"node:os";import{basename as oM,dirname as Ov,join as xn}from"node:path";var $s=".materialized",ND=`# Global role
387
389
 
388
390
  _To be shaped via DM._
389
- `,oD=`# Silverhand Onboarding Guide
391
+ `,jD=`# Silverhand Onboarding Guide
390
392
 
391
393
  ## What Silverhand Is
392
394
  Silverhand is a desktop app where humans and AI agents collaborate in shared
@@ -465,7 +467,7 @@ Do not leave the user with a list of options to decide between.
465
467
  the nearest useful alternative \u2014 do not dwell on limitations.
466
468
  - Channel silence is not failure. If the user is active elsewhere, follow
467
469
  the work there.
468
- `,sD=`# Silverhand Onboarding FAQ
470
+ `,LD=`# Silverhand Onboarding FAQ
469
471
 
470
472
  Reference answers to common user questions.
471
473
  Understand the core idea and guardrail for each item, then answer in your own
@@ -532,7 +534,7 @@ words based on the user's context. Do not copy these answers verbatim.
532
534
  - Ask for 2\u20133 recurring work types and map each to an agent.
533
535
  ### Guardrail
534
536
  - Start simple. Unspecialized start is valid; avoid over-scaling early.
535
- `,iD=`# User Preferences
537
+ `,FD=`# User Preferences
536
538
 
537
539
  Record durable preferences that should shape future work.
538
540
 
@@ -542,7 +544,7 @@ Examples:
542
544
  - Product and design preferences that apply across tasks.
543
545
 
544
546
  Keep this file concise. Prefer editing existing bullets over appending duplicates.
545
- `,aD=`# Project Notes
547
+ `,HD=`# Project Notes
546
548
 
547
549
  Record durable project context and architecture facts.
548
550
 
@@ -552,7 +554,7 @@ Examples:
552
554
  - Invariants or guardrails that future work must preserve.
553
555
 
554
556
  Keep transient task status in work-log.md instead.
555
- `,cD=`# Work Log
557
+ `,UD=`# Work Log
556
558
 
557
559
  Record significant completed work, decisions, and follow-ups.
558
560
 
@@ -562,14 +564,14 @@ Use this for detail that would make MEMORY.md too large:
562
564
  - Follow-up risks that are not active blockers.
563
565
 
564
566
  Keep entries compact and merge related updates when a task iterates.
565
- `,uD=["# Memory","","Role source: system_prompt.md (already loaded by runtime; do not duplicate the role contract here).","","## Key Knowledge","- Read [notes/onboarding-guide.md](notes/onboarding-guide.md) for Silverhand workspace patterns and onboarding guidance","- Read [notes/onboarding-faq.md](notes/onboarding-faq.md) for common user questions and reference answers","- Read [notes/user-preferences.md](notes/user-preferences.md) for durable user preferences","- Read [notes/project.md](notes/project.md) for durable project context and invariants","- Read [notes/work-log.md](notes/work-log.md) for significant work history and follow-ups","","## Active Context","_Keep only the current handoff here. Detailed history belongs in notes/work-log.md._",""].join(`
566
- `),lD={name:"default",dirs:["notes"],files:[{relPath:"system_prompt.md",content:nD},{relPath:"MEMORY.md",content:uD},{relPath:"notes/onboarding-guide.md",content:oD},{relPath:"notes/onboarding-faq.md",content:sD},{relPath:"notes/user-preferences.md",content:iD},{relPath:"notes/project.md",content:aD},{relPath:"notes/work-log.md",content:cD}]};function Pc(t){switch(t){case"default":return lD;case"onboarding":case"minimal":return null;default:return null}}function Hd(t){let e=Pc(t);return e==null?null:{...e,files:e.files.filter(r=>r.relPath!=="system_prompt.md")}}import{linkSync as dD,mkdirSync as pD,readFileSync as mD,unlinkSync as fD,writeFileSync as hD}from"node:fs";import{randomUUID as gD}from"node:crypto";import{basename as _D,dirname as vv,join as bv}from"node:path";var Sv=s.object({version:s.number().int().positive(),agent_id:s.string().min(1),template_choice:s.string().min(1),runtime:s.string().min(1),materialized_at:s.number().int().positive()}).strict();function Ud(t){return bv(t,Is)}function qd(t){let e;try{e=mD(Ud(t),"utf8")}catch(o){if(yD(o)&&o.code==="ENOENT")return{kind:"missing"};throw o}let r;try{r=JSON.parse(e)}catch(o){return{kind:"invalid",reason:`sentinel is not valid JSON: ${o instanceof Error?o.message:String(o)}`}}let n=Sv.safeParse(r);return n.success?n.data.version!==1?{kind:"invalid",reason:`sentinel version ${n.data.version} is not supported (handler expects ${1})`}:{kind:"ok",sentinel:n.data}:{kind:"invalid",reason:`sentinel does not match schema: ${n.error.errors.map(o=>`${o.path.join(".")}: ${o.message}`).join("; ")}`}}function Wd(t,e){return t.agent_id!==e.agent_id?{kind:"mismatch",reason:`sentinel.agent_id=${t.agent_id} but request.agent_id=${e.agent_id}`}:t.template_choice!==e.template_choice?{kind:"mismatch",reason:`sentinel.template_choice=${t.template_choice} but request.template_choice=${e.template_choice}`}:t.runtime!==e.runtime?{kind:"mismatch",reason:`sentinel.runtime=${t.runtime} but request.runtime=${e.runtime}`}:{kind:"match"}}function Zd(t,e){let r=Ud(t);pD(vv(r),{recursive:!0});let n=bv(vv(r),`.${_D(r)}.${process.pid}.${gD()}.tmp`);try{hD(n,`${JSON.stringify(e)}
567
- `,{mode:384}),dD(n,r)}finally{try{fD(n)}catch{}}}function yD(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"}var Ke=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentMaterializeError"}code};function kv(t,e=wD()){return Sn(e,".silverhand","agents",t)}function Rv(t,e){return Sn(e,t)}function Ge(t,e={}){return e.agentHomeRootDir?Rv(t,e.agentHomeRootDir):kv(t,e.homeDir)}async function Kd(t,e={}){let r=e.now??Date.now,n=Ge(t.agent_id,e),o=Pc(t.template_choice);if(!o)throw new Ke("unsupported_template",`daemon does not have a template definition for template_choice='${t.template_choice}'`);let i;try{i=qd(n)}catch(c){throw Bd(c,`failed to read sentinel at ${Sn(n,Is)}`)}if(i.kind==="ok"){let c=Wd(i.sentinel,{agent_id:t.agent_id,template_choice:t.template_choice,runtime:t.runtime});if(c.kind==="match")return{ok:!0,agent_dir:n,agent_home_workspace_path:n,materialized_at:i.sentinel.materialized_at};throw new Ke("agent_dir_collision",`agent_dir already materialized with mismatched metadata; ${c.reason}`)}if(i.kind==="invalid")throw new Ke("agent_dir_collision",`agent_dir has an unrecognized sentinel; ${i.reason}`);let a;try{a=wv(n)}catch(c){if(TD(c,"ENOENT"))a=null;else throw Bd(c,`failed to read ${n}`)}if(a!==null&&a.length>0)throw new Ke("agent_dir_collision",`agent_dir is not empty and has no sentinel; refusing to overwrite (${a.length} foreign entries: ${a.slice(0,5).join(", ")}${a.length>5?", ...":""})`);try{e.afterEmptyDirCheck!==void 0&&await e.afterEmptyDirCheck(n),RD(n,o),PD(n,o);let c=r();return Zd(n,{version:1,agent_id:t.agent_id,template_choice:t.template_choice,runtime:t.runtime,materialized_at:c}),{ok:!0,agent_dir:n,agent_home_workspace_path:n,materialized_at:c}}catch(c){throw c instanceof Ke?c:Bd(c,`failed to seed template under ${n}`)}}function RD(t,e){Vd(t,{recursive:!0});for(let r of e.dirs)Vd(Sn(t,r),{recursive:!0});for(let r of e.files)CD(Sn(t,r.relPath),r.content)}function PD(t,e){let r=new Set;for(let i of e.dirs)r.add(i);for(let i of e.files)r.add(i.relPath);let n=ED(t),o=[];for(let i of n)r.has(i)||o.push(i);if(o.length>0)throw new Ke("agent_dir_collision",`post-seed expected-tree scan found foreign content (${o.length} entries: ${o.slice(0,5).join(", ")}${o.length>5?", ...":""}); refusing to write sentinel`)}function ED(t){let e=[],r=[{absDir:t,relDir:""}];for(;r.length>0;){let{absDir:n,relDir:o}=r.pop(),i=wv(n,{withFileTypes:!0});for(let a of i){let c=o===""?a.name:`${o}/${a.name}`;e.push(c),a.isDirectory()&&r.push({absDir:Sn(n,a.name),relDir:c})}}return e}function CD(t,e){Vd(xv(t),{recursive:!0});let r=Sn(xv(t),`.${kD(t)}.${process.pid}.${xD()}.tmp`);try{SD(r,e,{mode:384}),vD(r,t)}finally{try{bD(r)}catch{}}}function Bd(t,e){if(!Pv(t))return new Ke("internal_error",`${e}: ${t instanceof Error?t.message:String(t)}`);switch(t.code){case"ENOSPC":return new Ke("fs_quota_exceeded",`${e}: ${t.message}`);case"EDQUOT":return new Ke("fs_quota_exceeded",`${e}: ${t.message}`);case"EACCES":case"EPERM":case"EROFS":return new Ke("fs_unavailable",`${e}: ${t.message}`);case"EEXIST":return new Ke("agent_dir_collision",`${e}: ${t.message}`);default:return new Ke("internal_error",`${e}: ${t.message}`)}}function Pv(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"}function TD(t,e){return Pv(t)&&t.code===e}import{createHash as Cv}from"node:crypto";import{mkdirSync as AD,readFileSync as ID,renameSync as $D,statSync as zD,unlinkSync as OD,writeFileSync as DD}from"node:fs";import{homedir as MD}from"node:os";import{isAbsolute as Ev,join as Ec,resolve as So,sep as xo}from"node:path";var ae=class extends Error{constructor(r,n){super(n);this.code=r;this.name="WorkspaceRegistryError"}code},Cc=1,ND="workspace-registry.json",jD="workspaces";function Tv(t){return Cv("sha256").update(`${t.server_origin}\0${t.host_id}`).digest("hex").slice(0,16)}function Av(t){return Cv("sha256").update(t).digest("hex").slice(0,32)}var LD=s.object({server_origin:s.string().min(1),host_id:s.string().min(1)}).strict(),FD=s.object({path:s.string().min(1),provisioned_at:s.number().int().positive()}).strict(),HD=s.object({schema_version:s.literal(Cc),binding:LD,workspaces:s.record(s.string().min(1),FD)}).strict();function UD(t,e){return t.server_origin===e.server_origin&&t.host_id===e.host_id}function qD(t,e){return t===e||t.startsWith(e+xo)||e.startsWith(t+xo)}var zt=class{filePath;managedRoot;binding;silverhandStateRoot;legacyWorkspacesRoot;now;constructor(e){let r=Ec(e.stateDir,Tv(e.binding));this.filePath=Ec(r,ND),this.managedRoot=Ec(r,jD),this.binding=e.binding,this.silverhandStateRoot=e.silverhandStateRoot?So(e.silverhandStateRoot):void 0,this.legacyWorkspacesRoot=e.legacyWorkspacesRoot?So(e.legacyWorkspacesRoot):void 0,this.now=e.now??(()=>Date.now())}registryFilePath(){return this.filePath}currentBinding(){return this.binding}resolve(e){let n=this.loadForRead().workspaces[e];if(!n)throw new ae("not_provisioned",`workspace ${e} is not provisioned in this daemon's registry`);return n.path}has(e){return!!this.loadForRead().workspaces[e]}provision(e,r){let n=this.loadOrInit(),o=n.workspaces[e];if(o){if(r===void 0)return{path:o.path,created:!1};if(Ev(r)&&So(r)===o.path)return{path:o.path,created:!1};let a=this.validateRequestedPath(r);throw new ae("path_conflict",`workspace ${e} is already bound to ${o.path}; refusing to overwrite with ${a}`)}let i;return r===void 0?i=Ec(this.managedRoot,Av(e)):i=this.validateRequestedPath(r),this.assertNoOverlap(n,e,i),n.workspaces[e]={path:i,provisioned_at:this.now()},this.persist(n),{path:i,created:!0}}remove(e,r){let n=this.loadOrInit(),o=n.workspaces[e];return!o||o.path!==r?!1:(delete n.workspaces[e],this.persist(n),!0)}assertNoOverlap(e,r,n){for(let[o,i]of Object.entries(e.workspaces))if(o!==r&&qD(i.path,n))throw new ae("path_conflict",`path ${n} overlaps workspace ${o} bound at ${i.path}; two workspaces cannot share or nest roots`)}validateRequestedPath(e){if(typeof e!="string"||e.trim()==="")throw new ae("invalid_path","requested path is empty");if(!Ev(e))throw new ae("invalid_path","requested path must be absolute");let r=So(e);if(r==="/"||r===xo)throw new ae("invalid_path","requested path cannot be the filesystem root");if(r===So(MD()))throw new ae("invalid_path","requested path cannot be the home directory");let n=So(this.managedRoot);if(r===n||r.startsWith(n+xo))throw new ae("invalid_path","requested path cannot live inside the daemon-managed workspaces root");if(this.silverhandStateRoot){let o=r===this.silverhandStateRoot||r.startsWith(this.silverhandStateRoot+xo),i=this.legacyWorkspacesRoot!==void 0&&r.startsWith(this.legacyWorkspacesRoot+xo);if(o&&!i)throw new ae("invalid_path","requested path cannot live inside the silverhand state dir (except under workspaces/)")}return r}list(){let e=this.loadForRead();return Object.entries(e.workspaces).map(([r,n])=>({workspace_id:r,path:n.path,provisioned_at:n.provisioned_at}))}loadForRead(){return this.load()??{schema_version:Cc,binding:this.binding,workspaces:{}}}loadOrInit(){return this.load()??{schema_version:Cc,binding:this.binding,workspaces:{}}}load(){let e;try{if(!zD(this.filePath).isFile())throw new ae("registry_corrupt",`registry path ${this.filePath} is not a file`);e=ID(this.filePath,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw n instanceof ae?n:new ae("registry_corrupt",`failed to read registry: ${n.message}`)}let r;try{r=HD.parse(JSON.parse(e))}catch(n){throw new ae("registry_corrupt",`registry file is malformed: ${n.message}`)}if(!UD(r.binding,this.binding))throw new ae("registry_foreign",`registry is bound to ${r.binding.server_origin}/${r.binding.host_id}, not the current ${this.binding.server_origin}/${this.binding.host_id}`);return r}persist(e){AD(this.managedRoot,{recursive:!0});let r=`${this.filePath}.tmp-${process.pid}`;try{DD(r,`${JSON.stringify(e,null,2)}
568
- `,{mode:384}),$D(r,this.filePath)}catch(n){try{OD(r)}catch{}throw n}}};import{mkdir as Iv}from"node:fs/promises";import{join as $v}from"node:path";async function Gd(t){await Iv(t,{recursive:!0});let e=$v(t,".silverhand");await Iv($v(e,"agents"),{recursive:!0})}function Jd(t){let e=t?.code;return e==="ENOSPC"||e==="EDQUOT"?"fs_quota_exceeded":e==="EACCES"||e==="EPERM"||e==="EROFS"||e==="ENOENT"||e==="ENOTDIR"||e==="EEXIST"?"fs_unavailable":null}var bt=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="WorkspaceProvisionError"}code};async function Yd(t,e){if(t.kind==="agent_home")throw new bt("unsupported_kind","agent_home workspaces are materialized via agent_materialize, not workspace_provision");let r,n;try{({path:r,created:n}=e.registry.provision(t.workspace_id,t.requested_path))}catch(o){throw zv(o)}try{await Gd(r)}catch(o){if(n)try{e.registry.remove(t.workspace_id,r)}catch(i){e.logger?.warn({workspace_id:t.workspace_id,path:r,error:i instanceof Error?i.message:String(i)},"workspace_provision: failed to roll back registry entry after skeleton failure")}throw zv(o)}return{ok:!0,provisioned:n,bound_workspace_path:r}}function zv(t){if(t instanceof bt)return t;if(t instanceof ae)return t.code==="registry_foreign"||t.code==="registry_corrupt"?new bt("registry_unavailable",t.message):t.code==="invalid_path"||t.code==="path_conflict"?new bt(t.code,t.message):new bt("internal_error",t.message);let e=Jd(t);return e?new bt(e,t.message):new bt("internal_error",t instanceof Error?t.message:String(t))}import{join as WD}from"node:path";var xn=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentWorkspaceIndexError"}code};async function Xd(t,e){let r=[],n=[];for(let o of t.workspace_ids){if(ba(o,t.agent_id)){r.push({workspace_id:o,agent_dir:Ge(t.agent_id,e)});continue}let i;try{i=e.registry.resolve(o)}catch(a){if(a instanceof ae){if(a.code==="not_provisioned"){n.push(o);continue}if(a.code==="registry_foreign"||a.code==="registry_corrupt")throw new xn("registry_unavailable",a.message)}throw new xn("internal_error",a instanceof Error?a.message:String(a))}r.push({workspace_id:o,agent_dir:WD(i,".silverhand","agents",t.agent_id)})}return{ok:!0,entries:r,unresolved:n}}import{promises as wo}from"node:fs";import{dirname as ZD,join as Tc}from"node:path";var St=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentL2SeedError"}code};async function Qd(t,e){let r=Hd(t.template_choice);if(r==null)throw new St("unsupported_template",`template '${t.template_choice}' has no host-side L2 entry`);let n;try{n=e.registry.resolve(t.workspace_id)}catch(i){if(i instanceof ae){if(i.code==="not_provisioned")throw new St("workspace_not_provisioned",`workspace ${t.workspace_id} is not provisioned; cannot seed L2`);if(i.code==="registry_foreign"||i.code==="registry_corrupt")throw new St("registry_unavailable",i.message)}throw new St("internal_error",i instanceof Error?i.message:String(i))}let o=Tc(n,".silverhand","agents",t.agent_id);try{let i=!1;await wo.mkdir(o,{recursive:!0});for(let c of r.dirs)await wo.mkdir(Tc(o,c),{recursive:!0});for(let c of r.files){let u=await BD(Tc(o,c.relPath),c.content);i=i||u}let a=await VD(Tc(o,"MEMORY.md"));return{ok:!0,seeded:i,l2_present:a}}catch(i){throw KD(i)}}async function BD(t,e){try{return await wo.access(t),!1}catch{return await wo.mkdir(ZD(t),{recursive:!0}),await wo.writeFile(t,e),!0}}async function VD(t){try{return await wo.access(t),!0}catch{return!1}}function KD(t){if(t instanceof St)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new St("fs_unavailable",t instanceof Error?t.message:String(t)):new St("internal_error",t instanceof Error?t.message:String(t))}import{promises as Ov}from"node:fs";import{join as GD}from"node:path";var zr=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentFilesPurgeError"}code};async function ep(t,e){let r=[],n=0;t.scope==="all"&&r.push(Ge(t.agent_id,e));for(let a of t.workspace_ids){let c;try{c=e.registry.resolve(a)}catch(u){if(u instanceof ae){if(u.code==="not_provisioned"){n+=1;continue}if(u.code==="registry_foreign"||u.code==="registry_corrupt")throw new zr("registry_unavailable",u.message)}throw new zr("internal_error",u instanceof Error?u.message:String(u))}r.push(GD(c,".silverhand","agents",t.agent_id))}let o=0,i=[];for(let a of r)try{let c=await JD(a);await Ov.rm(a,{recursive:!0,force:!0}),c&&(o+=1)}catch(c){if(c?.code==="ENOENT")continue;i.push(`${a}: ${c instanceof Error?c.message:String(c)}`)}if(i.length>0)throw new zr("partial_purge",`failed to remove ${i.length} target(s): ${i.join("; ")}`);return{ok:!0,purged_count:o,skipped_unprovisioned:n}}async function JD(t){try{return await Ov.access(t),!0}catch{return!1}}var Te=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentWorkspaceFsError"}code};import{promises as jv}from"node:fs";import{join as rM}from"node:path";import{promises as zs}from"node:fs";import{isAbsolute as YD,join as XD,relative as QD,sep as eM}from"node:path";async function Ac(t){let e;try{e=await zs.lstat(t)}catch(n){if(tp(n))return{ok:!1,code:"not_found"};throw n}if(e.isSymbolicLink())return{ok:!1,code:"forbidden_path"};let r;try{r=await zs.realpath(t)}catch(n){if(tp(n))return{ok:!1,code:"not_found"};throw n}return{ok:!0,realBase:r,lstat:e}}var Dv=/[\0\\]/;function Ic(t){return!(typeof t!="string"||t.length===0||t==="."||t===".."||t.startsWith(".")||Dv.test(t))}function Mv(t,e={}){if(typeof t!="string")return{ok:!1,code:"forbidden_path"};if(t==="")return e.allowRoot?{ok:!0,segments:[]}:{ok:!1,code:"forbidden_path"};if(t.startsWith("/")||t.endsWith("/"))return{ok:!1,code:"forbidden_path"};if(Dv.test(t))return{ok:!1,code:"forbidden_path"};let r=t.split("/");for(let n of r)if(!Ic(n))return{ok:!1,code:"forbidden_path"};return{ok:!0,segments:r}}async function Nv(t,e){let r=e;for(let o=0;o<t.length;o+=1){r=XD(r,t[o]);let i;try{i=await zs.lstat(r)}catch(a){if(tp(a))return{ok:!1,code:"not_found"};throw a}if(i.isSymbolicLink())return{ok:!1,code:"forbidden_path"};if(o<t.length-1&&!i.isDirectory())return{ok:!1,code:"not_found"};if(o===t.length-1){let a=await zs.realpath(r),c=QD(e,a);return c===""||!c.startsWith("..")&&!c.startsWith(`..${eM}`)&&!YD(c)?{ok:!0,real:a,lstat:i}:{ok:!1,code:"forbidden_path"}}}let n=await zs.lstat(e);return n.isSymbolicLink()?{ok:!1,code:"forbidden_path"}:{ok:!0,real:e,lstat:n}}async function rp(t,e,r={}){let n=Mv(t,r);if(!n.ok)return n;let o=await Ac(e);return o.ok?Nv(n.segments,o.realBase):o}function tp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}import{join as tM}from"node:path";function $c(t,e={}){let r=t.workspace_id;if(!r||ba(r,t.agent_id))return Ge(t.agent_id,e);if(!e.registry)throw new Te("registry_unavailable","workspace registry is not available for scoped agent workspace read");try{let n=e.registry.resolve(r);return tM(n,".silverhand","agents",t.agent_id)}catch(n){if(n instanceof ae){if(n.code==="not_provisioned")throw new Te("workspace_not_provisioned",`workspace ${r} is not provisioned; cannot resolve agent workspace`);if(n.code==="registry_foreign"||n.code==="registry_corrupt")throw new Te("registry_unavailable",n.message)}throw new Te("internal_error",n instanceof Error?n.message:String(n))}}var Lv=5e3;async function np(t,e={}){let r=$c(t,e),n=[];try{let o=await Ac(r);if(!o.ok){if(o.code==="not_found")return{ok:!0,tree:{nodes:[]}};throw new Te("forbidden_path","agent home dir is not a readable directory")}return await Hv(o.realBase,o.realBase,n),{ok:!0,tree:{nodes:n}}}catch(o){throw sM(o)}}async function Hv(t,e,r){if(r.length>=Lv)return;let n;try{n=await jv.readdir(e,{withFileTypes:!0})}catch(i){if(Fv(i))return;throw i}let o=n.slice().sort(nM);for(let i of o){if(r.length>=Lv)return;if(!Ic(i.name)||i.isSymbolicLink())continue;let a=rM(e,i.name),c=oM(t,a),u;try{u=await jv.lstat(a)}catch(l){if(Fv(l))continue;throw l}u.isSymbolicLink()||(i.isDirectory()?(r.push({path:c,kind:"directory",size:0,mtime:u.mtimeMs}),await Hv(t,a,r)):i.isFile()&&r.push({path:c,kind:"file",size:u.size,mtime:u.mtimeMs}))}}function nM(t,e){let r=t.isDirectory(),n=e.isDirectory();return r!==n?r?-1:1:t.name.localeCompare(e.name)}function oM(t,e){return(e.startsWith(t)?e.slice(t.length):e).replace(/^[\\/]+/,"").replace(/\\/g,"/")}function Fv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function sM(t){if(t instanceof Te)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new Te("fs_unavailable",t instanceof Error?t.message:String(t)):new Te("internal_error",t instanceof Error?t.message:String(t))}import{promises as iM}from"node:fs";var Os=64*1024,aM=`
567
+ `,qD=["# Memory","","Role source: system_prompt.md (already loaded by runtime; do not duplicate the role contract here).","","## Key Knowledge","- Read [notes/onboarding-guide.md](notes/onboarding-guide.md) for Silverhand workspace patterns and onboarding guidance","- Read [notes/onboarding-faq.md](notes/onboarding-faq.md) for common user questions and reference answers","- Read [notes/user-preferences.md](notes/user-preferences.md) for durable user preferences","- Read [notes/project.md](notes/project.md) for durable project context and invariants","- Read [notes/work-log.md](notes/work-log.md) for significant work history and follow-ups","","## Active Context","_Keep only the current handoff here. Detailed history belongs in notes/work-log.md._",""].join(`
568
+ `),WD={name:"default",dirs:["notes"],files:[{relPath:"system_prompt.md",content:ND},{relPath:"MEMORY.md",content:qD},{relPath:"notes/onboarding-guide.md",content:jD},{relPath:"notes/onboarding-faq.md",content:LD},{relPath:"notes/user-preferences.md",content:FD},{relPath:"notes/project.md",content:HD},{relPath:"notes/work-log.md",content:UD}]};function Ac(t){switch(t){case"default":return WD;case"onboarding":case"minimal":return null;default:return null}}function Vd(t){let e=Ac(t);return e==null?null:{...e,files:e.files.filter(r=>r.relPath!=="system_prompt.md")}}import{linkSync as ZD,mkdirSync as BD,readFileSync as VD,unlinkSync as KD,writeFileSync as GD}from"node:fs";import{randomUUID as JD}from"node:crypto";import{basename as YD,dirname as Iv,join as $v}from"node:path";var zv=s.object({version:s.number().int().positive(),agent_id:s.string().min(1),template_choice:s.string().min(1),runtime:s.string().min(1),materialized_at:s.number().int().positive()}).strict();function Kd(t){return $v(t,$s)}function Gd(t){let e;try{e=VD(Kd(t),"utf8")}catch(o){if(XD(o)&&o.code==="ENOENT")return{kind:"missing"};throw o}let r;try{r=JSON.parse(e)}catch(o){return{kind:"invalid",reason:`sentinel is not valid JSON: ${o instanceof Error?o.message:String(o)}`}}let n=zv.safeParse(r);return n.success?n.data.version!==1?{kind:"invalid",reason:`sentinel version ${n.data.version} is not supported (handler expects ${1})`}:{kind:"ok",sentinel:n.data}:{kind:"invalid",reason:`sentinel does not match schema: ${n.error.errors.map(o=>`${o.path.join(".")}: ${o.message}`).join("; ")}`}}function Jd(t,e){return t.agent_id!==e.agent_id?{kind:"mismatch",reason:`sentinel.agent_id=${t.agent_id} but request.agent_id=${e.agent_id}`}:t.template_choice!==e.template_choice?{kind:"mismatch",reason:`sentinel.template_choice=${t.template_choice} but request.template_choice=${e.template_choice}`}:t.runtime!==e.runtime?{kind:"mismatch",reason:`sentinel.runtime=${t.runtime} but request.runtime=${e.runtime}`}:{kind:"match"}}function Yd(t,e){let r=Kd(t);BD(Iv(r),{recursive:!0});let n=$v(Iv(r),`.${YD(r)}.${process.pid}.${JD()}.tmp`);try{GD(n,`${JSON.stringify(e)}
569
+ `,{mode:384}),ZD(n,r)}finally{try{KD(n)}catch{}}}function XD(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"}var Ge=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentMaterializeError"}code};function Mv(t,e=nM()){return xn(e,".silverhand","agents",t)}function Nv(t,e){return xn(e,t)}function Je(t,e={}){return e.agentHomeRootDir?Nv(t,e.agentHomeRootDir):Mv(t,e.homeDir)}async function ep(t,e={}){let r=e.now??Date.now,n=Je(t.agent_id,e),o=Ac(t.template_choice);if(!o)throw new Ge("unsupported_template",`daemon does not have a template definition for template_choice='${t.template_choice}'`);let i;try{i=Gd(n)}catch(c){throw Xd(c,`failed to read sentinel at ${xn(n,$s)}`)}if(i.kind==="ok"){let c=Jd(i.sentinel,{agent_id:t.agent_id,template_choice:t.template_choice,runtime:t.runtime});if(c.kind==="match")return{ok:!0,agent_dir:n,agent_home_workspace_path:n,materialized_at:i.sentinel.materialized_at};throw new Ge("agent_dir_collision",`agent_dir already materialized with mismatched metadata; ${c.reason}`)}if(i.kind==="invalid")throw new Ge("agent_dir_collision",`agent_dir has an unrecognized sentinel; ${i.reason}`);let a;try{a=Dv(n)}catch(c){if(uM(c,"ENOENT"))a=null;else throw Xd(c,`failed to read ${n}`)}if(a!==null&&a.length>0)throw new Ge("agent_dir_collision",`agent_dir is not empty and has no sentinel; refusing to overwrite (${a.length} foreign entries: ${a.slice(0,5).join(", ")}${a.length>5?", ...":""})`);try{e.afterEmptyDirCheck!==void 0&&await e.afterEmptyDirCheck(n),sM(n,o),iM(n,o);let c=r();return Yd(n,{version:1,agent_id:t.agent_id,template_choice:t.template_choice,runtime:t.runtime,materialized_at:c}),{ok:!0,agent_dir:n,agent_home_workspace_path:n,materialized_at:c}}catch(c){throw c instanceof Ge?c:Xd(c,`failed to seed template under ${n}`)}}function sM(t,e){Qd(t,{recursive:!0});for(let r of e.dirs)Qd(xn(t,r),{recursive:!0});for(let r of e.files)cM(xn(t,r.relPath),r.content)}function iM(t,e){let r=new Set;for(let i of e.dirs)r.add(i);for(let i of e.files)r.add(i.relPath);let n=aM(t),o=[];for(let i of n)r.has(i)||o.push(i);if(o.length>0)throw new Ge("agent_dir_collision",`post-seed expected-tree scan found foreign content (${o.length} entries: ${o.slice(0,5).join(", ")}${o.length>5?", ...":""}); refusing to write sentinel`)}function aM(t){let e=[],r=[{absDir:t,relDir:""}];for(;r.length>0;){let{absDir:n,relDir:o}=r.pop(),i=Dv(n,{withFileTypes:!0});for(let a of i){let c=o===""?a.name:`${o}/${a.name}`;e.push(c),a.isDirectory()&&r.push({absDir:xn(n,a.name),relDir:c})}}return e}function cM(t,e){Qd(Ov(t),{recursive:!0});let r=xn(Ov(t),`.${oM(t)}.${process.pid}.${rM()}.tmp`);try{tM(r,e,{mode:384}),QD(r,t)}finally{try{eM(r)}catch{}}}function Xd(t,e){if(!jv(t))return new Ge("internal_error",`${e}: ${t instanceof Error?t.message:String(t)}`);switch(t.code){case"ENOSPC":return new Ge("fs_quota_exceeded",`${e}: ${t.message}`);case"EDQUOT":return new Ge("fs_quota_exceeded",`${e}: ${t.message}`);case"EACCES":case"EPERM":case"EROFS":return new Ge("fs_unavailable",`${e}: ${t.message}`);case"EEXIST":return new Ge("agent_dir_collision",`${e}: ${t.message}`);default:return new Ge("internal_error",`${e}: ${t.message}`)}}function jv(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"}function uM(t,e){return jv(t)&&t.code===e}import{createHash as Fv}from"node:crypto";import{mkdirSync as lM,readFileSync as dM,renameSync as pM,statSync as mM,unlinkSync as fM,writeFileSync as hM}from"node:fs";import{homedir as gM}from"node:os";import{isAbsolute as Lv,join as Ic,resolve as xo,sep as wo}from"node:path";var ae=class extends Error{constructor(r,n){super(n);this.code=r;this.name="WorkspaceRegistryError"}code},$c=1,_M="workspace-registry.json",yM="workspaces";function Hv(t){return Fv("sha256").update(`${t.server_origin}\0${t.host_id}`).digest("hex").slice(0,16)}function Uv(t){return Fv("sha256").update(t).digest("hex").slice(0,32)}var vM=s.object({server_origin:s.string().min(1),host_id:s.string().min(1)}).strict(),bM=s.object({path:s.string().min(1),provisioned_at:s.number().int().positive()}).strict(),SM=s.object({schema_version:s.literal($c),binding:vM,workspaces:s.record(s.string().min(1),bM)}).strict();function xM(t,e){return t.server_origin===e.server_origin&&t.host_id===e.host_id}function wM(t,e){return t===e||t.startsWith(e+wo)||e.startsWith(t+wo)}var Ot=class{filePath;managedRoot;binding;silverhandStateRoot;legacyWorkspacesRoot;now;constructor(e){let r=Ic(e.stateDir,Hv(e.binding));this.filePath=Ic(r,_M),this.managedRoot=Ic(r,yM),this.binding=e.binding,this.silverhandStateRoot=e.silverhandStateRoot?xo(e.silverhandStateRoot):void 0,this.legacyWorkspacesRoot=e.legacyWorkspacesRoot?xo(e.legacyWorkspacesRoot):void 0,this.now=e.now??(()=>Date.now())}registryFilePath(){return this.filePath}currentBinding(){return this.binding}resolve(e){let n=this.loadForRead().workspaces[e];if(!n)throw new ae("not_provisioned",`workspace ${e} is not provisioned in this daemon's registry`);return n.path}has(e){return!!this.loadForRead().workspaces[e]}provision(e,r){let n=this.loadOrInit(),o=n.workspaces[e];if(o){if(r===void 0)return{path:o.path,created:!1};if(Lv(r)&&xo(r)===o.path)return{path:o.path,created:!1};let a=this.validateRequestedPath(r);throw new ae("path_conflict",`workspace ${e} is already bound to ${o.path}; refusing to overwrite with ${a}`)}let i;return r===void 0?i=Ic(this.managedRoot,Uv(e)):i=this.validateRequestedPath(r),this.assertNoOverlap(n,e,i),n.workspaces[e]={path:i,provisioned_at:this.now()},this.persist(n),{path:i,created:!0}}remove(e,r){let n=this.loadOrInit(),o=n.workspaces[e];return!o||o.path!==r?!1:(delete n.workspaces[e],this.persist(n),!0)}assertNoOverlap(e,r,n){for(let[o,i]of Object.entries(e.workspaces))if(o!==r&&wM(i.path,n))throw new ae("path_conflict",`path ${n} overlaps workspace ${o} bound at ${i.path}; two workspaces cannot share or nest roots`)}validateRequestedPath(e){if(typeof e!="string"||e.trim()==="")throw new ae("invalid_path","requested path is empty");if(!Lv(e))throw new ae("invalid_path","requested path must be absolute");let r=xo(e);if(r==="/"||r===wo)throw new ae("invalid_path","requested path cannot be the filesystem root");if(r===xo(gM()))throw new ae("invalid_path","requested path cannot be the home directory");let n=xo(this.managedRoot);if(r===n||r.startsWith(n+wo))throw new ae("invalid_path","requested path cannot live inside the daemon-managed workspaces root");if(this.silverhandStateRoot){let o=r===this.silverhandStateRoot||r.startsWith(this.silverhandStateRoot+wo),i=this.legacyWorkspacesRoot!==void 0&&r.startsWith(this.legacyWorkspacesRoot+wo);if(o&&!i)throw new ae("invalid_path","requested path cannot live inside the silverhand state dir (except under workspaces/)")}return r}list(){let e=this.loadForRead();return Object.entries(e.workspaces).map(([r,n])=>({workspace_id:r,path:n.path,provisioned_at:n.provisioned_at}))}loadForRead(){return this.load()??{schema_version:$c,binding:this.binding,workspaces:{}}}loadOrInit(){return this.load()??{schema_version:$c,binding:this.binding,workspaces:{}}}load(){let e;try{if(!mM(this.filePath).isFile())throw new ae("registry_corrupt",`registry path ${this.filePath} is not a file`);e=dM(this.filePath,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw n instanceof ae?n:new ae("registry_corrupt",`failed to read registry: ${n.message}`)}let r;try{r=SM.parse(JSON.parse(e))}catch(n){throw new ae("registry_corrupt",`registry file is malformed: ${n.message}`)}if(!xM(r.binding,this.binding))throw new ae("registry_foreign",`registry is bound to ${r.binding.server_origin}/${r.binding.host_id}, not the current ${this.binding.server_origin}/${this.binding.host_id}`);return r}persist(e){lM(this.managedRoot,{recursive:!0});let r=`${this.filePath}.tmp-${process.pid}`;try{hM(r,`${JSON.stringify(e,null,2)}
570
+ `,{mode:384}),pM(r,this.filePath)}catch(n){try{fM(r)}catch{}throw n}}};import{mkdir as qv}from"node:fs/promises";import{join as Wv}from"node:path";async function tp(t){await qv(t,{recursive:!0});let e=Wv(t,".silverhand");await qv(Wv(e,"agents"),{recursive:!0})}function rp(t){let e=t?.code;return e==="ENOSPC"||e==="EDQUOT"?"fs_quota_exceeded":e==="EACCES"||e==="EPERM"||e==="EROFS"||e==="ENOENT"||e==="ENOTDIR"||e==="EEXIST"?"fs_unavailable":null}var St=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="WorkspaceProvisionError"}code};async function np(t,e){if(t.kind==="agent_home")throw new St("unsupported_kind","agent_home workspaces are materialized via agent_materialize, not workspace_provision");let r,n;try{({path:r,created:n}=e.registry.provision(t.workspace_id,t.requested_path))}catch(o){throw Zv(o)}try{await tp(r)}catch(o){if(n)try{e.registry.remove(t.workspace_id,r)}catch(i){e.logger?.warn({workspace_id:t.workspace_id,path:r,error:i instanceof Error?i.message:String(i)},"workspace_provision: failed to roll back registry entry after skeleton failure")}throw Zv(o)}return{ok:!0,provisioned:n,bound_workspace_path:r}}function Zv(t){if(t instanceof St)return t;if(t instanceof ae)return t.code==="registry_foreign"||t.code==="registry_corrupt"?new St("registry_unavailable",t.message):t.code==="invalid_path"||t.code==="path_conflict"?new St(t.code,t.message):new St("internal_error",t.message);let e=rp(t);return e?new St(e,t.message):new St("internal_error",t instanceof Error?t.message:String(t))}import{join as kM}from"node:path";var wn=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentWorkspaceIndexError"}code};async function op(t,e){let r=[],n=[];for(let o of t.workspace_ids){if(Sa(o,t.agent_id)){r.push({workspace_id:o,agent_dir:Je(t.agent_id,e)});continue}let i;try{i=e.registry.resolve(o)}catch(a){if(a instanceof ae){if(a.code==="not_provisioned"){n.push(o);continue}if(a.code==="registry_foreign"||a.code==="registry_corrupt")throw new wn("registry_unavailable",a.message)}throw new wn("internal_error",a instanceof Error?a.message:String(a))}r.push({workspace_id:o,agent_dir:kM(i,".silverhand","agents",t.agent_id)})}return{ok:!0,entries:r,unresolved:n}}import{promises as ko}from"node:fs";import{dirname as RM,join as zc}from"node:path";var xt=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentL2SeedError"}code};async function sp(t,e){let r=Vd(t.template_choice);if(r==null)throw new xt("unsupported_template",`template '${t.template_choice}' has no host-side L2 entry`);let n;try{n=e.registry.resolve(t.workspace_id)}catch(i){if(i instanceof ae){if(i.code==="not_provisioned")throw new xt("workspace_not_provisioned",`workspace ${t.workspace_id} is not provisioned; cannot seed L2`);if(i.code==="registry_foreign"||i.code==="registry_corrupt")throw new xt("registry_unavailable",i.message)}throw new xt("internal_error",i instanceof Error?i.message:String(i))}let o=zc(n,".silverhand","agents",t.agent_id);try{let i=!1;await ko.mkdir(o,{recursive:!0});for(let c of r.dirs)await ko.mkdir(zc(o,c),{recursive:!0});for(let c of r.files){let u=await PM(zc(o,c.relPath),c.content);i=i||u}let a=await EM(zc(o,"MEMORY.md"));return{ok:!0,seeded:i,l2_present:a}}catch(i){throw CM(i)}}async function PM(t,e){try{return await ko.access(t),!1}catch{return await ko.mkdir(RM(t),{recursive:!0}),await ko.writeFile(t,e),!0}}async function EM(t){try{return await ko.access(t),!0}catch{return!1}}function CM(t){if(t instanceof xt)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new xt("fs_unavailable",t instanceof Error?t.message:String(t)):new xt("internal_error",t instanceof Error?t.message:String(t))}import{promises as Bv}from"node:fs";import{join as TM}from"node:path";var Or=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentFilesPurgeError"}code};async function ip(t,e){let r=[],n=0;t.scope==="all"&&r.push(Je(t.agent_id,e));for(let a of t.workspace_ids){let c;try{c=e.registry.resolve(a)}catch(u){if(u instanceof ae){if(u.code==="not_provisioned"){n+=1;continue}if(u.code==="registry_foreign"||u.code==="registry_corrupt")throw new Or("registry_unavailable",u.message)}throw new Or("internal_error",u instanceof Error?u.message:String(u))}r.push(TM(c,".silverhand","agents",t.agent_id))}let o=0,i=[];for(let a of r)try{let c=await AM(a);await Bv.rm(a,{recursive:!0,force:!0}),c&&(o+=1)}catch(c){if(c?.code==="ENOENT")continue;i.push(`${a}: ${c instanceof Error?c.message:String(c)}`)}if(i.length>0)throw new Or("partial_purge",`failed to remove ${i.length} target(s): ${i.join("; ")}`);return{ok:!0,purged_count:o,skipped_unprovisioned:n}}async function AM(t){try{return await Bv.access(t),!0}catch{return!1}}var Te=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentWorkspaceFsError"}code};import{promises as Jv}from"node:fs";import{join as MM}from"node:path";import{promises as Os}from"node:fs";import{isAbsolute as IM,join as $M,relative as zM,sep as OM}from"node:path";async function Oc(t){let e;try{e=await Os.lstat(t)}catch(n){if(ap(n))return{ok:!1,code:"not_found"};throw n}if(e.isSymbolicLink())return{ok:!1,code:"forbidden_path"};let r;try{r=await Os.realpath(t)}catch(n){if(ap(n))return{ok:!1,code:"not_found"};throw n}return{ok:!0,realBase:r,lstat:e}}var Vv=/[\0\\]/;function Dc(t){return!(typeof t!="string"||t.length===0||t==="."||t===".."||t.startsWith(".")||Vv.test(t))}function Kv(t,e={}){if(typeof t!="string")return{ok:!1,code:"forbidden_path"};if(t==="")return e.allowRoot?{ok:!0,segments:[]}:{ok:!1,code:"forbidden_path"};if(t.startsWith("/")||t.endsWith("/"))return{ok:!1,code:"forbidden_path"};if(Vv.test(t))return{ok:!1,code:"forbidden_path"};let r=t.split("/");for(let n of r)if(!Dc(n))return{ok:!1,code:"forbidden_path"};return{ok:!0,segments:r}}async function Gv(t,e){let r=e;for(let o=0;o<t.length;o+=1){r=$M(r,t[o]);let i;try{i=await Os.lstat(r)}catch(a){if(ap(a))return{ok:!1,code:"not_found"};throw a}if(i.isSymbolicLink())return{ok:!1,code:"forbidden_path"};if(o<t.length-1&&!i.isDirectory())return{ok:!1,code:"not_found"};if(o===t.length-1){let a=await Os.realpath(r),c=zM(e,a);return c===""||!c.startsWith("..")&&!c.startsWith(`..${OM}`)&&!IM(c)?{ok:!0,real:a,lstat:i}:{ok:!1,code:"forbidden_path"}}}let n=await Os.lstat(e);return n.isSymbolicLink()?{ok:!1,code:"forbidden_path"}:{ok:!0,real:e,lstat:n}}async function cp(t,e,r={}){let n=Kv(t,r);if(!n.ok)return n;let o=await Oc(e);return o.ok?Gv(n.segments,o.realBase):o}function ap(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}import{join as DM}from"node:path";function Mc(t,e={}){let r=t.workspace_id;if(!r||Sa(r,t.agent_id))return Je(t.agent_id,e);if(!e.registry)throw new Te("registry_unavailable","workspace registry is not available for scoped agent workspace read");try{let n=e.registry.resolve(r);return DM(n,".silverhand","agents",t.agent_id)}catch(n){if(n instanceof ae){if(n.code==="not_provisioned")throw new Te("workspace_not_provisioned",`workspace ${r} is not provisioned; cannot resolve agent workspace`);if(n.code==="registry_foreign"||n.code==="registry_corrupt")throw new Te("registry_unavailable",n.message)}throw new Te("internal_error",n instanceof Error?n.message:String(n))}}var Yv=5e3;async function up(t,e={}){let r=Mc(t,e),n=[];try{let o=await Oc(r);if(!o.ok){if(o.code==="not_found")return{ok:!0,tree:{nodes:[]}};throw new Te("forbidden_path","agent home dir is not a readable directory")}return await Qv(o.realBase,o.realBase,n),{ok:!0,tree:{nodes:n}}}catch(o){throw LM(o)}}async function Qv(t,e,r){if(r.length>=Yv)return;let n;try{n=await Jv.readdir(e,{withFileTypes:!0})}catch(i){if(Xv(i))return;throw i}let o=n.slice().sort(NM);for(let i of o){if(r.length>=Yv)return;if(!Dc(i.name)||i.isSymbolicLink())continue;let a=MM(e,i.name),c=jM(t,a),u;try{u=await Jv.lstat(a)}catch(l){if(Xv(l))continue;throw l}u.isSymbolicLink()||(i.isDirectory()?(r.push({path:c,kind:"directory",size:0,mtime:u.mtimeMs}),await Qv(t,a,r)):i.isFile()&&r.push({path:c,kind:"file",size:u.size,mtime:u.mtimeMs}))}}function NM(t,e){let r=t.isDirectory(),n=e.isDirectory();return r!==n?r?-1:1:t.name.localeCompare(e.name)}function jM(t,e){return(e.startsWith(t)?e.slice(t.length):e).replace(/^[\\/]+/,"").replace(/\\/g,"/")}function Xv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function LM(t){if(t instanceof Te)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new Te("fs_unavailable",t instanceof Error?t.message:String(t)):new Te("internal_error",t instanceof Error?t.message:String(t))}import{promises as FM}from"node:fs";var Ds=64*1024,HM=`
569
571
 
570
- \u2026 (truncated; open in Finder for full content)`;async function sp(t,e={}){let r=$c(t,e),n;try{n=await rp(t.path,r)}catch(d){throw op(d)}if(!n.ok)throw new Te(n.code,n.code==="forbidden_path"?"path is not a readable file under the agent home dir":"path not found");if(!n.lstat.isFile())throw new Te("not_found","path is not a regular file");let o=Buffer.allocUnsafe(Os+1),i;try{i=await iM.open(n.real,"r")}catch(d){throw op(d)}let a=0;try{for(;a<Os+1;){let d=Os+1-a,p=await i.read(o,a,d,a);if(p.bytesRead===0)break;a+=p.bytesRead}}catch(d){throw await i.close().catch(()=>{}),op(d)}await i.close().catch(()=>{});let c=n.lstat.size>Os,u=Math.min(a,Os),l=c?o.subarray(0,u).toString("utf8")+aM:o.subarray(0,a).toString("utf8");return{ok:!0,file:{path:t.path,content:l,size:n.lstat.size,mtime:n.lstat.mtimeMs,truncated:c}}}function op(t){if(t instanceof Te)return t;let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"?new Te("not_found","path not found"):typeof e=="string"&&/^E[A-Z]+$/.test(e)?new Te("fs_unavailable",t instanceof Error?t.message:String(t)):new Te("internal_error",t instanceof Error?t.message:String(t))}import{randomUUID as cM}from"node:crypto";import{promises as Ds}from"node:fs";import{dirname as uM,join as ip}from"node:path";var ko=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentProfileMcpError"}code};async function Uv(t,e={}){let r=ip(Ge(t.agent_id,e),Tr);try{return{ok:!0,raw:await Ds.readFile(r,"utf-8")}}catch(n){if(n?.code==="ENOENT")return{ok:!0,raw:null};throw Wv(n)}}async function qv(t,e={}){let r=io(t.raw);if(!r.ok)throw new ko("invalid_config",r.error);let n=Ge(t.agent_id,e),o=ip(n,Tr),i=Buffer.byteLength(t.raw,"utf-8"),a=ip(n,`.${Tr}.${process.pid}.${cM()}.tmp`);try{await Ds.mkdir(uM(o),{recursive:!0}),await Ds.writeFile(a,t.raw,{mode:384}),await Ds.rename(a,o)}catch(c){throw await Ds.rm(a,{force:!0}).catch(()=>{}),Wv(c)}return{ok:!0,bytes_written:i}}function Wv(t){if(t instanceof ko)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new ko("fs_unavailable",t instanceof Error?t.message:String(t)):new ko("internal_error",t instanceof Error?t.message:String(t))}import{promises as v2}from"node:fs";import{join as b2}from"node:path";var ap=Object.freeze({status:"aborted"});function b(t,e,r){function n(c,u){var l;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(l=c._zod).traits??(l.traits=new Set),c._zod.traits.add(t),e(c,u);for(let d in a.prototype)d in c||Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;n(l,c),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}var fr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},zc={};function ut(t){return t&&Object.assign(zc,t),zc}var se={};Xi(se,{BIGINT_FORMAT_RANGES:()=>Bv,Class:()=>up,NUMBER_FORMAT_RANGES:()=>_p,aborted:()=>kn,allowsEval:()=>fp,assert:()=>fM,assertEqual:()=>lM,assertIs:()=>pM,assertNever:()=>mM,assertNotEqual:()=>dM,assignProp:()=>mp,cached:()=>Ns,captureStackTrace:()=>Dc,cleanEnum:()=>EM,cleanRegex:()=>Ls,clone:()=>Ot,createTransparentProxy:()=>bM,defineLazy:()=>me,esc:()=>wn,escapeRegex:()=>Or,extend:()=>wM,finalizeIssue:()=>Dt,floatSafeRemainder:()=>pp,getElementAtPath:()=>hM,getEnumValues:()=>lp,getLengthableOrigin:()=>Fs,getParsedType:()=>vM,getSizableOrigin:()=>Vv,isObject:()=>Ro,isPlainObject:()=>Po,issue:()=>yp,joinValues:()=>Oc,jsonStringifyReplacer:()=>dp,merge:()=>kM,normalizeParams:()=>N,nullish:()=>js,numKeys:()=>yM,omit:()=>xM,optionalKeys:()=>gp,partial:()=>RM,pick:()=>SM,prefixIssues:()=>Xt,primitiveTypes:()=>Zv,promiseAllObject:()=>gM,propertyKeyTypes:()=>hp,randomString:()=>_M,required:()=>PM,stringifyPrimitive:()=>Mc,unwrapMessage:()=>Ms});function lM(t){return t}function dM(t){return t}function pM(t){}function mM(t){throw new Error}function fM(t){}function lp(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Oc(t,e="|"){return t.map(r=>Mc(r)).join(e)}function dp(t,e){return typeof e=="bigint"?e.toString():e}function Ns(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function js(t){return t==null}function Ls(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pp(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}function me(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function mp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function hM(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function gM(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function _M(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function wn(t){return JSON.stringify(t)}var Dc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ro(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fp=Ns(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Po(t){if(Ro(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ro(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yM(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var vM=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},hp=new Set(["string","number","symbol"]),Zv=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function N(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function bM(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Mc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var _p={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Bv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function SM(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function xM(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function wM(t,e){if(!Po(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return mp(this,"shape",n),n},checks:[]};return Ot(t,r)}function kM(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function RM(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return Ot(e,{...e._zod.def,shape:o,checks:[]})}function PM(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new t({type:"nonoptional",innerType:n[i]});return Ot(e,{...e._zod.def,shape:o,checks:[]})}function kn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Xt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ms(t){return typeof t=="string"?t:t?.message}function Dt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ms(t.inst?._zod.def?.error?.(t))??Ms(e?.error?.(t))??Ms(r.customError?.(t))??Ms(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Vv(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function yp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function EM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var up=class{constructor(...e){}};var Kv=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,dp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Nc=b("$ZodError",Kv),vp=b("$ZodError",Kv,{Parent:Error});function bp(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Sp(t,e){let r=e||function(i){return i.message},n={_errors:[]},o=i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return o(t),n}var Gv=t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new fr;if(a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>Dt(u,i,ut())));throw Dc(c,o?.callee),c}return a.value};var Jv=t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>Dt(u,i,ut())));throw Dc(c,o?.callee),c}return a.value};var xp=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new fr;return i.issues.length?{success:!1,error:new(t??Nc)(i.issues.map(a=>Dt(a,o,ut())))}:{success:!0,data:i.value}},Hs=xp(vp),wp=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>Dt(a,o,ut())))}:{success:!0,data:i.value}},jc=wp(vp);var Yv=/^[cC][^\s-]{8,}$/,Xv=/^[0-9a-z]+$/,Qv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eb=/^[0-9a-vA-V]{20}$/,tb=/^[A-Za-z0-9]{27}$/,rb=/^[a-zA-Z0-9_-]{21}$/,nb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ob=/^([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})$/,kp=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/;var sb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var TM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ib(){return new RegExp(TM,"u")}var ab=/^(?:(?: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])$/,cb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,ub=/^((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])$/,lb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,db=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rp=/^[A-Za-z0-9_-]*$/,pb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var mb=/^\+(?:[0-9]){6,14}[0-9]$/,fb="(?:(?:\\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])))",hb=new RegExp(`^${fb}$`);function gb(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function _b(t){return new RegExp(`^${gb(t)}$`)}function yb(t){let e=gb({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${fb}T(?:${n})$`)}var vb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},bb=/^\d+n?$/,Sb=/^\d+$/,xb=/^-?\d+(?:\.\d+)?/i,wb=/true|false/i,kb=/null/i;var Rb=/^[^A-Z]*$/,Pb=/^[^a-z]*$/;var qe=b("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Eb={number:"number",bigint:"bigint",object:"date"},Pp=b("$ZodCheckLessThan",(t,e)=>{qe.init(t,e);let r=Eb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ep=b("$ZodCheckGreaterThan",(t,e)=>{qe.init(t,e);let r=Eb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Cb=b("$ZodCheckMultipleOf",(t,e)=>{qe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):pp(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Tb=b("$ZodCheckNumberFormat",(t,e)=>{qe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=_p[e.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=e.format,c.minimum=o,c.maximum=i,r&&(c.pattern=Sb)}),t._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}c<o&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),c>i&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}});var Ab=b("$ZodCheckMaxLength",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!js(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let a=Fs(o);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ib=b("$ZodCheckMinLength",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!js(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let a=Fs(o);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),$b=b("$ZodCheckLengthEquals",(t,e)=>{var r;qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!js(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,i=o.length;if(i===e.length)return;let a=Fs(o),c=i>e.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Us=b("$ZodCheckStringFormat",(t,e)=>{var r,n;qe.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),zb=b("$ZodCheckRegex",(t,e)=>{Us.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ob=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Rb),Us.init(t,e)}),Db=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Pb),Us.init(t,e)}),Mb=b("$ZodCheckIncludes",(t,e)=>{qe.init(t,e);let r=Or(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Nb=b("$ZodCheckStartsWith",(t,e)=>{qe.init(t,e);let r=new RegExp(`^${Or(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),jb=b("$ZodCheckEndsWith",(t,e)=>{qe.init(t,e);let r=new RegExp(`.*${Or(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Lb=b("$ZodCheckOverwrite",(t,e)=>{qe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Fc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
572
+ \u2026 (truncated; open in Finder for full content)`;async function dp(t,e={}){let r=Mc(t,e),n;try{n=await cp(t.path,r)}catch(d){throw lp(d)}if(!n.ok)throw new Te(n.code,n.code==="forbidden_path"?"path is not a readable file under the agent home dir":"path not found");if(!n.lstat.isFile())throw new Te("not_found","path is not a regular file");let o=Buffer.allocUnsafe(Ds+1),i;try{i=await FM.open(n.real,"r")}catch(d){throw lp(d)}let a=0;try{for(;a<Ds+1;){let d=Ds+1-a,p=await i.read(o,a,d,a);if(p.bytesRead===0)break;a+=p.bytesRead}}catch(d){throw await i.close().catch(()=>{}),lp(d)}await i.close().catch(()=>{});let c=n.lstat.size>Ds,u=Math.min(a,Ds),l=c?o.subarray(0,u).toString("utf8")+HM:o.subarray(0,a).toString("utf8");return{ok:!0,file:{path:t.path,content:l,size:n.lstat.size,mtime:n.lstat.mtimeMs,truncated:c}}}function lp(t){if(t instanceof Te)return t;let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"?new Te("not_found","path not found"):typeof e=="string"&&/^E[A-Z]+$/.test(e)?new Te("fs_unavailable",t instanceof Error?t.message:String(t)):new Te("internal_error",t instanceof Error?t.message:String(t))}import{randomUUID as UM}from"node:crypto";import{promises as Ms}from"node:fs";import{dirname as qM,join as pp}from"node:path";var Ro=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="AgentProfileMcpError"}code};async function eb(t,e={}){let r=pp(Je(t.agent_id,e),Ar);try{return{ok:!0,raw:await Ms.readFile(r,"utf-8")}}catch(n){if(n?.code==="ENOENT")return{ok:!0,raw:null};throw rb(n)}}async function tb(t,e={}){let r=ao(t.raw);if(!r.ok)throw new Ro("invalid_config",r.error);let n=Je(t.agent_id,e),o=pp(n,Ar),i=Buffer.byteLength(t.raw,"utf-8"),a=pp(n,`.${Ar}.${process.pid}.${UM()}.tmp`);try{await Ms.mkdir(qM(o),{recursive:!0}),await Ms.writeFile(a,t.raw,{mode:384}),await Ms.rename(a,o)}catch(c){throw await Ms.rm(a,{force:!0}).catch(()=>{}),rb(c)}return{ok:!0,bytes_written:i}}function rb(t){if(t instanceof Ro)return t;let e=t?.code;return typeof e=="string"&&/^E[A-Z]+$/.test(e)?new Ro("fs_unavailable",t instanceof Error?t.message:String(t)):new Ro("internal_error",t instanceof Error?t.message:String(t))}import{promises as Q2}from"node:fs";import{join as eZ}from"node:path";var mp=Object.freeze({status:"aborted"});function b(t,e,r){function n(c,u){var l;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(l=c._zod).traits??(l.traits=new Set),c._zod.traits.add(t),e(c,u);for(let d in a.prototype)d in c||Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;n(l,c),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}var hr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Nc={};function lt(t){return t&&Object.assign(Nc,t),Nc}var se={};Qi(se,{BIGINT_FORMAT_RANGES:()=>ob,Class:()=>hp,NUMBER_FORMAT_RANGES:()=>wp,aborted:()=>Rn,allowsEval:()=>bp,assert:()=>KM,assertEqual:()=>WM,assertIs:()=>BM,assertNever:()=>VM,assertNotEqual:()=>ZM,assignProp:()=>vp,cached:()=>js,captureStackTrace:()=>Lc,cleanEnum:()=>aN,cleanRegex:()=>Fs,clone:()=>Dt,createTransparentProxy:()=>eN,defineLazy:()=>me,esc:()=>kn,escapeRegex:()=>Dr,extend:()=>nN,finalizeIssue:()=>Mt,floatSafeRemainder:()=>yp,getElementAtPath:()=>GM,getEnumValues:()=>gp,getLengthableOrigin:()=>Hs,getParsedType:()=>QM,getSizableOrigin:()=>sb,isObject:()=>Po,isPlainObject:()=>Eo,issue:()=>kp,joinValues:()=>jc,jsonStringifyReplacer:()=>_p,merge:()=>oN,normalizeParams:()=>N,nullish:()=>Ls,numKeys:()=>XM,omit:()=>rN,optionalKeys:()=>xp,partial:()=>sN,pick:()=>tN,prefixIssues:()=>Qt,primitiveTypes:()=>nb,promiseAllObject:()=>JM,propertyKeyTypes:()=>Sp,randomString:()=>YM,required:()=>iN,stringifyPrimitive:()=>Fc,unwrapMessage:()=>Ns});function WM(t){return t}function ZM(t){return t}function BM(t){}function VM(t){throw new Error}function KM(t){}function gp(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function jc(t,e="|"){return t.map(r=>Fc(r)).join(e)}function _p(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ls(t){return t==null}function Fs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function yp(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}function me(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function vp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function GM(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function JM(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function YM(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function kn(t){return JSON.stringify(t)}var Lc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Po(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var bp=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Eo(t){if(Po(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Po(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function XM(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var QM=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Sp=new Set(["string","number","symbol"]),nb=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function N(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function eN(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Fc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function xp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var wp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ob={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function tN(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Dt(t,{...t._zod.def,shape:r,checks:[]})}function rN(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Dt(t,{...t._zod.def,shape:r,checks:[]})}function nN(t,e){if(!Eo(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return vp(this,"shape",n),n},checks:[]};return Dt(t,r)}function oN(t,e){return Dt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return vp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function sN(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return Dt(e,{...e._zod.def,shape:o,checks:[]})}function iN(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new t({type:"nonoptional",innerType:n[i]});return Dt(e,{...e._zod.def,shape:o,checks:[]})}function Rn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Qt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ns(t){return typeof t=="string"?t:t?.message}function Mt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ns(t.inst?._zod.def?.error?.(t))??Ns(e?.error?.(t))??Ns(r.customError?.(t))??Ns(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function sb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Hs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function kp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function aN(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var hp=class{constructor(...e){}};var ib=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,_p,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Hc=b("$ZodError",ib),Rp=b("$ZodError",ib,{Parent:Error});function Pp(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Ep(t,e){let r=e||function(i){return i.message},n={_errors:[]},o=i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}};return o(t),n}var ab=t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new hr;if(a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>Mt(u,i,lt())));throw Lc(c,o?.callee),c}return a.value};var cb=t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>Mt(u,i,lt())));throw Lc(c,o?.callee),c}return a.value};var Cp=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new hr;return i.issues.length?{success:!1,error:new(t??Hc)(i.issues.map(a=>Mt(a,o,lt())))}:{success:!0,data:i.value}},Us=Cp(Rp),Tp=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>Mt(a,o,lt())))}:{success:!0,data:i.value}},Uc=Tp(Rp);var ub=/^[cC][^\s-]{8,}$/,lb=/^[0-9a-z]+$/,db=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pb=/^[0-9a-vA-V]{20}$/,mb=/^[A-Za-z0-9]{27}$/,fb=/^[a-zA-Z0-9_-]{21}$/,hb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gb=/^([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})$/,Ap=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/;var _b=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var uN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function yb(){return new RegExp(uN,"u")}var vb=/^(?:(?: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])$/,bb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Sb=/^((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])$/,xb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ip=/^[A-Za-z0-9_-]*$/,kb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Rb=/^\+(?:[0-9]){6,14}[0-9]$/,Pb="(?:(?:\\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])))",Eb=new RegExp(`^${Pb}$`);function Cb(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Tb(t){return new RegExp(`^${Cb(t)}$`)}function Ab(t){let e=Cb({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Pb}T(?:${n})$`)}var Ib=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},$b=/^\d+n?$/,zb=/^\d+$/,Ob=/^-?\d+(?:\.\d+)?/i,Db=/true|false/i,Mb=/null/i;var Nb=/^[^A-Z]*$/,jb=/^[^a-z]*$/;var We=b("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Lb={number:"number",bigint:"bigint",object:"date"},$p=b("$ZodCheckLessThan",(t,e)=>{We.init(t,e);let r=Lb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zp=b("$ZodCheckGreaterThan",(t,e)=>{We.init(t,e);let r=Lb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fb=b("$ZodCheckMultipleOf",(t,e)=>{We.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):yp(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Hb=b("$ZodCheckNumberFormat",(t,e)=>{We.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=wp[e.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=e.format,c.minimum=o,c.maximum=i,r&&(c.pattern=zb)}),t._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}c<o&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),c>i&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}});var Ub=b("$ZodCheckMaxLength",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ls(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let a=Hs(o);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qb=b("$ZodCheckMinLength",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ls(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let a=Hs(o);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wb=b("$ZodCheckLengthEquals",(t,e)=>{var r;We.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ls(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,i=o.length;if(i===e.length)return;let a=Hs(o),c=i>e.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),qs=b("$ZodCheckStringFormat",(t,e)=>{var r,n;We.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Zb=b("$ZodCheckRegex",(t,e)=>{qs.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Bb=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nb),qs.init(t,e)}),Vb=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jb),qs.init(t,e)}),Kb=b("$ZodCheckIncludes",(t,e)=>{We.init(t,e);let r=Dr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Gb=b("$ZodCheckStartsWith",(t,e)=>{We.init(t,e);let r=new RegExp(`^${Dr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Jb=b("$ZodCheckEndsWith",(t,e)=>{We.init(t,e);let r=new RegExp(`.*${Dr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Yb=b("$ZodCheckOverwrite",(t,e)=>{We.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Wc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
571
573
  `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
572
- `))}};var Hb={major:4,minor:0,patch:0};var ce=b("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Hb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=kn(i),l;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,m=d._zod.check(i);if(m instanceof Promise&&c?.async===!1)throw new fr;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,i.issues.length!==p&&(u||(u=kn(i,p)))});else{if(i.issues.length===p)continue;u||(u=kn(i,p))}}return l?l.then(()=>i):i};t._zod.run=(i,a)=>{let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new fr;return c.then(u=>o(u,n,a))}return o(c,n,a)}}t["~standard"]={validate:o=>{try{let i=Hs(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return jc(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Uc=b("$ZodString",(t,e)=>{ce.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??vb(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ge=b("$ZodStringFormat",(t,e)=>{Us.init(t,e),Uc.init(t,e)}),Yb=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ob),ge.init(t,e)}),Xb=b("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=kp(n))}else e.pattern??(e.pattern=kp());ge.init(t,e)}),Qb=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=sb),ge.init(t,e)}),eS=b("$ZodURL",(t,e)=>{ge.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),i=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:pb.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),tS=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ib()),ge.init(t,e)}),rS=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=rb),ge.init(t,e)}),nS=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Yv),ge.init(t,e)}),oS=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Xv),ge.init(t,e)}),sS=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Qv),ge.init(t,e)}),iS=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=eb),ge.init(t,e)}),aS=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=tb),ge.init(t,e)}),cS=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=yb(e)),ge.init(t,e)}),uS=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=hb),ge.init(t,e)}),lS=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=_b(e)),ge.init(t,e)}),dS=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=nb),ge.init(t,e)}),pS=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ab),ge.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),mS=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=cb),ge.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),fS=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ub),ge.init(t,e)}),hS=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=lb),ge.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function gS(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var _S=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=db),ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{gS(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function AM(t){if(!Rp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return gS(r)}var yS=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Rp),ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{AM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),vS=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=mb),ge.init(t,e)});function IM(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var bS=b("$ZodJWT",(t,e)=>{ge.init(t,e),t._zod.check=r=>{IM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Tp=b("$ZodNumber",(t,e)=>{ce.init(t,e),t._zod.pattern=t._zod.bag.pattern??xb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),r}}),SS=b("$ZodNumber",(t,e)=>{Tb.init(t,e),Tp.init(t,e)}),xS=b("$ZodBoolean",(t,e)=>{ce.init(t,e),t._zod.pattern=wb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),wS=b("$ZodBigInt",(t,e)=>{ce.init(t,e),t._zod.pattern=bb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var kS=b("$ZodNull",(t,e)=>{ce.init(t,e),t._zod.pattern=kb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),RS=b("$ZodAny",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),PS=b("$ZodUnknown",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),ES=b("$ZodNever",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var CS=b("$ZodDate",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),r}});function Ub(t,e,r){t.issues.length&&e.issues.push(...Xt(r,t.issues)),e.value[r]=t.value}var TS=b("$ZodArray",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let c=o[a],u=e.element._zod.run({value:c,issues:[]},n);u instanceof Promise?i.push(u.then(l=>Ub(l,r,a))):Ub(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});function Hc(t,e,r){t.issues.length&&e.issues.push(...Xt(r,t.issues)),e.value[r]=t.value}function qb(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Xt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var AS=b("$ZodObject",(t,e)=>{ce.init(t,e);let r=Ns(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof ce))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=gp(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});me(t._zod,"propValues",()=>{let p=e.shape,m={};for(let f in p){let _=p[f]._zod;if(_.values){m[f]??(m[f]=new Set);for(let g of _.values)m[f].add(g)}}return m});let n=p=>{let m=new Fc(["shape","payload","ctx"]),f=r.value,_=x=>{let w=wn(x);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),y=0;for(let x of f.keys)g[x]=`key_${y++}`;m.write("const newResult = {}");for(let x of f.keys)if(f.optionalKeys.has(x)){let w=g[x];m.write(`const ${w} = ${_(x)};`);let T=wn(x);m.write(`
574
+ `))}};var Qb={major:4,minor:0,patch:0};var ce=b("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Qb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Rn(i),l;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,m=d._zod.check(i);if(m instanceof Promise&&c?.async===!1)throw new hr;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,i.issues.length!==p&&(u||(u=Rn(i,p)))});else{if(i.issues.length===p)continue;u||(u=Rn(i,p))}}return l?l.then(()=>i):i};t._zod.run=(i,a)=>{let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new hr;return c.then(u=>o(u,n,a))}return o(c,n,a)}}t["~standard"]={validate:o=>{try{let i=Us(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Uc(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Bc=b("$ZodString",(t,e)=>{ce.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ib(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),_e=b("$ZodStringFormat",(t,e)=>{qs.init(t,e),Bc.init(t,e)}),uS=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=gb),_e.init(t,e)}),lS=b("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ap(n))}else e.pattern??(e.pattern=Ap());_e.init(t,e)}),dS=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=_b),_e.init(t,e)}),pS=b("$ZodURL",(t,e)=>{_e.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),i=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kb.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),mS=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=yb()),_e.init(t,e)}),fS=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=fb),_e.init(t,e)}),hS=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ub),_e.init(t,e)}),gS=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=lb),_e.init(t,e)}),_S=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=db),_e.init(t,e)}),yS=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pb),_e.init(t,e)}),vS=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mb),_e.init(t,e)}),bS=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ab(e)),_e.init(t,e)}),SS=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Eb),_e.init(t,e)}),xS=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Tb(e)),_e.init(t,e)}),wS=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hb),_e.init(t,e)}),kS=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=vb),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),RS=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=bb),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),PS=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Sb),_e.init(t,e)}),ES=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=xb),_e.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function CS(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var TS=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=wb),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{CS(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function lN(t){if(!Ip.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return CS(r)}var AS=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ip),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{lN(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),IS=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Rb),_e.init(t,e)});function dN(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var $S=b("$ZodJWT",(t,e)=>{_e.init(t,e),t._zod.check=r=>{dN(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Dp=b("$ZodNumber",(t,e)=>{ce.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ob,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),r}}),zS=b("$ZodNumber",(t,e)=>{Hb.init(t,e),Dp.init(t,e)}),OS=b("$ZodBoolean",(t,e)=>{ce.init(t,e),t._zod.pattern=Db,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),DS=b("$ZodBigInt",(t,e)=>{ce.init(t,e),t._zod.pattern=$b,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var MS=b("$ZodNull",(t,e)=>{ce.init(t,e),t._zod.pattern=Mb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),NS=b("$ZodAny",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),jS=b("$ZodUnknown",(t,e)=>{ce.init(t,e),t._zod.parse=r=>r}),LS=b("$ZodNever",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var FS=b("$ZodDate",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),r}});function eS(t,e,r){t.issues.length&&e.issues.push(...Qt(r,t.issues)),e.value[r]=t.value}var HS=b("$ZodArray",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let c=o[a],u=e.element._zod.run({value:c,issues:[]},n);u instanceof Promise?i.push(u.then(l=>eS(l,r,a))):eS(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});function Zc(t,e,r){t.issues.length&&e.issues.push(...Qt(r,t.issues)),e.value[r]=t.value}function tS(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Qt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var US=b("$ZodObject",(t,e)=>{ce.init(t,e);let r=js(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof ce))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=xp(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});me(t._zod,"propValues",()=>{let p=e.shape,m={};for(let f in p){let _=p[f]._zod;if(_.values){m[f]??(m[f]=new Set);for(let g of _.values)m[f].add(g)}}return m});let n=p=>{let m=new Wc(["shape","payload","ctx"]),f=r.value,_=x=>{let w=kn(x);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),y=0;for(let x of f.keys)g[x]=`key_${y++}`;m.write("const newResult = {}");for(let x of f.keys)if(f.optionalKeys.has(x)){let w=g[x];m.write(`const ${w} = ${_(x)};`);let T=kn(x);m.write(`
573
575
  if (${w}.issues.length) {
574
576
  if (input[${T}] === undefined) {
575
577
  if (${T} in input) {
@@ -591,44 +593,43 @@ Keep entries compact and merge related updates when a task iterates.
591
593
  `)}else{let w=g[x];m.write(`const ${w} = ${_(x)};`),m.write(`
592
594
  if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
593
595
  ...iss,
594
- path: iss.path ? [${wn(x)}, ...iss.path] : [${wn(x)}]
595
- })));`),m.write(`newResult[${wn(x)}] = ${w}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let S=m.compile();return(x,w)=>S(p,x,w)},o,i=Ro,a=!zc.jitless,u=a&&fp.value,l=e.catchall,d;t._zod.parse=(p,m)=>{d??(d=r.value);let f=p.value;if(!i(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let _=[];if(a&&u&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),p=o(p,m);else{p.value={};let w=d.shape;for(let T of d.keys){let v=w[T],P=v._zod.run({value:f[T],issues:[]},m),O=v._zod.optin==="optional"&&v._zod.optout==="optional";P instanceof Promise?_.push(P.then(J=>O?qb(J,p,T,f):Hc(J,p,T))):O?qb(P,p,T,f):Hc(P,p,T)}}if(!l)return _.length?Promise.all(_).then(()=>p):p;let g=[],y=d.keySet,S=l._zod,x=S.def.type;for(let w of Object.keys(f)){if(y.has(w))continue;if(x==="never"){g.push(w);continue}let T=S.run({value:f[w],issues:[]},m);T instanceof Promise?_.push(T.then(v=>Hc(v,p,w))):Hc(T,p,w)}return g.length&&p.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),_.length?Promise.all(_).then(()=>p):p}});function Wb(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>Dt(i,n,ut())))}),e}var Ap=b("$ZodUnion",(t,e)=>{ce.init(t,e),me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ls(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},n);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}return o?Promise.all(i).then(a=>Wb(a,r,t,n)):Wb(i,r,t,n)}}),IS=b("$ZodDiscriminatedUnion",(t,e)=>{Ap.init(t,e);let r=t._zod.parse;me(t._zod,"propValues",()=>{let o={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[c,u]of Object.entries(a)){o[c]||(o[c]=new Set);for(let l of u)o[c].add(l)}}return o});let n=Ns(()=>{let o=e.options,i=new Map;for(let a of o){let c=a._zod.propValues[e.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let u of c){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,a)}}return i});t._zod.parse=(o,i)=>{let a=o.value;if(!Ro(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let c=n.value.get(a?.[e.discriminator]);return c?c._zod.run(o,i):e.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),o)}}),$S=b("$ZodIntersection",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>Zb(r,u,l)):Zb(r,i,a)}});function Cp(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Po(t)&&Po(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=Cp(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=Cp(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Zb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),kn(t))return t;let n=Cp(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var zS=b("$ZodRecord",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Po(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let i=[];if(e.keyType._zod.values){let a=e.keyType._zod.values;r.value={};for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){let l=e.valueType._zod.run({value:o[u],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Xt(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...Xt(u,l.issues)),r.value[u]=l.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(l=>Dt(l,n,ut())),input:a,path:[a],inst:t}),r.value[c.value]=c.value;continue}let u=e.valueType._zod.run({value:o[a],issues:[]},n);u instanceof Promise?i.push(u.then(l=>{l.issues.length&&r.issues.push(...Xt(a,l.issues)),r.value[c.value]=l.value})):(u.issues.length&&r.issues.push(...Xt(a,u.issues)),r.value[c.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}});var OS=b("$ZodEnum",(t,e)=>{ce.init(t,e);let r=lp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>hp.has(typeof n)).map(n=>typeof n=="string"?Or(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),DS=b("$ZodLiteral",(t,e)=>{ce.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Or(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var MS=b("$ZodTransform",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new fr;return r.value=o,r}}),NS=b("$ZodOptional",(t,e)=>{ce.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ls(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),jS=b("$ZodNullable",(t,e)=>{ce.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ls(r.source)}|null)$`):void 0}),me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),LS=b("$ZodDefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Bb(i,e)):Bb(o,e)}});function Bb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var FS=b("$ZodPrefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),HS=b("$ZodNonOptional",(t,e)=>{ce.init(t,e),me(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Vb(i,t)):Vb(o,t)}});function Vb(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var US=b("$ZodCatch",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Dt(a,n,ut()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>Dt(i,n,ut()))},input:r.value}),r.issues=[]),r)}});var qS=b("$ZodPipe",(t,e)=>{ce.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(i=>Kb(i,e,n)):Kb(o,e,n)}});function Kb(t,e,r){return kn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var WS=b("$ZodReadonly",(t,e)=>{ce.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Gb):Gb(o)}});function Gb(t){return t.value=Object.freeze(t.value),t}var ZS=b("$ZodCustom",(t,e)=>{qe.init(t,e),ce.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>Jb(i,r,n,t));Jb(o,r,n,t)}});function Jb(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(yp(o))}}var $M=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},zM=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??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",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${$M(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Mc(n.values[0])}`:`Invalid option: expected one of ${Oc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Oc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function BS(){return{localeError:zM()}}var Ip=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function VS(){return new Ip}var Eo=VS();function KS(t,e){return new t({type:"string",...N(e)})}function GS(t,e){return new t({type:"string",coerce:!0,...N(e)})}function JS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function $p(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function YS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function XS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function QS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function ex(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function zp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function tx(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function rx(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function nx(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function ox(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function sx(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function ix(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function ax(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function cx(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function ux(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function lx(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function dx(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function px(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function mx(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function fx(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function hx(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function gx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function _x(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function yx(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function vx(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function bx(t,e){return new t({type:"number",checks:[],...N(e)})}function Sx(t,e){return new t({type:"number",coerce:!0,checks:[],...N(e)})}function xx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function wx(t,e){return new t({type:"boolean",...N(e)})}function kx(t,e){return new t({type:"boolean",coerce:!0,...N(e)})}function Rx(t,e){return new t({type:"bigint",coerce:!0,...N(e)})}function Px(t,e){return new t({type:"null",...N(e)})}function Ex(t){return new t({type:"any"})}function Cx(t){return new t({type:"unknown"})}function Tx(t,e){return new t({type:"never",...N(e)})}function Ax(t,e){return new t({type:"date",coerce:!0,...N(e)})}function Co(t,e){return new Pp({check:"less_than",...N(e),value:t,inclusive:!1})}function hr(t,e){return new Pp({check:"less_than",...N(e),value:t,inclusive:!0})}function To(t,e){return new Ep({check:"greater_than",...N(e),value:t,inclusive:!1})}function Mt(t,e){return new Ep({check:"greater_than",...N(e),value:t,inclusive:!0})}function qs(t,e){return new Cb({check:"multiple_of",...N(e),value:t})}function qc(t,e){return new Ab({check:"max_length",...N(e),maximum:t})}function Ao(t,e){return new Ib({check:"min_length",...N(e),minimum:t})}function Wc(t,e){return new $b({check:"length_equals",...N(e),length:t})}function Op(t,e){return new zb({check:"string_format",format:"regex",...N(e),pattern:t})}function Dp(t){return new Ob({check:"string_format",format:"lowercase",...N(t)})}function Mp(t){return new Db({check:"string_format",format:"uppercase",...N(t)})}function Np(t,e){return new Mb({check:"string_format",format:"includes",...N(e),includes:t})}function jp(t,e){return new Nb({check:"string_format",format:"starts_with",...N(e),prefix:t})}function Lp(t,e){return new jb({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Rn(t){return new Lb({check:"overwrite",tx:t})}function Fp(t){return Rn(e=>e.normalize(t))}function Hp(){return Rn(t=>t.trim())}function Up(){return Rn(t=>t.toLowerCase())}function qp(){return Rn(t=>t.toUpperCase())}function Ix(t,e,r){return new t({type:"array",element:e,...N(r)})}function $x(t,e,r){let n=N(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function zx(t,e,r){return new t({type:"custom",check:"custom",fn:e,...N(r)})}function $o(t){return!!t._zod}function Nt(t,e){return $o(t)?Hs(t,e):t.safeParse(e)}function Zc(t){if(!t)return;let e;if($o(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ox(t){if($o(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ws={};Xi(Ws,{ZodISODate:()=>Mx,ZodISODateTime:()=>Dx,ZodISODuration:()=>jx,ZodISOTime:()=>Nx,date:()=>Zp,datetime:()=>Wp,duration:()=>Vp,time:()=>Bp});var Dx=b("ZodISODateTime",(t,e)=>{cS.init(t,e),xe.init(t,e)});function Wp(t){return gx(Dx,t)}var Mx=b("ZodISODate",(t,e)=>{uS.init(t,e),xe.init(t,e)});function Zp(t){return _x(Mx,t)}var Nx=b("ZodISOTime",(t,e)=>{lS.init(t,e),xe.init(t,e)});function Bp(t){return yx(Nx,t)}var jx=b("ZodISODuration",(t,e)=>{dS.init(t,e),xe.init(t,e)});function Vp(t){return vx(jx,t)}var Fx=(t,e)=>{Nc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Sp(t,r)},flatten:{value:r=>bp(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},E8=b("ZodError",Fx),Zs=b("ZodError",Fx,{Parent:Error});var Hx=Gv(Zs),Ux=Jv(Zs),qx=xp(Zs),Wx=wp(Zs);var fe=b("ZodType",(t,e)=>(ce.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Hx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>qx(t,r,n),t.parseAsync=async(r,n)=>Ux(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wx(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(E1(r,n)),t.superRefine=r=>t.check(C1(r)),t.overwrite=r=>t.check(Rn(r)),t.optional=()=>ke(t),t.nullable=()=>Vx(t),t.nullish=()=>ke(Vx(t)),t.nonoptional=r=>b1(t,r),t.array=()=>C(t),t.or=r=>_e([t,r]),t.and=r=>Kc(t,r),t.transform=r=>Gp(t,nw(r)),t.default=r=>_1(t,r),t.prefault=r=>v1(t,r),t.catch=r=>x1(t,r),t.pipe=r=>Gp(t,r),t.readonly=()=>R1(t),t.describe=r=>{let n=t.clone();return Eo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Eo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Eo.get(t);let n=t.clone();return Eo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Kx=b("_ZodString",(t,e)=>{Uc.init(t,e),fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Op(...n)),t.includes=(...n)=>t.check(Np(...n)),t.startsWith=(...n)=>t.check(jp(...n)),t.endsWith=(...n)=>t.check(Lp(...n)),t.min=(...n)=>t.check(Ao(...n)),t.max=(...n)=>t.check(qc(...n)),t.length=(...n)=>t.check(Wc(...n)),t.nonempty=(...n)=>t.check(Ao(1,...n)),t.lowercase=n=>t.check(Dp(n)),t.uppercase=n=>t.check(Mp(n)),t.trim=()=>t.check(Hp()),t.normalize=(...n)=>t.check(Fp(...n)),t.toLowerCase=()=>t.check(Up()),t.toUpperCase=()=>t.check(qp())}),Jp=b("ZodString",(t,e)=>{Uc.init(t,e),Kx.init(t,e),t.email=r=>t.check(JS(HM,r)),t.url=r=>t.check(zp(Gx,r)),t.jwt=r=>t.check(hx(r1,r)),t.emoji=r=>t.check(tx(UM,r)),t.guid=r=>t.check($p(Zx,r)),t.uuid=r=>t.check(YS(Bc,r)),t.uuidv4=r=>t.check(XS(Bc,r)),t.uuidv6=r=>t.check(QS(Bc,r)),t.uuidv7=r=>t.check(ex(Bc,r)),t.nanoid=r=>t.check(rx(qM,r)),t.guid=r=>t.check($p(Zx,r)),t.cuid=r=>t.check(nx(WM,r)),t.cuid2=r=>t.check(ox(ZM,r)),t.ulid=r=>t.check(sx(BM,r)),t.base64=r=>t.check(px(QM,r)),t.base64url=r=>t.check(mx(e1,r)),t.xid=r=>t.check(ix(VM,r)),t.ksuid=r=>t.check(ax(KM,r)),t.ipv4=r=>t.check(cx(GM,r)),t.ipv6=r=>t.check(ux(JM,r)),t.cidrv4=r=>t.check(lx(YM,r)),t.cidrv6=r=>t.check(dx(XM,r)),t.e164=r=>t.check(fx(t1,r)),t.datetime=r=>t.check(Wp(r)),t.date=r=>t.check(Zp(r)),t.time=r=>t.check(Bp(r)),t.duration=r=>t.check(Vp(r))});function h(t){return KS(Jp,t)}var xe=b("ZodStringFormat",(t,e)=>{ge.init(t,e),Kx.init(t,e)}),HM=b("ZodEmail",(t,e)=>{Qb.init(t,e),xe.init(t,e)});var Zx=b("ZodGUID",(t,e)=>{Yb.init(t,e),xe.init(t,e)});var Bc=b("ZodUUID",(t,e)=>{Xb.init(t,e),xe.init(t,e)});var Gx=b("ZodURL",(t,e)=>{eS.init(t,e),xe.init(t,e)});function Jx(t){return zp(Gx,t)}var UM=b("ZodEmoji",(t,e)=>{tS.init(t,e),xe.init(t,e)});var qM=b("ZodNanoID",(t,e)=>{rS.init(t,e),xe.init(t,e)});var WM=b("ZodCUID",(t,e)=>{nS.init(t,e),xe.init(t,e)});var ZM=b("ZodCUID2",(t,e)=>{oS.init(t,e),xe.init(t,e)});var BM=b("ZodULID",(t,e)=>{sS.init(t,e),xe.init(t,e)});var VM=b("ZodXID",(t,e)=>{iS.init(t,e),xe.init(t,e)});var KM=b("ZodKSUID",(t,e)=>{aS.init(t,e),xe.init(t,e)});var GM=b("ZodIPv4",(t,e)=>{pS.init(t,e),xe.init(t,e)});var JM=b("ZodIPv6",(t,e)=>{mS.init(t,e),xe.init(t,e)});var YM=b("ZodCIDRv4",(t,e)=>{fS.init(t,e),xe.init(t,e)});var XM=b("ZodCIDRv6",(t,e)=>{hS.init(t,e),xe.init(t,e)});var QM=b("ZodBase64",(t,e)=>{_S.init(t,e),xe.init(t,e)});var e1=b("ZodBase64URL",(t,e)=>{yS.init(t,e),xe.init(t,e)});var t1=b("ZodE164",(t,e)=>{vS.init(t,e),xe.init(t,e)});var r1=b("ZodJWT",(t,e)=>{bS.init(t,e),xe.init(t,e)});var Vc=b("ZodNumber",(t,e)=>{Tp.init(t,e),fe.init(t,e),t.gt=(n,o)=>t.check(To(n,o)),t.gte=(n,o)=>t.check(Mt(n,o)),t.min=(n,o)=>t.check(Mt(n,o)),t.lt=(n,o)=>t.check(Co(n,o)),t.lte=(n,o)=>t.check(hr(n,o)),t.max=(n,o)=>t.check(hr(n,o)),t.int=n=>t.check(Bx(n)),t.safe=n=>t.check(Bx(n)),t.positive=n=>t.check(To(0,n)),t.nonnegative=n=>t.check(Mt(0,n)),t.negative=n=>t.check(Co(0,n)),t.nonpositive=n=>t.check(hr(0,n)),t.multipleOf=(n,o)=>t.check(qs(n,o)),t.step=(n,o)=>t.check(qs(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ne(t){return bx(Vc,t)}var n1=b("ZodNumberFormat",(t,e)=>{SS.init(t,e),Vc.init(t,e)});function Bx(t){return xx(n1,t)}var Yp=b("ZodBoolean",(t,e)=>{xS.init(t,e),fe.init(t,e)});function de(t){return wx(Yp,t)}var Yx=b("ZodBigInt",(t,e)=>{wS.init(t,e),fe.init(t,e),t.gte=(n,o)=>t.check(Mt(n,o)),t.min=(n,o)=>t.check(Mt(n,o)),t.gt=(n,o)=>t.check(To(n,o)),t.gte=(n,o)=>t.check(Mt(n,o)),t.min=(n,o)=>t.check(Mt(n,o)),t.lt=(n,o)=>t.check(Co(n,o)),t.lte=(n,o)=>t.check(hr(n,o)),t.max=(n,o)=>t.check(hr(n,o)),t.positive=n=>t.check(To(BigInt(0),n)),t.negative=n=>t.check(Co(BigInt(0),n)),t.nonpositive=n=>t.check(hr(BigInt(0),n)),t.nonnegative=n=>t.check(Mt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(qs(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var o1=b("ZodNull",(t,e)=>{kS.init(t,e),fe.init(t,e)});function Xx(t){return Px(o1,t)}var s1=b("ZodAny",(t,e)=>{RS.init(t,e),fe.init(t,e)});function Qx(){return Ex(s1)}var i1=b("ZodUnknown",(t,e)=>{PS.init(t,e),fe.init(t,e)});function we(){return Cx(i1)}var a1=b("ZodNever",(t,e)=>{ES.init(t,e),fe.init(t,e)});function c1(t){return Tx(a1,t)}var ew=b("ZodDate",(t,e)=>{CS.init(t,e),fe.init(t,e),t.min=(n,o)=>t.check(Mt(n,o)),t.max=(n,o)=>t.check(hr(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var u1=b("ZodArray",(t,e)=>{TS.init(t,e),fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ao(r,n)),t.nonempty=r=>t.check(Ao(1,r)),t.max=(r,n)=>t.check(qc(r,n)),t.length=(r,n)=>t.check(Wc(r,n)),t.unwrap=()=>t.element});function C(t,e){return Ix(u1,t,e)}var tw=b("ZodObject",(t,e)=>{AS.init(t,e),fe.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>tt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:we()}),t.loose=()=>t.clone({...t._zod.def,catchall:we()}),t.strict=()=>t.clone({...t._zod.def,catchall:c1()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>se.extend(t,r),t.merge=r=>se.merge(t,r),t.pick=r=>se.pick(t,r),t.omit=r=>se.omit(t,r),t.partial=(...r)=>se.partial(ow,t,r[0]),t.required=(...r)=>se.required(sw,t,r[0])});function A(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new tw(r)}function Ae(t,e){return new tw({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:we(),...se.normalizeParams(e)})}var rw=b("ZodUnion",(t,e)=>{Ap.init(t,e),fe.init(t,e),t.options=e.options});function _e(t,e){return new rw({type:"union",options:t,...se.normalizeParams(e)})}var l1=b("ZodDiscriminatedUnion",(t,e)=>{rw.init(t,e),IS.init(t,e)});function Xp(t,e,r){return new l1({type:"union",options:e,discriminator:t,...se.normalizeParams(r)})}var d1=b("ZodIntersection",(t,e)=>{$S.init(t,e),fe.init(t,e)});function Kc(t,e){return new d1({type:"intersection",left:t,right:e})}var p1=b("ZodRecord",(t,e)=>{zS.init(t,e),fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function he(t,e,r){return new p1({type:"record",keyType:t,valueType:e,...se.normalizeParams(r)})}var Kp=b("ZodEnum",(t,e)=>{OS.init(t,e),fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Kp({...e,checks:[],...se.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Kp({...e,checks:[],...se.normalizeParams(o),entries:i})}});function tt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Kp({type:"enum",entries:r,...se.normalizeParams(e)})}var m1=b("ZodLiteral",(t,e)=>{DS.init(t,e),fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function D(t,e){return new m1({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var f1=b("ZodTransform",(t,e)=>{MS.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(se.issue(i,r.value,e));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(se.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function nw(t){return new f1({type:"transform",transform:t})}var ow=b("ZodOptional",(t,e)=>{NS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ke(t){return new ow({type:"optional",innerType:t})}var h1=b("ZodNullable",(t,e)=>{jS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Vx(t){return new h1({type:"nullable",innerType:t})}var g1=b("ZodDefault",(t,e)=>{LS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function _1(t,e){return new g1({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var y1=b("ZodPrefault",(t,e)=>{FS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function v1(t,e){return new y1({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var sw=b("ZodNonOptional",(t,e)=>{HS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function b1(t,e){return new sw({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var S1=b("ZodCatch",(t,e)=>{US.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function x1(t,e){return new S1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var w1=b("ZodPipe",(t,e)=>{qS.init(t,e),fe.init(t,e),t.in=e.in,t.out=e.out});function Gp(t,e){return new w1({type:"pipe",in:t,out:e})}var k1=b("ZodReadonly",(t,e)=>{WS.init(t,e),fe.init(t,e)});function R1(t){return new k1({type:"readonly",innerType:t})}var iw=b("ZodCustom",(t,e)=>{ZS.init(t,e),fe.init(t,e)});function P1(t){let e=new qe({check:"custom"});return e._zod.check=t,e}function aw(t,e){return $x(iw,t??(()=>!0),e)}function E1(t,e={}){return zx(iw,t,e)}function C1(t){let e=P1(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(se.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(se.issue(o))}},t(r.value,r)));return e}function Qp(t,e){return Gp(nw(t),e)}var cw={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Gc={};Xi(Gc,{bigint:()=>$1,boolean:()=>I1,date:()=>z1,number:()=>A1,string:()=>T1});function T1(t){return GS(Jp,t)}function A1(t){return Sx(Vc,t)}function I1(t){return kx(Yp,t)}function $1(t){return Rx(Yx,t)}function z1(t){return Ax(ew,t)}ut(BS());var Oo="2025-11-25";var uw=[Oo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Dr="io.modelcontextprotocol/related-task",Yc="2.0",Ie=aw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),lw=_e([h(),ne().int()]),dw=h(),kY=Ae({ttl:ne().optional(),pollInterval:ne().optional()}),D1=A({ttl:ne().optional()}),M1=A({taskId:h()}),tm=Ae({progressToken:lw.optional(),[Dr]:M1.optional()}),lt=A({_meta:tm.optional()}),Bs=lt.extend({task:D1.optional()}),pw=t=>Bs.safeParse(t).success,Me=A({method:h(),params:lt.loose().optional()}),xt=A({_meta:tm.optional()}),wt=A({method:h(),params:xt.loose().optional()}),Ne=Ae({_meta:tm.optional()}),Xc=_e([h(),ne().int()]),mw=A({jsonrpc:D(Yc),id:Xc,...Me.shape}).strict(),Vs=t=>mw.safeParse(t).success,fw=A({jsonrpc:D(Yc),...wt.shape}).strict(),hw=t=>fw.safeParse(t).success,rm=A({jsonrpc:D(Yc),id:Xc,result:Ne}).strict(),Pn=t=>rm.safeParse(t).success;var U;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var nm=A({jsonrpc:D(Yc),id:Xc.optional(),error:A({code:ne().int(),message:h(),data:we().optional()})}).strict();var gw=t=>nm.safeParse(t).success;var Mr=_e([mw,fw,rm,nm]),RY=_e([rm,nm]),En=Ne.strict(),N1=xt.extend({requestId:Xc.optional(),reason:h().optional()}),Qc=wt.extend({method:D("notifications/cancelled"),params:N1}),j1=A({src:h(),mimeType:h().optional(),sizes:C(h()).optional(),theme:tt(["light","dark"]).optional()}),Ks=A({icons:C(j1).optional()}),zo=A({name:h(),title:h().optional()}),_w=zo.extend({...zo.shape,...Ks.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),L1=Kc(A({applyDefaults:de().optional()}),he(h(),we())),F1=Qp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Kc(A({form:L1.optional(),url:Ie.optional()}),he(h(),we()).optional())),H1=Ae({list:Ie.optional(),cancel:Ie.optional(),requests:Ae({sampling:Ae({createMessage:Ie.optional()}).optional(),elicitation:Ae({create:Ie.optional()}).optional()}).optional()}),U1=Ae({list:Ie.optional(),cancel:Ie.optional(),requests:Ae({tools:Ae({call:Ie.optional()}).optional()}).optional()}),q1=A({experimental:he(h(),Ie).optional(),sampling:A({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:F1.optional(),roots:A({listChanged:de().optional()}).optional(),tasks:H1.optional(),extensions:he(h(),Ie).optional()}),W1=lt.extend({protocolVersion:h(),capabilities:q1,clientInfo:_w}),Z1=Me.extend({method:D("initialize"),params:W1});var B1=A({experimental:he(h(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:A({listChanged:de().optional()}).optional(),resources:A({subscribe:de().optional(),listChanged:de().optional()}).optional(),tools:A({listChanged:de().optional()}).optional(),tasks:U1.optional(),extensions:he(h(),Ie).optional()}),om=Ne.extend({protocolVersion:h(),capabilities:B1,serverInfo:_w,instructions:h().optional()}),yw=wt.extend({method:D("notifications/initialized"),params:xt.optional()}),vw=t=>yw.safeParse(t).success,eu=Me.extend({method:D("ping"),params:lt.optional()}),V1=A({progress:ne(),total:ke(ne()),message:ke(h())}),K1=A({...xt.shape,...V1.shape,progressToken:lw}),tu=wt.extend({method:D("notifications/progress"),params:K1}),G1=lt.extend({cursor:dw.optional()}),Gs=Me.extend({params:G1.optional()}),Js=Ne.extend({nextCursor:dw.optional()}),J1=tt(["working","input_required","completed","failed","cancelled"]),Ys=A({taskId:h(),status:J1,ttl:_e([ne(),Xx()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ke(ne()),statusMessage:ke(h())}),Cn=Ne.extend({task:Ys}),Y1=xt.merge(Ys),Xs=wt.extend({method:D("notifications/tasks/status"),params:Y1}),ru=Me.extend({method:D("tasks/get"),params:lt.extend({taskId:h()})}),nu=Ne.merge(Ys),ou=Me.extend({method:D("tasks/result"),params:lt.extend({taskId:h()})}),PY=Ne.loose(),su=Gs.extend({method:D("tasks/list")}),iu=Js.extend({tasks:C(Ys)}),au=Me.extend({method:D("tasks/cancel"),params:lt.extend({taskId:h()})}),bw=Ne.merge(Ys),Sw=A({uri:h(),mimeType:ke(h()),_meta:he(h(),we()).optional()}),xw=Sw.extend({text:h()}),sm=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ww=Sw.extend({blob:sm}),Qs=tt(["user","assistant"]),Do=A({audience:C(Qs).optional(),priority:ne().min(0).max(1).optional(),lastModified:Ws.datetime({offset:!0}).optional()}),kw=A({...zo.shape,...Ks.shape,uri:h(),description:ke(h()),mimeType:ke(h()),size:ke(ne()),annotations:Do.optional(),_meta:ke(Ae({}))}),X1=A({...zo.shape,...Ks.shape,uriTemplate:h(),description:ke(h()),mimeType:ke(h()),annotations:Do.optional(),_meta:ke(Ae({}))}),Q1=Gs.extend({method:D("resources/list")}),im=Js.extend({resources:C(kw)}),eN=Gs.extend({method:D("resources/templates/list")}),am=Js.extend({resourceTemplates:C(X1)}),cm=lt.extend({uri:h()}),tN=cm,rN=Me.extend({method:D("resources/read"),params:tN}),um=Ne.extend({contents:C(_e([xw,ww]))}),lm=wt.extend({method:D("notifications/resources/list_changed"),params:xt.optional()}),nN=cm,oN=Me.extend({method:D("resources/subscribe"),params:nN}),sN=cm,iN=Me.extend({method:D("resources/unsubscribe"),params:sN}),aN=xt.extend({uri:h()}),cN=wt.extend({method:D("notifications/resources/updated"),params:aN}),uN=A({name:h(),description:ke(h()),required:ke(de())}),lN=A({...zo.shape,...Ks.shape,description:ke(h()),arguments:ke(C(uN)),_meta:ke(Ae({}))}),dN=Gs.extend({method:D("prompts/list")}),dm=Js.extend({prompts:C(lN)}),pN=lt.extend({name:h(),arguments:he(h(),h()).optional()}),mN=Me.extend({method:D("prompts/get"),params:pN}),pm=A({type:D("text"),text:h(),annotations:Do.optional(),_meta:he(h(),we()).optional()}),mm=A({type:D("image"),data:sm,mimeType:h(),annotations:Do.optional(),_meta:he(h(),we()).optional()}),fm=A({type:D("audio"),data:sm,mimeType:h(),annotations:Do.optional(),_meta:he(h(),we()).optional()}),fN=A({type:D("tool_use"),name:h(),id:h(),input:he(h(),we()),_meta:he(h(),we()).optional()}),hN=A({type:D("resource"),resource:_e([xw,ww]),annotations:Do.optional(),_meta:he(h(),we()).optional()}),gN=kw.extend({type:D("resource_link")}),hm=_e([pm,mm,fm,gN,hN]),_N=A({role:Qs,content:hm}),gm=Ne.extend({description:h().optional(),messages:C(_N)}),_m=wt.extend({method:D("notifications/prompts/list_changed"),params:xt.optional()}),yN=A({title:h().optional(),readOnlyHint:de().optional(),destructiveHint:de().optional(),idempotentHint:de().optional(),openWorldHint:de().optional()}),vN=A({taskSupport:tt(["required","optional","forbidden"]).optional()}),Rw=A({...zo.shape,...Ks.shape,description:h().optional(),inputSchema:A({type:D("object"),properties:he(h(),Ie).optional(),required:C(h()).optional()}).catchall(we()),outputSchema:A({type:D("object"),properties:he(h(),Ie).optional(),required:C(h()).optional()}).catchall(we()).optional(),annotations:yN.optional(),execution:vN.optional(),_meta:he(h(),we()).optional()}),bN=Gs.extend({method:D("tools/list")}),ym=Js.extend({tools:C(Rw)}),Mo=Ne.extend({content:C(hm).default([]),structuredContent:he(h(),we()).optional(),isError:de().optional()}),EY=Mo.or(Ne.extend({toolResult:we()})),SN=Bs.extend({name:h(),arguments:he(h(),we()).optional()}),xN=Me.extend({method:D("tools/call"),params:SN}),vm=wt.extend({method:D("notifications/tools/list_changed"),params:xt.optional()}),Pw=A({autoRefresh:de().default(!0),debounceMs:ne().int().nonnegative().default(300)}),Ew=tt(["debug","info","notice","warning","error","critical","alert","emergency"]),wN=lt.extend({level:Ew}),kN=Me.extend({method:D("logging/setLevel"),params:wN}),RN=xt.extend({level:Ew,logger:h().optional(),data:we()}),PN=wt.extend({method:D("notifications/message"),params:RN}),EN=A({name:h().optional()}),CN=A({hints:C(EN).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),TN=A({mode:tt(["auto","required","none"]).optional()}),AN=A({type:D("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:C(hm).default([]),structuredContent:A({}).loose().optional(),isError:de().optional(),_meta:he(h(),we()).optional()}),IN=Xp("type",[pm,mm,fm]),Jc=Xp("type",[pm,mm,fm,fN,AN]),$N=A({role:Qs,content:_e([Jc,C(Jc)]),_meta:he(h(),we()).optional()}),zN=Bs.extend({messages:C($N),modelPreferences:CN.optional(),systemPrompt:h().optional(),includeContext:tt(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:C(h()).optional(),metadata:Ie.optional(),tools:C(Rw).optional(),toolChoice:TN.optional()}),bm=Me.extend({method:D("sampling/createMessage"),params:zN}),Sm=Ne.extend({model:h(),stopReason:ke(tt(["endTurn","stopSequence","maxTokens"]).or(h())),role:Qs,content:IN}),xm=Ne.extend({model:h(),stopReason:ke(tt(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:Qs,content:_e([Jc,C(Jc)])}),ON=A({type:D("boolean"),title:h().optional(),description:h().optional(),default:de().optional()}),DN=A({type:D("string"),title:h().optional(),description:h().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:tt(["email","uri","date","date-time"]).optional(),default:h().optional()}),MN=A({type:tt(["number","integer"]),title:h().optional(),description:h().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),NN=A({type:D("string"),title:h().optional(),description:h().optional(),enum:C(h()),default:h().optional()}),jN=A({type:D("string"),title:h().optional(),description:h().optional(),oneOf:C(A({const:h(),title:h()})),default:h().optional()}),LN=A({type:D("string"),title:h().optional(),description:h().optional(),enum:C(h()),enumNames:C(h()).optional(),default:h().optional()}),FN=_e([NN,jN]),HN=A({type:D("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:A({type:D("string"),enum:C(h())}),default:C(h()).optional()}),UN=A({type:D("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:A({anyOf:C(A({const:h(),title:h()}))}),default:C(h()).optional()}),qN=_e([HN,UN]),WN=_e([LN,FN,qN]),ZN=_e([WN,ON,DN,MN]),BN=Bs.extend({mode:D("form").optional(),message:h(),requestedSchema:A({type:D("object"),properties:he(h(),ZN),required:C(h()).optional()})}),VN=Bs.extend({mode:D("url"),message:h(),elicitationId:h(),url:h().url()}),KN=_e([BN,VN]),wm=Me.extend({method:D("elicitation/create"),params:KN}),GN=xt.extend({elicitationId:h()}),JN=wt.extend({method:D("notifications/elicitation/complete"),params:GN}),km=Ne.extend({action:tt(["accept","decline","cancel"]),content:Qp(t=>t===null?void 0:t,he(h(),_e([h(),ne(),de(),C(h())])).optional())}),YN=A({type:D("ref/resource"),uri:h()});var XN=A({type:D("ref/prompt"),name:h()}),QN=lt.extend({ref:_e([XN,YN]),argument:A({name:h(),value:h()}),context:A({arguments:he(h(),h()).optional()}).optional()}),ej=Me.extend({method:D("completion/complete"),params:QN});var Rm=Ne.extend({completion:Ae({values:C(h()).max(100),total:ke(ne().int()),hasMore:ke(de())})}),tj=A({uri:h().startsWith("file://"),name:h().optional(),_meta:he(h(),we()).optional()}),rj=Me.extend({method:D("roots/list"),params:lt.optional()}),nj=Ne.extend({roots:C(tj)}),oj=wt.extend({method:D("notifications/roots/list_changed"),params:xt.optional()}),CY=_e([eu,Z1,ej,kN,mN,dN,Q1,eN,rN,oN,iN,xN,bN,ru,ou,su,au]),TY=_e([Qc,tu,yw,oj,Xs]),AY=_e([En,Sm,xm,km,nj,nu,iu,Cn]),IY=_e([eu,bm,wm,rj,ru,ou,su,au]),$Y=_e([Qc,tu,PN,cN,lm,vm,_m,Xs,JN]),zY=_e([En,om,Rm,gm,dm,im,am,um,Mo,ym,nu,iu,Cn]),j=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===U.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new em(o.elicitations,r)}return new t(e,r,n)}},em=class extends j{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Nr(t){return t==="completed"||t==="failed"||t==="cancelled"}var p7=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pm(t){let r=Zc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ox(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Em(t,e){let r=Nt(t,e);if(!r.success)throw r.error;return r.data}var lj=6e4,cu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Qc,r=>{this._oncancel(r)}),this.setNotificationHandler(tu,r=>{this._onprogress(r)}),this.setRequestHandler(eu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ru,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ou,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(c.type==="response"||c.type==="error"){let u=c.message,l=u.id,d=this._requestResolvers.get(l);if(d)if(this._requestResolvers.delete(l),c.type==="response")d(u);else{let p=u,m=new j(p.error.code,p.error.message,p.error.data);d(m)}else{let p=c.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new j(U.InvalidParams,`Task not found: ${i}`);if(!Nr(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Nr(a.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[Dr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(su,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new j(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(au,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nr(o.status))throw new j(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new j(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof j?o:new j(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),j.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),Pn(i)||gw(i)?this._onresponse(i):Vs(i)?this._onrequest(i,a):hw(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=j.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Dr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(d).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c=pw(e.params)?e.params.task:void 0,u=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(a.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(d,p)},sendRequest:async(d,p,m)=>{if(a.signal.aborted)throw new j(U.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let _=f.relatedTask?.taskId??i;return _&&u&&await u.updateTaskStatus(_,"input_required"),await this.request(d,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:u,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async d=>{if(a.signal.aborted)return;let p={result:d,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async d=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:U.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(u);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Pn(e))n(e);else{let a=new j(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Pn(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let c=a.task;typeof c.taskId=="string"&&(i=!0,this._taskProgressTokens.set(c.taskId,r))}}if(i||this._progressHandlers.delete(r),Pn(e))o(e);else{let a=j.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof j?a:new j(U.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Cn,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new j(U.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},Nr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new j(U.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new j(U.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let u=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,u)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof j?a:new j(U.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:c,relatedTask:u}=n??{};return new Promise((l,d)=>{let p=x=>{d(x)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(x){p(x);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),c&&(f.params={...f.params,task:c}),u&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Dr]:u}});let _=x=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(x)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let w=x instanceof j?x:new j(U.RequestTimeout,String(x));d(w)};this._responseHandlers.set(m,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return d(x);try{let w=Nt(r,x.result);w.success?l(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{_(n?.signal?.reason)});let g=n?.timeout??lj,y=()=>_(j.fromError(U.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=u?.taskId;if(S){let x=w=>{let T=this._responseHandlers.get(m);T?T(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,x),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),d(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(m),d(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},nu,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},iu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},bw,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let c={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Dr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[Dr]:r.relatedTask}}}),this._transport?.send(c,r).catch(u=>this._onerror(u))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Dr]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=Pm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=Em(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Pm(e);this._notificationHandlers.set(n,o=>{let i=Em(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Vs(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new j(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new j(U.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new j(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=Xs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Nr(c.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let c=await n.getTask(o,r);if(!c)throw new j(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nr(c.status))throw new j(U.InvalidParams,`Cannot update task "${o}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let u=await n.getTask(o,r);if(u){let l=Xs.parse({method:"notifications/tasks/status",params:u});await this.notification(l),Nr(u.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Cw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Tw(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];Cw(a)&&Cw(i)?r[o]={...a,...i}:r[o]=i}return r}var bP=Tt(fh(),1),SP=Tt(vP(),1);function mW(){let t=new bP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,SP.default)(t),t}var qu=class{constructor(e){this._ajv=e??mW()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Wu=class{constructor(e){this._client=e}async*callToolStream(e,r=Mo,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:e},r,i),c=o.getToolOutputValidator(e.name);for await(let u of a){if(u.type==="result"&&c){let l=u.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new j(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let d=c(l.structuredContent);if(!d.valid){yield{type:"error",error:new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof j){yield{type:"error",error:d};return}yield{type:"error",error:new j(U.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield u}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function xP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function wP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Zu(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Zu(i,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Zu(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Zu(r,e)}}function fW(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Bu=class extends cu{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new qu,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",vm,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",_m,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",lm,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Wu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Tw(this._capabilities,e)}setRequestHandler(e,r){let o=Zc(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if($o(o)){let c=o;i=c._zod?.def?.value??c.value}else{let c=o;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let c=async(u,l)=>{let d=Nt(wm,u);if(!d.success){let x=d.error instanceof Error?d.error.message:String(d.error);throw new j(U.InvalidParams,`Invalid elicitation request: ${x}`)}let{params:p}=d.data;p.mode=p.mode??"form";let{supportsFormMode:m,supportsUrlMode:f}=fW(this._capabilities.elicitation);if(p.mode==="form"&&!m)throw new j(U.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!f)throw new j(U.InvalidParams,"Client does not support URL-mode elicitation requests");let _=await Promise.resolve(r(u,l));if(p.task){let x=Nt(Cn,_);if(!x.success){let w=x.error instanceof Error?x.error.message:String(x.error);throw new j(U.InvalidParams,`Invalid task creation result: ${w}`)}return x.data}let g=Nt(km,_);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid elicitation result: ${x}`)}let y=g.data,S=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Zu(S,y.content)}catch{}return y};return super.setRequestHandler(e,c)}if(a==="sampling/createMessage"){let c=async(u,l)=>{let d=Nt(bm,u);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new j(U.InvalidParams,`Invalid sampling request: ${y}`)}let{params:p}=d.data,m=await Promise.resolve(r(u,l));if(p.task){let y=Nt(Cn,m);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new j(U.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let _=p.tools||p.toolChoice?xm:Sm,g=Nt(_,m);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(e,c)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Oo,capabilities:this._capabilities,clientInfo:this._clientInfo}},om,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!uw.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){xP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&wP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},En,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Rm,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},En,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},gm,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},dm,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},im,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},am,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},um,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},En,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},En,r)}async callTool(e,r=Mo,n){if(this.isToolTaskRequired(e.name))throw new j(U.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!o.structuredContent&&!o.isError)throw new j(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let a=i(o.structuredContent);if(!a.valid)throw new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof j?a:new j(U.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},ym,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let i=Pw.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:c}=i.data,{onChanged:u}=n,l=async()=>{if(!a){u(null,null);return}try{let p=await o();u(null,p)}catch(p){let m=p instanceof Error?p:new Error(String(p));u(m,null)}},d=()=>{if(c){let p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);let m=setTimeout(l,c);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var mE=Tt(dE(),1);import Ih from"node:process";import{PassThrough as UW}from"node:stream";var Ku=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
596
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),HW(r)}clear(){this._buffer=void 0}};function HW(t){return Mr.parse(JSON.parse(t))}function pE(t){return JSON.stringify(t)+`
597
- `}var qW=Ih.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function $h(){let t={};for(let e of qW){let r=Ih.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Gu=class{constructor(e){this._readBuffer=new Ku,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new UW)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,mE.default)(this._serverParams.command,this._serverParams.args??[],{env:{...$h(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Ih.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=pE(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function ns(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Ju(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...ns(e.headers),...ns(n.headers)}:e.headers};return t(r,o)}:t}var zh;zh=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function WW(t){return(await zh).getRandomValues(new Uint8Array(t))}async function ZW(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await WW(t-n.length);for(let i of o)i<r&&(n+=e[i%e.length])}return n}async function BW(t){return await ZW(t)}async function VW(t){let e=await(await zh).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Oh(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await BW(t),r=await VW(e);return{code_verifier:e,code_challenge:r}}var He=Jx().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:cw.custom,message:"URL must be parseable",fatal:!0}),ap}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),hE=Ae({resource:h().url(),authorization_servers:C(He).optional(),jwks_uri:h().url().optional(),scopes_supported:C(h()).optional(),bearer_methods_supported:C(h()).optional(),resource_signing_alg_values_supported:C(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:de().optional(),authorization_details_types_supported:C(h()).optional(),dpop_signing_alg_values_supported:C(h()).optional(),dpop_bound_access_tokens_required:de().optional()}),Dh=Ae({issuer:h(),authorization_endpoint:He,token_endpoint:He,registration_endpoint:He.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),service_documentation:He.optional(),revocation_endpoint:He.optional(),revocation_endpoint_auth_methods_supported:C(h()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(h()).optional(),introspection_endpoint:h().optional(),introspection_endpoint_auth_methods_supported:C(h()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(h()).optional(),code_challenge_methods_supported:C(h()).optional(),client_id_metadata_document_supported:de().optional()}),KW=Ae({issuer:h(),authorization_endpoint:He,token_endpoint:He,userinfo_endpoint:He.optional(),jwks_uri:He,registration_endpoint:He.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),acr_values_supported:C(h()).optional(),subject_types_supported:C(h()),id_token_signing_alg_values_supported:C(h()),id_token_encryption_alg_values_supported:C(h()).optional(),id_token_encryption_enc_values_supported:C(h()).optional(),userinfo_signing_alg_values_supported:C(h()).optional(),userinfo_encryption_alg_values_supported:C(h()).optional(),userinfo_encryption_enc_values_supported:C(h()).optional(),request_object_signing_alg_values_supported:C(h()).optional(),request_object_encryption_alg_values_supported:C(h()).optional(),request_object_encryption_enc_values_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),display_values_supported:C(h()).optional(),claim_types_supported:C(h()).optional(),claims_supported:C(h()).optional(),service_documentation:h().optional(),claims_locales_supported:C(h()).optional(),ui_locales_supported:C(h()).optional(),claims_parameter_supported:de().optional(),request_parameter_supported:de().optional(),request_uri_parameter_supported:de().optional(),require_request_uri_registration:de().optional(),op_policy_uri:He.optional(),op_tos_uri:He.optional(),client_id_metadata_document_supported:de().optional()}),gE=A({...KW.shape,...Dh.pick({code_challenge_methods_supported:!0}).shape}),_E=A({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:Gc.number().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),yE=A({error:h(),error_description:h().optional(),error_uri:h().optional()}),fE=He.optional().or(D("").transform(()=>{})),GW=A({redirect_uris:C(He),token_endpoint_auth_method:h().optional(),grant_types:C(h()).optional(),response_types:C(h()).optional(),client_name:h().optional(),client_uri:He.optional(),logo_uri:fE,scope:h().optional(),contacts:C(h()).optional(),tos_uri:fE,policy_uri:h().optional(),jwks_uri:He.optional(),jwks:Qx().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),JW=A({client_id:h(),client_secret:h().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),vE=GW.merge(JW),sre=A({error:h(),error_description:h().optional()}).strip(),ire=A({token:h(),token_type_hint:h().optional()}).strip();function bE(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function SE({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var Ce=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ai=class extends Ce{};Ai.errorCode="invalid_request";var Fn=class extends Ce{};Fn.errorCode="invalid_client";var Hn=class extends Ce{};Hn.errorCode="invalid_grant";var Un=class extends Ce{};Un.errorCode="unauthorized_client";var Ii=class extends Ce{};Ii.errorCode="unsupported_grant_type";var $i=class extends Ce{};$i.errorCode="invalid_scope";var zi=class extends Ce{};zi.errorCode="access_denied";var Sr=class extends Ce{};Sr.errorCode="server_error";var Oi=class extends Ce{};Oi.errorCode="temporarily_unavailable";var Di=class extends Ce{};Di.errorCode="unsupported_response_type";var Mi=class extends Ce{};Mi.errorCode="unsupported_token_type";var Ni=class extends Ce{};Ni.errorCode="invalid_token";var ji=class extends Ce{};ji.errorCode="method_not_allowed";var Li=class extends Ce{};Li.errorCode="too_many_requests";var qn=class extends Ce{};qn.errorCode="invalid_client_metadata";var Fi=class extends Ce{};Fi.errorCode="insufficient_scope";var Hi=class extends Ce{};Hi.errorCode="invalid_target";var xE={[Ai.errorCode]:Ai,[Fn.errorCode]:Fn,[Hn.errorCode]:Hn,[Un.errorCode]:Un,[Ii.errorCode]:Ii,[$i.errorCode]:$i,[zi.errorCode]:zi,[Sr.errorCode]:Sr,[Oi.errorCode]:Oi,[Di.errorCode]:Di,[Mi.errorCode]:Mi,[Ni.errorCode]:Ni,[ji.errorCode]:ji,[Li.errorCode]:Li,[qn.errorCode]:qn,[Fi.errorCode]:Fi,[Hi.errorCode]:Hi};var Xe=class extends Error{constructor(e){super(e??"Unauthorized")}};function YW(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Mh="code",Nh="S256";function XW(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&YW(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function QW(t,e,r,n){let{client_id:o,client_secret:i}=e;switch(t){case"client_secret_basic":e2(o,i,r);return;case"client_secret_post":t2(o,i,n);return;case"none":r2(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function e2(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function t2(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function r2(t,e){e.set("client_id",t)}async function kE(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=yE.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:a}=n,c=xE[o]||Sr;return new c(i||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Sr(o)}}async function xr(t,e){try{return await jh(t,e)}catch(r){if(r instanceof Fn||r instanceof Un)return await t.invalidateCredentials?.("all"),await jh(t,e);if(r instanceof Hn)return await t.invalidateCredentials?.("tokens"),await jh(t,e);throw r}}async function jh(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){let a=await t.discoveryState?.(),c,u,l,d=o;if(!d&&a?.resourceMetadataUrl&&(d=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(u=a.authorizationServerUrl,c=a.resourceMetadata,l=a.authorizationServerMetadata??await PE(u,{fetchFn:i}),!c)try{c=await RE(e,{resourceMetadataUrl:d},i)}catch{}(l!==a.authorizationServerMetadata||c!==a.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let w=await u2(e,{resourceMetadataUrl:d,fetchFn:i});u=w.authorizationServerUrl,l=w.authorizationServerMetadata,c=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let p=await o2(e,t,c),m=n||c?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=l?.client_id_metadata_document_supported===!0,T=t.clientMetadataUrl;if(T&&!n2(T))throw new qn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${T}`);if(w&&T)f={client_id:T},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await f2(u,{metadata:l,clientMetadata:t.clientMetadata,scope:m,fetchFn:i});await t.saveClientInformation(P),f=P}}let _=!t.redirectUrl;if(r!==void 0||_){let w=await m2(t,u,{metadata:l,resource:p,authorizationCode:r,fetchFn:i});return await t.saveTokens(w),"AUTHORIZED"}let g=await t.tokens();if(g?.refresh_token)try{let w=await p2(u,{metadata:l,clientInformation:f,refreshToken:g.refresh_token,resource:p,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Ce)||w instanceof Sr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:x}=await l2(u,{metadata:l,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:m,resource:p});return await t.saveCodeVerifier(x),await t.redirectToAuthorization(S),"REDIRECT"}function n2(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function o2(t,e,r){let n=bE(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!SE({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function os(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Lh(t,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let a=Lh(t,"scope")||void 0,c=Lh(t,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:c}}function Lh(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function RE(t,e,r=fetch){let n=await a2(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return hE.parse(await n.json())}async function Fh(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Fh(t,void 0,r):void 0;throw n}}function s2(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function wE(t,e,r=fetch){return await Fh(t,{"MCP-Protocol-Version":e},r)}function i2(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function a2(t,e,r,n){let o=new URL(t),i=n?.protocolVersion??Oo,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let u=s2(e,o.pathname);a=new URL(u,n?.metadataServerUrl??o),a.search=o.search}let c=await wE(a,i,r);if(!n?.metadataUrl&&i2(c,o.pathname)){let u=new URL(`/.well-known/${e}`,o);c=await wE(u,i,r)}return c}function c2(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function PE(t,{fetchFn:e=fetch,protocolVersion:r=Oo}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=c2(t);for(let{url:i,type:a}of o){let c=await Fh(i,n,e);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Dh.parse(await c.json()):gE.parse(await c.json())}}}async function u2(t,e){let r,n;try{r=await RE(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let o=await PE(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function l2(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:a}){let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Mh))throw new Error(`Incompatible auth server: does not support response type ${Mh}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Nh))throw new Error(`Incompatible auth server: does not support code challenge method ${Nh}`)}else c=new URL("/authorize",t);let u=await Oh(),l=u.code_verifier,d=u.code_challenge;return c.searchParams.set("response_type",Mh),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",d),c.searchParams.set("code_challenge_method",Nh),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:l}}function d2(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function EE(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:a}){let c=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),o)await o(u,r,c,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],p=XW(n,d);QW(p,n,u,r)}let l=await(a??fetch)(c,{method:"POST",headers:u,body:r});if(!l.ok)throw await kE(l);return _E.parse(await l.json())}async function p2(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:a}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),u=await EE(t,{metadata:e,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:a});return{refresh_token:n,...u}}async function m2(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){let a=t.clientMetadata.scope,c;if(t.prepareTokenRequest&&(c=await t.prepareTokenRequest(a)),!c){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await t.codeVerifier();c=d2(o,l,t.redirectUrl)}let u=await t.clientInformation();return EE(e,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:i})}async function f2(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let a=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!a.ok)throw await kE(a);return vE.parse(await a.json())}var Ui=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},CE=10,h2=13,Wn=32;function Hh(t){}function Yu(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Hh,onError:r=Hh,onRetry:n=Hh,onComment:o,maxBufferSize:i}=t,a=[],c=0,u=!0,l,d="",p=0,m,f=!1;function _(v){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(u&&(u=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),a.length===0){let J=y(v);J!==""&&(a.push(J),c=J.length),g();return}if(v.indexOf(`
598
- `)===-1&&v.indexOf("\r")===-1){a.push(v),c+=v.length,g();return}a.push(v);let P=a.join("");a.length=0,c=0;let O=y(P);O!==""&&(a.push(O),c=O.length),g()}function g(){i!==void 0&&(c+d.length<=i||(f=!0,a.length=0,c=0,l=void 0,d="",p=0,m=void 0,r(new Ui(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let P=0;if(v.indexOf("\r")===-1){let O=v.indexOf(`
596
+ path: iss.path ? [${kn(x)}, ...iss.path] : [${kn(x)}]
597
+ })));`),m.write(`newResult[${kn(x)}] = ${w}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let S=m.compile();return(x,w)=>S(p,x,w)},o,i=Po,a=!Nc.jitless,u=a&&bp.value,l=e.catchall,d;t._zod.parse=(p,m)=>{d??(d=r.value);let f=p.value;if(!i(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let _=[];if(a&&u&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),p=o(p,m);else{p.value={};let w=d.shape;for(let T of d.keys){let v=w[T],P=v._zod.run({value:f[T],issues:[]},m),O=v._zod.optin==="optional"&&v._zod.optout==="optional";P instanceof Promise?_.push(P.then(J=>O?tS(J,p,T,f):Zc(J,p,T))):O?tS(P,p,T,f):Zc(P,p,T)}}if(!l)return _.length?Promise.all(_).then(()=>p):p;let g=[],y=d.keySet,S=l._zod,x=S.def.type;for(let w of Object.keys(f)){if(y.has(w))continue;if(x==="never"){g.push(w);continue}let T=S.run({value:f[w],issues:[]},m);T instanceof Promise?_.push(T.then(v=>Zc(v,p,w))):Zc(T,p,w)}return g.length&&p.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),_.length?Promise.all(_).then(()=>p):p}});function rS(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>Mt(i,n,lt())))}),e}var Mp=b("$ZodUnion",(t,e)=>{ce.init(t,e),me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Fs(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,i=[];for(let a of e.options){let c=a._zod.run({value:r.value,issues:[]},n);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}return o?Promise.all(i).then(a=>rS(a,r,t,n)):rS(i,r,t,n)}}),qS=b("$ZodDiscriminatedUnion",(t,e)=>{Mp.init(t,e);let r=t._zod.parse;me(t._zod,"propValues",()=>{let o={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[c,u]of Object.entries(a)){o[c]||(o[c]=new Set);for(let l of u)o[c].add(l)}}return o});let n=js(()=>{let o=e.options,i=new Map;for(let a of o){let c=a._zod.propValues[e.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let u of c){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,a)}}return i});t._zod.parse=(o,i)=>{let a=o.value;if(!Po(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let c=n.value.get(a?.[e.discriminator]);return c?c._zod.run(o,i):e.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),o)}}),WS=b("$ZodIntersection",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>nS(r,u,l)):nS(r,i,a)}});function Op(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Eo(t)&&Eo(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=Op(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=Op(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function nS(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Rn(t))return t;let n=Op(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var ZS=b("$ZodRecord",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Eo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let i=[];if(e.keyType._zod.values){let a=e.keyType._zod.values;r.value={};for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){let l=e.valueType._zod.run({value:o[u],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Qt(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...Qt(u,l.issues)),r.value[u]=l.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(l=>Mt(l,n,lt())),input:a,path:[a],inst:t}),r.value[c.value]=c.value;continue}let u=e.valueType._zod.run({value:o[a],issues:[]},n);u instanceof Promise?i.push(u.then(l=>{l.issues.length&&r.issues.push(...Qt(a,l.issues)),r.value[c.value]=l.value})):(u.issues.length&&r.issues.push(...Qt(a,u.issues)),r.value[c.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}});var BS=b("$ZodEnum",(t,e)=>{ce.init(t,e);let r=gp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Sp.has(typeof n)).map(n=>typeof n=="string"?Dr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),VS=b("$ZodLiteral",(t,e)=>{ce.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Dr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var KS=b("$ZodTransform",(t,e)=>{ce.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new hr;return r.value=o,r}}),GS=b("$ZodOptional",(t,e)=>{ce.init(t,e),t._zod.optin="optional",t._zod.optout="optional",me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fs(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),JS=b("$ZodNullable",(t,e)=>{ce.init(t,e),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fs(r.source)}|null)$`):void 0}),me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),YS=b("$ZodDefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>oS(i,e)):oS(o,e)}});function oS(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var XS=b("$ZodPrefault",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),QS=b("$ZodNonOptional",(t,e)=>{ce.init(t,e),me(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>sS(i,t)):sS(o,t)}});function sS(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var ex=b("$ZodCatch",(t,e)=>{ce.init(t,e),t._zod.optin="optional",me(t._zod,"optout",()=>e.innerType._zod.optout),me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Mt(a,n,lt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>Mt(i,n,lt()))},input:r.value}),r.issues=[]),r)}});var tx=b("$ZodPipe",(t,e)=>{ce.init(t,e),me(t._zod,"values",()=>e.in._zod.values),me(t._zod,"optin",()=>e.in._zod.optin),me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(i=>iS(i,e,n)):iS(o,e,n)}});function iS(t,e,r){return Rn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var rx=b("$ZodReadonly",(t,e)=>{ce.init(t,e),me(t._zod,"propValues",()=>e.innerType._zod.propValues),me(t._zod,"values",()=>e.innerType._zod.values),me(t._zod,"optin",()=>e.innerType._zod.optin),me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(aS):aS(o)}});function aS(t){return t.value=Object.freeze(t.value),t}var nx=b("$ZodCustom",(t,e)=>{We.init(t,e),ce.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>cS(i,r,n,t));cS(o,r,n,t)}});function cS(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(kp(o))}}var pN=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},mN=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??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",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${pN(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Fc(n.values[0])}`:`Invalid option: expected one of ${jc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${jc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ox(){return{localeError:mN()}}var Np=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function sx(){return new Np}var Co=sx();function ix(t,e){return new t({type:"string",...N(e)})}function ax(t,e){return new t({type:"string",coerce:!0,...N(e)})}function cx(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...N(e)})}function jp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...N(e)})}function ux(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...N(e)})}function lx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(e)})}function dx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(e)})}function px(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(e)})}function Lp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...N(e)})}function mx(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...N(e)})}function fx(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(e)})}function hx(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...N(e)})}function gx(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(e)})}function _x(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...N(e)})}function yx(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...N(e)})}function vx(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(e)})}function bx(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(e)})}function Sx(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(e)})}function xx(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(e)})}function wx(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(e)})}function kx(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...N(e)})}function Rx(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...N(e)})}function Px(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...N(e)})}function Ex(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...N(e)})}function Cx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(e)})}function Tx(t,e){return new t({type:"string",format:"date",check:"string_format",...N(e)})}function Ax(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...N(e)})}function Ix(t,e){return new t({type:"string",format:"duration",check:"string_format",...N(e)})}function $x(t,e){return new t({type:"number",checks:[],...N(e)})}function zx(t,e){return new t({type:"number",coerce:!0,checks:[],...N(e)})}function Ox(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...N(e)})}function Dx(t,e){return new t({type:"boolean",...N(e)})}function Mx(t,e){return new t({type:"boolean",coerce:!0,...N(e)})}function Nx(t,e){return new t({type:"bigint",coerce:!0,...N(e)})}function jx(t,e){return new t({type:"null",...N(e)})}function Lx(t){return new t({type:"any"})}function Fx(t){return new t({type:"unknown"})}function Hx(t,e){return new t({type:"never",...N(e)})}function Ux(t,e){return new t({type:"date",coerce:!0,...N(e)})}function To(t,e){return new $p({check:"less_than",...N(e),value:t,inclusive:!1})}function gr(t,e){return new $p({check:"less_than",...N(e),value:t,inclusive:!0})}function Ao(t,e){return new zp({check:"greater_than",...N(e),value:t,inclusive:!1})}function Nt(t,e){return new zp({check:"greater_than",...N(e),value:t,inclusive:!0})}function Ws(t,e){return new Fb({check:"multiple_of",...N(e),value:t})}function Vc(t,e){return new Ub({check:"max_length",...N(e),maximum:t})}function Io(t,e){return new qb({check:"min_length",...N(e),minimum:t})}function Kc(t,e){return new Wb({check:"length_equals",...N(e),length:t})}function Fp(t,e){return new Zb({check:"string_format",format:"regex",...N(e),pattern:t})}function Hp(t){return new Bb({check:"string_format",format:"lowercase",...N(t)})}function Up(t){return new Vb({check:"string_format",format:"uppercase",...N(t)})}function qp(t,e){return new Kb({check:"string_format",format:"includes",...N(e),includes:t})}function Wp(t,e){return new Gb({check:"string_format",format:"starts_with",...N(e),prefix:t})}function Zp(t,e){return new Jb({check:"string_format",format:"ends_with",...N(e),suffix:t})}function Pn(t){return new Yb({check:"overwrite",tx:t})}function Bp(t){return Pn(e=>e.normalize(t))}function Vp(){return Pn(t=>t.trim())}function Kp(){return Pn(t=>t.toLowerCase())}function Gp(){return Pn(t=>t.toUpperCase())}function qx(t,e,r){return new t({type:"array",element:e,...N(r)})}function Wx(t,e,r){let n=N(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Zx(t,e,r){return new t({type:"custom",check:"custom",fn:e,...N(r)})}function zo(t){return!!t._zod}function jt(t,e){return zo(t)?Us(t,e):t.safeParse(e)}function Gc(t){if(!t)return;let e;if(zo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bx(t){if(zo(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Zs={};Qi(Zs,{ZodISODate:()=>Kx,ZodISODateTime:()=>Vx,ZodISODuration:()=>Jx,ZodISOTime:()=>Gx,date:()=>Yp,datetime:()=>Jp,duration:()=>Qp,time:()=>Xp});var Vx=b("ZodISODateTime",(t,e)=>{bS.init(t,e),xe.init(t,e)});function Jp(t){return Cx(Vx,t)}var Kx=b("ZodISODate",(t,e)=>{SS.init(t,e),xe.init(t,e)});function Yp(t){return Tx(Kx,t)}var Gx=b("ZodISOTime",(t,e)=>{xS.init(t,e),xe.init(t,e)});function Xp(t){return Ax(Gx,t)}var Jx=b("ZodISODuration",(t,e)=>{wS.init(t,e),xe.init(t,e)});function Qp(t){return Ix(Jx,t)}var Xx=(t,e)=>{Hc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ep(t,r)},flatten:{value:r=>Pp(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},aY=b("ZodError",Xx),Bs=b("ZodError",Xx,{Parent:Error});var Qx=ab(Bs),ew=cb(Bs),tw=Cp(Bs),rw=Tp(Bs);var fe=b("ZodType",(t,e)=>(ce.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Qx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>tw(t,r,n),t.parseAsync=async(r,n)=>ew(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>rw(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(a1(r,n)),t.superRefine=r=>t.check(c1(r)),t.overwrite=r=>t.check(Pn(r)),t.optional=()=>ke(t),t.nullable=()=>sw(t),t.nullish=()=>ke(sw(t)),t.nonoptional=r=>e1(t,r),t.array=()=>C(t),t.or=r=>ye([t,r]),t.and=r=>Xc(t,r),t.transform=r=>tm(t,hw(r)),t.default=r=>YN(t,r),t.prefault=r=>QN(t,r),t.catch=r=>r1(t,r),t.pipe=r=>tm(t,r),t.readonly=()=>s1(t),t.describe=r=>{let n=t.clone();return Co.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Co.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Co.get(t);let n=t.clone();return Co.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),iw=b("_ZodString",(t,e)=>{Bc.init(t,e),fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Fp(...n)),t.includes=(...n)=>t.check(qp(...n)),t.startsWith=(...n)=>t.check(Wp(...n)),t.endsWith=(...n)=>t.check(Zp(...n)),t.min=(...n)=>t.check(Io(...n)),t.max=(...n)=>t.check(Vc(...n)),t.length=(...n)=>t.check(Kc(...n)),t.nonempty=(...n)=>t.check(Io(1,...n)),t.lowercase=n=>t.check(Hp(n)),t.uppercase=n=>t.check(Up(n)),t.trim=()=>t.check(Vp()),t.normalize=(...n)=>t.check(Bp(...n)),t.toLowerCase=()=>t.check(Kp()),t.toUpperCase=()=>t.check(Gp())}),rm=b("ZodString",(t,e)=>{Bc.init(t,e),iw.init(t,e),t.email=r=>t.check(cx(SN,r)),t.url=r=>t.check(Lp(aw,r)),t.jwt=r=>t.check(Ex(MN,r)),t.emoji=r=>t.check(mx(xN,r)),t.guid=r=>t.check(jp(nw,r)),t.uuid=r=>t.check(ux(Jc,r)),t.uuidv4=r=>t.check(lx(Jc,r)),t.uuidv6=r=>t.check(dx(Jc,r)),t.uuidv7=r=>t.check(px(Jc,r)),t.nanoid=r=>t.check(fx(wN,r)),t.guid=r=>t.check(jp(nw,r)),t.cuid=r=>t.check(hx(kN,r)),t.cuid2=r=>t.check(gx(RN,r)),t.ulid=r=>t.check(_x(PN,r)),t.base64=r=>t.check(kx(zN,r)),t.base64url=r=>t.check(Rx(ON,r)),t.xid=r=>t.check(yx(EN,r)),t.ksuid=r=>t.check(vx(CN,r)),t.ipv4=r=>t.check(bx(TN,r)),t.ipv6=r=>t.check(Sx(AN,r)),t.cidrv4=r=>t.check(xx(IN,r)),t.cidrv6=r=>t.check(wx($N,r)),t.e164=r=>t.check(Px(DN,r)),t.datetime=r=>t.check(Jp(r)),t.date=r=>t.check(Yp(r)),t.time=r=>t.check(Xp(r)),t.duration=r=>t.check(Qp(r))});function h(t){return ix(rm,t)}var xe=b("ZodStringFormat",(t,e)=>{_e.init(t,e),iw.init(t,e)}),SN=b("ZodEmail",(t,e)=>{dS.init(t,e),xe.init(t,e)});var nw=b("ZodGUID",(t,e)=>{uS.init(t,e),xe.init(t,e)});var Jc=b("ZodUUID",(t,e)=>{lS.init(t,e),xe.init(t,e)});var aw=b("ZodURL",(t,e)=>{pS.init(t,e),xe.init(t,e)});function cw(t){return Lp(aw,t)}var xN=b("ZodEmoji",(t,e)=>{mS.init(t,e),xe.init(t,e)});var wN=b("ZodNanoID",(t,e)=>{fS.init(t,e),xe.init(t,e)});var kN=b("ZodCUID",(t,e)=>{hS.init(t,e),xe.init(t,e)});var RN=b("ZodCUID2",(t,e)=>{gS.init(t,e),xe.init(t,e)});var PN=b("ZodULID",(t,e)=>{_S.init(t,e),xe.init(t,e)});var EN=b("ZodXID",(t,e)=>{yS.init(t,e),xe.init(t,e)});var CN=b("ZodKSUID",(t,e)=>{vS.init(t,e),xe.init(t,e)});var TN=b("ZodIPv4",(t,e)=>{kS.init(t,e),xe.init(t,e)});var AN=b("ZodIPv6",(t,e)=>{RS.init(t,e),xe.init(t,e)});var IN=b("ZodCIDRv4",(t,e)=>{PS.init(t,e),xe.init(t,e)});var $N=b("ZodCIDRv6",(t,e)=>{ES.init(t,e),xe.init(t,e)});var zN=b("ZodBase64",(t,e)=>{TS.init(t,e),xe.init(t,e)});var ON=b("ZodBase64URL",(t,e)=>{AS.init(t,e),xe.init(t,e)});var DN=b("ZodE164",(t,e)=>{IS.init(t,e),xe.init(t,e)});var MN=b("ZodJWT",(t,e)=>{$S.init(t,e),xe.init(t,e)});var Yc=b("ZodNumber",(t,e)=>{Dp.init(t,e),fe.init(t,e),t.gt=(n,o)=>t.check(Ao(n,o)),t.gte=(n,o)=>t.check(Nt(n,o)),t.min=(n,o)=>t.check(Nt(n,o)),t.lt=(n,o)=>t.check(To(n,o)),t.lte=(n,o)=>t.check(gr(n,o)),t.max=(n,o)=>t.check(gr(n,o)),t.int=n=>t.check(ow(n)),t.safe=n=>t.check(ow(n)),t.positive=n=>t.check(Ao(0,n)),t.nonnegative=n=>t.check(Nt(0,n)),t.negative=n=>t.check(To(0,n)),t.nonpositive=n=>t.check(gr(0,n)),t.multipleOf=(n,o)=>t.check(Ws(n,o)),t.step=(n,o)=>t.check(Ws(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ne(t){return $x(Yc,t)}var NN=b("ZodNumberFormat",(t,e)=>{zS.init(t,e),Yc.init(t,e)});function ow(t){return Ox(NN,t)}var nm=b("ZodBoolean",(t,e)=>{OS.init(t,e),fe.init(t,e)});function de(t){return Dx(nm,t)}var uw=b("ZodBigInt",(t,e)=>{DS.init(t,e),fe.init(t,e),t.gte=(n,o)=>t.check(Nt(n,o)),t.min=(n,o)=>t.check(Nt(n,o)),t.gt=(n,o)=>t.check(Ao(n,o)),t.gte=(n,o)=>t.check(Nt(n,o)),t.min=(n,o)=>t.check(Nt(n,o)),t.lt=(n,o)=>t.check(To(n,o)),t.lte=(n,o)=>t.check(gr(n,o)),t.max=(n,o)=>t.check(gr(n,o)),t.positive=n=>t.check(Ao(BigInt(0),n)),t.negative=n=>t.check(To(BigInt(0),n)),t.nonpositive=n=>t.check(gr(BigInt(0),n)),t.nonnegative=n=>t.check(Nt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Ws(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var jN=b("ZodNull",(t,e)=>{MS.init(t,e),fe.init(t,e)});function lw(t){return jx(jN,t)}var LN=b("ZodAny",(t,e)=>{NS.init(t,e),fe.init(t,e)});function dw(){return Lx(LN)}var FN=b("ZodUnknown",(t,e)=>{jS.init(t,e),fe.init(t,e)});function we(){return Fx(FN)}var HN=b("ZodNever",(t,e)=>{LS.init(t,e),fe.init(t,e)});function UN(t){return Hx(HN,t)}var pw=b("ZodDate",(t,e)=>{FS.init(t,e),fe.init(t,e),t.min=(n,o)=>t.check(Nt(n,o)),t.max=(n,o)=>t.check(gr(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var qN=b("ZodArray",(t,e)=>{HS.init(t,e),fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Io(r,n)),t.nonempty=r=>t.check(Io(1,r)),t.max=(r,n)=>t.check(Vc(r,n)),t.length=(r,n)=>t.check(Kc(r,n)),t.unwrap=()=>t.element});function C(t,e){return qx(qN,t,e)}var mw=b("ZodObject",(t,e)=>{US.init(t,e),fe.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>rt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:we()}),t.loose=()=>t.clone({...t._zod.def,catchall:we()}),t.strict=()=>t.clone({...t._zod.def,catchall:UN()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>se.extend(t,r),t.merge=r=>se.merge(t,r),t.pick=r=>se.pick(t,r),t.omit=r=>se.omit(t,r),t.partial=(...r)=>se.partial(gw,t,r[0]),t.required=(...r)=>se.required(_w,t,r[0])});function A(t,e){let r={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new mw(r)}function Ae(t,e){return new mw({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:we(),...se.normalizeParams(e)})}var fw=b("ZodUnion",(t,e)=>{Mp.init(t,e),fe.init(t,e),t.options=e.options});function ye(t,e){return new fw({type:"union",options:t,...se.normalizeParams(e)})}var WN=b("ZodDiscriminatedUnion",(t,e)=>{fw.init(t,e),qS.init(t,e)});function om(t,e,r){return new WN({type:"union",options:e,discriminator:t,...se.normalizeParams(r)})}var ZN=b("ZodIntersection",(t,e)=>{WS.init(t,e),fe.init(t,e)});function Xc(t,e){return new ZN({type:"intersection",left:t,right:e})}var BN=b("ZodRecord",(t,e)=>{ZS.init(t,e),fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function he(t,e,r){return new BN({type:"record",keyType:t,valueType:e,...se.normalizeParams(r)})}var em=b("ZodEnum",(t,e)=>{BS.init(t,e),fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new em({...e,checks:[],...se.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new em({...e,checks:[],...se.normalizeParams(o),entries:i})}});function rt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new em({type:"enum",entries:r,...se.normalizeParams(e)})}var VN=b("ZodLiteral",(t,e)=>{VS.init(t,e),fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function D(t,e){return new VN({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var KN=b("ZodTransform",(t,e)=>{KS.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(se.issue(i,r.value,e));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(se.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function hw(t){return new KN({type:"transform",transform:t})}var gw=b("ZodOptional",(t,e)=>{GS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ke(t){return new gw({type:"optional",innerType:t})}var GN=b("ZodNullable",(t,e)=>{JS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sw(t){return new GN({type:"nullable",innerType:t})}var JN=b("ZodDefault",(t,e)=>{YS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function YN(t,e){return new JN({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var XN=b("ZodPrefault",(t,e)=>{XS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function QN(t,e){return new XN({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var _w=b("ZodNonOptional",(t,e)=>{QS.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function e1(t,e){return new _w({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var t1=b("ZodCatch",(t,e)=>{ex.init(t,e),fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function r1(t,e){return new t1({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var n1=b("ZodPipe",(t,e)=>{tx.init(t,e),fe.init(t,e),t.in=e.in,t.out=e.out});function tm(t,e){return new n1({type:"pipe",in:t,out:e})}var o1=b("ZodReadonly",(t,e)=>{rx.init(t,e),fe.init(t,e)});function s1(t){return new o1({type:"readonly",innerType:t})}var yw=b("ZodCustom",(t,e)=>{nx.init(t,e),fe.init(t,e)});function i1(t){let e=new We({check:"custom"});return e._zod.check=t,e}function vw(t,e){return Wx(yw,t??(()=>!0),e)}function a1(t,e={}){return Zx(yw,t,e)}function c1(t){let e=i1(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(se.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(se.issue(o))}},t(r.value,r)));return e}function sm(t,e){return tm(hw(t),e)}var bw={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Qc={};Qi(Qc,{bigint:()=>p1,boolean:()=>d1,date:()=>m1,number:()=>l1,string:()=>u1});function u1(t){return ax(rm,t)}function l1(t){return zx(Yc,t)}function d1(t){return Mx(nm,t)}function p1(t){return Nx(uw,t)}function m1(t){return Ux(pw,t)}lt(ox());var Do="2025-11-25";var Sw=[Do,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Mr="io.modelcontextprotocol/related-task",tu="2.0",Ie=vw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),xw=ye([h(),ne().int()]),ww=h(),o7=Ae({ttl:ne().optional(),pollInterval:ne().optional()}),h1=A({ttl:ne().optional()}),g1=A({taskId:h()}),am=Ae({progressToken:xw.optional(),[Mr]:g1.optional()}),dt=A({_meta:am.optional()}),Vs=dt.extend({task:h1.optional()}),kw=t=>Vs.safeParse(t).success,Me=A({method:h(),params:dt.loose().optional()}),wt=A({_meta:am.optional()}),kt=A({method:h(),params:wt.loose().optional()}),Ne=Ae({_meta:am.optional()}),ru=ye([h(),ne().int()]),Rw=A({jsonrpc:D(tu),id:ru,...Me.shape}).strict(),Ks=t=>Rw.safeParse(t).success,Pw=A({jsonrpc:D(tu),...kt.shape}).strict(),Ew=t=>Pw.safeParse(t).success,cm=A({jsonrpc:D(tu),id:ru,result:Ne}).strict(),En=t=>cm.safeParse(t).success;var U;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var um=A({jsonrpc:D(tu),id:ru.optional(),error:A({code:ne().int(),message:h(),data:we().optional()})}).strict();var Cw=t=>um.safeParse(t).success;var Nr=ye([Rw,Pw,cm,um]),s7=ye([cm,um]),Cn=Ne.strict(),_1=wt.extend({requestId:ru.optional(),reason:h().optional()}),nu=kt.extend({method:D("notifications/cancelled"),params:_1}),y1=A({src:h(),mimeType:h().optional(),sizes:C(h()).optional(),theme:rt(["light","dark"]).optional()}),Gs=A({icons:C(y1).optional()}),Oo=A({name:h(),title:h().optional()}),Tw=Oo.extend({...Oo.shape,...Gs.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),v1=Xc(A({applyDefaults:de().optional()}),he(h(),we())),b1=sm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Xc(A({form:v1.optional(),url:Ie.optional()}),he(h(),we()).optional())),S1=Ae({list:Ie.optional(),cancel:Ie.optional(),requests:Ae({sampling:Ae({createMessage:Ie.optional()}).optional(),elicitation:Ae({create:Ie.optional()}).optional()}).optional()}),x1=Ae({list:Ie.optional(),cancel:Ie.optional(),requests:Ae({tools:Ae({call:Ie.optional()}).optional()}).optional()}),w1=A({experimental:he(h(),Ie).optional(),sampling:A({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:b1.optional(),roots:A({listChanged:de().optional()}).optional(),tasks:S1.optional(),extensions:he(h(),Ie).optional()}),k1=dt.extend({protocolVersion:h(),capabilities:w1,clientInfo:Tw}),R1=Me.extend({method:D("initialize"),params:k1});var P1=A({experimental:he(h(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:A({listChanged:de().optional()}).optional(),resources:A({subscribe:de().optional(),listChanged:de().optional()}).optional(),tools:A({listChanged:de().optional()}).optional(),tasks:x1.optional(),extensions:he(h(),Ie).optional()}),lm=Ne.extend({protocolVersion:h(),capabilities:P1,serverInfo:Tw,instructions:h().optional()}),Aw=kt.extend({method:D("notifications/initialized"),params:wt.optional()}),Iw=t=>Aw.safeParse(t).success,ou=Me.extend({method:D("ping"),params:dt.optional()}),E1=A({progress:ne(),total:ke(ne()),message:ke(h())}),C1=A({...wt.shape,...E1.shape,progressToken:xw}),su=kt.extend({method:D("notifications/progress"),params:C1}),T1=dt.extend({cursor:ww.optional()}),Js=Me.extend({params:T1.optional()}),Ys=Ne.extend({nextCursor:ww.optional()}),A1=rt(["working","input_required","completed","failed","cancelled"]),Xs=A({taskId:h(),status:A1,ttl:ye([ne(),lw()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ke(ne()),statusMessage:ke(h())}),Tn=Ne.extend({task:Xs}),I1=wt.merge(Xs),Qs=kt.extend({method:D("notifications/tasks/status"),params:I1}),iu=Me.extend({method:D("tasks/get"),params:dt.extend({taskId:h()})}),au=Ne.merge(Xs),cu=Me.extend({method:D("tasks/result"),params:dt.extend({taskId:h()})}),i7=Ne.loose(),uu=Js.extend({method:D("tasks/list")}),lu=Ys.extend({tasks:C(Xs)}),du=Me.extend({method:D("tasks/cancel"),params:dt.extend({taskId:h()})}),$w=Ne.merge(Xs),zw=A({uri:h(),mimeType:ke(h()),_meta:he(h(),we()).optional()}),Ow=zw.extend({text:h()}),dm=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Dw=zw.extend({blob:dm}),ei=rt(["user","assistant"]),Mo=A({audience:C(ei).optional(),priority:ne().min(0).max(1).optional(),lastModified:Zs.datetime({offset:!0}).optional()}),Mw=A({...Oo.shape,...Gs.shape,uri:h(),description:ke(h()),mimeType:ke(h()),size:ke(ne()),annotations:Mo.optional(),_meta:ke(Ae({}))}),$1=A({...Oo.shape,...Gs.shape,uriTemplate:h(),description:ke(h()),mimeType:ke(h()),annotations:Mo.optional(),_meta:ke(Ae({}))}),z1=Js.extend({method:D("resources/list")}),pm=Ys.extend({resources:C(Mw)}),O1=Js.extend({method:D("resources/templates/list")}),mm=Ys.extend({resourceTemplates:C($1)}),fm=dt.extend({uri:h()}),D1=fm,M1=Me.extend({method:D("resources/read"),params:D1}),hm=Ne.extend({contents:C(ye([Ow,Dw]))}),gm=kt.extend({method:D("notifications/resources/list_changed"),params:wt.optional()}),N1=fm,j1=Me.extend({method:D("resources/subscribe"),params:N1}),L1=fm,F1=Me.extend({method:D("resources/unsubscribe"),params:L1}),H1=wt.extend({uri:h()}),U1=kt.extend({method:D("notifications/resources/updated"),params:H1}),q1=A({name:h(),description:ke(h()),required:ke(de())}),W1=A({...Oo.shape,...Gs.shape,description:ke(h()),arguments:ke(C(q1)),_meta:ke(Ae({}))}),Z1=Js.extend({method:D("prompts/list")}),_m=Ys.extend({prompts:C(W1)}),B1=dt.extend({name:h(),arguments:he(h(),h()).optional()}),V1=Me.extend({method:D("prompts/get"),params:B1}),ym=A({type:D("text"),text:h(),annotations:Mo.optional(),_meta:he(h(),we()).optional()}),vm=A({type:D("image"),data:dm,mimeType:h(),annotations:Mo.optional(),_meta:he(h(),we()).optional()}),bm=A({type:D("audio"),data:dm,mimeType:h(),annotations:Mo.optional(),_meta:he(h(),we()).optional()}),K1=A({type:D("tool_use"),name:h(),id:h(),input:he(h(),we()),_meta:he(h(),we()).optional()}),G1=A({type:D("resource"),resource:ye([Ow,Dw]),annotations:Mo.optional(),_meta:he(h(),we()).optional()}),J1=Mw.extend({type:D("resource_link")}),Sm=ye([ym,vm,bm,J1,G1]),Y1=A({role:ei,content:Sm}),xm=Ne.extend({description:h().optional(),messages:C(Y1)}),wm=kt.extend({method:D("notifications/prompts/list_changed"),params:wt.optional()}),X1=A({title:h().optional(),readOnlyHint:de().optional(),destructiveHint:de().optional(),idempotentHint:de().optional(),openWorldHint:de().optional()}),Q1=A({taskSupport:rt(["required","optional","forbidden"]).optional()}),Nw=A({...Oo.shape,...Gs.shape,description:h().optional(),inputSchema:A({type:D("object"),properties:he(h(),Ie).optional(),required:C(h()).optional()}).catchall(we()),outputSchema:A({type:D("object"),properties:he(h(),Ie).optional(),required:C(h()).optional()}).catchall(we()).optional(),annotations:X1.optional(),execution:Q1.optional(),_meta:he(h(),we()).optional()}),ej=Js.extend({method:D("tools/list")}),km=Ys.extend({tools:C(Nw)}),No=Ne.extend({content:C(Sm).default([]),structuredContent:he(h(),we()).optional(),isError:de().optional()}),a7=No.or(Ne.extend({toolResult:we()})),tj=Vs.extend({name:h(),arguments:he(h(),we()).optional()}),rj=Me.extend({method:D("tools/call"),params:tj}),Rm=kt.extend({method:D("notifications/tools/list_changed"),params:wt.optional()}),jw=A({autoRefresh:de().default(!0),debounceMs:ne().int().nonnegative().default(300)}),Lw=rt(["debug","info","notice","warning","error","critical","alert","emergency"]),nj=dt.extend({level:Lw}),oj=Me.extend({method:D("logging/setLevel"),params:nj}),sj=wt.extend({level:Lw,logger:h().optional(),data:we()}),ij=kt.extend({method:D("notifications/message"),params:sj}),aj=A({name:h().optional()}),cj=A({hints:C(aj).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),uj=A({mode:rt(["auto","required","none"]).optional()}),lj=A({type:D("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:C(Sm).default([]),structuredContent:A({}).loose().optional(),isError:de().optional(),_meta:he(h(),we()).optional()}),dj=om("type",[ym,vm,bm]),eu=om("type",[ym,vm,bm,K1,lj]),pj=A({role:ei,content:ye([eu,C(eu)]),_meta:he(h(),we()).optional()}),mj=Vs.extend({messages:C(pj),modelPreferences:cj.optional(),systemPrompt:h().optional(),includeContext:rt(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:C(h()).optional(),metadata:Ie.optional(),tools:C(Nw).optional(),toolChoice:uj.optional()}),Pm=Me.extend({method:D("sampling/createMessage"),params:mj}),Em=Ne.extend({model:h(),stopReason:ke(rt(["endTurn","stopSequence","maxTokens"]).or(h())),role:ei,content:dj}),Cm=Ne.extend({model:h(),stopReason:ke(rt(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:ei,content:ye([eu,C(eu)])}),fj=A({type:D("boolean"),title:h().optional(),description:h().optional(),default:de().optional()}),hj=A({type:D("string"),title:h().optional(),description:h().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:rt(["email","uri","date","date-time"]).optional(),default:h().optional()}),gj=A({type:rt(["number","integer"]),title:h().optional(),description:h().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),_j=A({type:D("string"),title:h().optional(),description:h().optional(),enum:C(h()),default:h().optional()}),yj=A({type:D("string"),title:h().optional(),description:h().optional(),oneOf:C(A({const:h(),title:h()})),default:h().optional()}),vj=A({type:D("string"),title:h().optional(),description:h().optional(),enum:C(h()),enumNames:C(h()).optional(),default:h().optional()}),bj=ye([_j,yj]),Sj=A({type:D("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:A({type:D("string"),enum:C(h())}),default:C(h()).optional()}),xj=A({type:D("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:A({anyOf:C(A({const:h(),title:h()}))}),default:C(h()).optional()}),wj=ye([Sj,xj]),kj=ye([vj,bj,wj]),Rj=ye([kj,fj,hj,gj]),Pj=Vs.extend({mode:D("form").optional(),message:h(),requestedSchema:A({type:D("object"),properties:he(h(),Rj),required:C(h()).optional()})}),Ej=Vs.extend({mode:D("url"),message:h(),elicitationId:h(),url:h().url()}),Cj=ye([Pj,Ej]),Tm=Me.extend({method:D("elicitation/create"),params:Cj}),Tj=wt.extend({elicitationId:h()}),Aj=kt.extend({method:D("notifications/elicitation/complete"),params:Tj}),Am=Ne.extend({action:rt(["accept","decline","cancel"]),content:sm(t=>t===null?void 0:t,he(h(),ye([h(),ne(),de(),C(h())])).optional())}),Ij=A({type:D("ref/resource"),uri:h()});var $j=A({type:D("ref/prompt"),name:h()}),zj=dt.extend({ref:ye([$j,Ij]),argument:A({name:h(),value:h()}),context:A({arguments:he(h(),h()).optional()}).optional()}),Oj=Me.extend({method:D("completion/complete"),params:zj});var Im=Ne.extend({completion:Ae({values:C(h()).max(100),total:ke(ne().int()),hasMore:ke(de())})}),Dj=A({uri:h().startsWith("file://"),name:h().optional(),_meta:he(h(),we()).optional()}),Mj=Me.extend({method:D("roots/list"),params:dt.optional()}),Nj=Ne.extend({roots:C(Dj)}),jj=kt.extend({method:D("notifications/roots/list_changed"),params:wt.optional()}),c7=ye([ou,R1,Oj,oj,V1,Z1,z1,O1,M1,j1,F1,rj,ej,iu,cu,uu,du]),u7=ye([nu,su,Aw,jj,Qs]),l7=ye([Cn,Em,Cm,Am,Nj,au,lu,Tn]),d7=ye([ou,Pm,Tm,Mj,iu,cu,uu,du]),p7=ye([nu,su,ij,U1,gm,Rm,wm,Qs,Aj]),m7=ye([Cn,lm,Im,xm,_m,pm,mm,hm,No,km,au,lu,Tn]),j=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===U.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new im(o.elicitations,r)}return new t(e,r,n)}},im=class extends j{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function jr(t){return t==="completed"||t==="failed"||t==="cancelled"}var B7=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $m(t){let r=Gc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Bx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zm(t,e){let r=jt(t,e);if(!r.success)throw r.error;return r.data}var Wj=6e4,pu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(nu,r=>{this._oncancel(r)}),this.setNotificationHandler(su,r=>{this._onprogress(r)}),this.setRequestHandler(ou,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(iu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(cu,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(c.type==="response"||c.type==="error"){let u=c.message,l=u.id,d=this._requestResolvers.get(l);if(d)if(this._requestResolvers.delete(l),c.type==="response")d(u);else{let p=u,m=new j(p.error.code,p.error.message,p.error.data);d(m)}else{let p=c.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new j(U.InvalidParams,`Task not found: ${i}`);if(!jr(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(jr(a.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[Mr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(uu,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new j(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(du,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(jr(o.status))throw new j(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new j(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof j?o:new j(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),j.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),En(i)||Cw(i)?this._onresponse(i):Ks(i)?this._onrequest(i,a):Ew(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=j.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Mr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(d).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c=kw(e.params)?e.params.task:void 0,u=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(a.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(d,p)},sendRequest:async(d,p,m)=>{if(a.signal.aborted)throw new j(U.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let _=f.relatedTask?.taskId??i;return _&&u&&await u.updateTaskStatus(_,"input_required"),await this.request(d,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:u,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async d=>{if(a.signal.aborted)return;let p={result:d,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async d=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:U.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&a&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(u);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),En(e))n(e);else{let a=new j(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(En(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let c=a.task;typeof c.taskId=="string"&&(i=!0,this._taskProgressTokens.set(c.taskId,r))}}if(i||this._progressHandlers.delete(r),En(e))o(e);else{let a=j.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof j?a:new j(U.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Tn,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new j(U.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},jr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new j(U.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new j(U.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let u=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,u)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof j?a:new j(U.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:c,relatedTask:u}=n??{};return new Promise((l,d)=>{let p=x=>{d(x)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(x){p(x);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),c&&(f.params={...f.params,task:c}),u&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Mr]:u}});let _=x=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(x)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));let w=x instanceof j?x:new j(U.RequestTimeout,String(x));d(w)};this._responseHandlers.set(m,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return d(x);try{let w=jt(r,x.result);w.success?l(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{_(n?.signal?.reason)});let g=n?.timeout??Wj,y=()=>_(j.fromError(U.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=u?.taskId;if(S){let x=w=>{let T=this._responseHandlers.get(m);T?T(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,x),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),d(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(m),d(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},au,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},lu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},$w,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let c={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Mr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[Mr]:r.relatedTask}}}),this._transport?.send(c,r).catch(u=>this._onerror(u))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Mr]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=$m(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=zm(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=$m(e);this._notificationHandlers.set(n,o=>{let i=zm(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ks(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new j(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new j(U.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new j(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new j(U.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=Qs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),jr(c.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let c=await n.getTask(o,r);if(!c)throw new j(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(jr(c.status))throw new j(U.InvalidParams,`Cannot update task "${o}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let u=await n.getTask(o,r);if(u){let l=Qs.parse({method:"notifications/tasks/status",params:u});await this.notification(l),jr(u.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Fw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Hw(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];Fw(a)&&Fw(i)?r[o]={...a,...i}:r[o]=i}return r}var $P=At(bh(),1),zP=At(IP(),1);function VW(){let t=new $P.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zP.default)(t),t}var Vu=class{constructor(e){this._ajv=e??VW()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ku=class{constructor(e){this._client=e}async*callToolStream(e,r=No,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:e},r,i),c=o.getToolOutputValidator(e.name);for await(let u of a){if(u.type==="result"&&c){let l=u.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new j(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let d=c(l.structuredContent);if(!d.valid){yield{type:"error",error:new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof j){yield{type:"error",error:d};return}yield{type:"error",error:new j(U.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield u}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function OP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function DP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Gu(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Gu(i,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Gu(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Gu(r,e)}}function KW(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Ju=class extends pu{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Vu,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Rm,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",wm,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",gm,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ku(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Hw(this._capabilities,e)}setRequestHandler(e,r){let o=Gc(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(zo(o)){let c=o;i=c._zod?.def?.value??c.value}else{let c=o;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let c=async(u,l)=>{let d=jt(Tm,u);if(!d.success){let x=d.error instanceof Error?d.error.message:String(d.error);throw new j(U.InvalidParams,`Invalid elicitation request: ${x}`)}let{params:p}=d.data;p.mode=p.mode??"form";let{supportsFormMode:m,supportsUrlMode:f}=KW(this._capabilities.elicitation);if(p.mode==="form"&&!m)throw new j(U.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!f)throw new j(U.InvalidParams,"Client does not support URL-mode elicitation requests");let _=await Promise.resolve(r(u,l));if(p.task){let x=jt(Tn,_);if(!x.success){let w=x.error instanceof Error?x.error.message:String(x.error);throw new j(U.InvalidParams,`Invalid task creation result: ${w}`)}return x.data}let g=jt(Am,_);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid elicitation result: ${x}`)}let y=g.data,S=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Gu(S,y.content)}catch{}return y};return super.setRequestHandler(e,c)}if(a==="sampling/createMessage"){let c=async(u,l)=>{let d=jt(Pm,u);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new j(U.InvalidParams,`Invalid sampling request: ${y}`)}let{params:p}=d.data,m=await Promise.resolve(r(u,l));if(p.task){let y=jt(Tn,m);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new j(U.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let _=p.tools||p.toolChoice?Cm:Em,g=jt(_,m);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new j(U.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(e,c)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Do,capabilities:this._capabilities,clientInfo:this._clientInfo}},lm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sw.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){OP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&DP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Cn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Im,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Cn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},xm,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},_m,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},pm,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},mm,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},hm,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Cn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Cn,r)}async callTool(e,r=No,n){if(this.isToolTaskRequired(e.name))throw new j(U.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!o.structuredContent&&!o.isError)throw new j(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let a=i(o.structuredContent);if(!a.valid)throw new j(U.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof j?a:new j(U.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},km,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let i=jw.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:c}=i.data,{onChanged:u}=n,l=async()=>{if(!a){u(null,null);return}try{let p=await o();u(null,p)}catch(p){let m=p instanceof Error?p:new Error(String(p));u(m,null)}},d=()=>{if(c){let p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);let m=setTimeout(l,c);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var RE=At(wE(),1);import Nh from"node:process";import{PassThrough as x2}from"node:stream";var Xu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
598
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),S2(r)}clear(){this._buffer=void 0}};function S2(t){return Nr.parse(JSON.parse(t))}function kE(t){return JSON.stringify(t)+`
599
+ `}var w2=Nh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function jh(){let t={};for(let e of w2){let r=Nh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Qu=class{constructor(e){this._readBuffer=new Xu,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new x2)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,RE.default)(this._serverParams.command,this._serverParams.args??[],{env:{...jh(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Nh.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=kE(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function os(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function el(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...os(e.headers),...os(n.headers)}:e.headers};return t(r,o)}:t}var Lh;Lh=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function k2(t){return(await Lh).getRandomValues(new Uint8Array(t))}async function R2(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await k2(t-n.length);for(let i of o)i<r&&(n+=e[i%e.length])}return n}async function P2(t){return await R2(t)}async function E2(t){let e=await(await Lh).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Fh(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await P2(t),r=await E2(e);return{code_verifier:e,code_challenge:r}}var He=cw().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:bw.custom,message:"URL must be parseable",fatal:!0}),mp}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),EE=Ae({resource:h().url(),authorization_servers:C(He).optional(),jwks_uri:h().url().optional(),scopes_supported:C(h()).optional(),bearer_methods_supported:C(h()).optional(),resource_signing_alg_values_supported:C(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:de().optional(),authorization_details_types_supported:C(h()).optional(),dpop_signing_alg_values_supported:C(h()).optional(),dpop_bound_access_tokens_required:de().optional()}),Hh=Ae({issuer:h(),authorization_endpoint:He,token_endpoint:He,registration_endpoint:He.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),service_documentation:He.optional(),revocation_endpoint:He.optional(),revocation_endpoint_auth_methods_supported:C(h()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(h()).optional(),introspection_endpoint:h().optional(),introspection_endpoint_auth_methods_supported:C(h()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(h()).optional(),code_challenge_methods_supported:C(h()).optional(),client_id_metadata_document_supported:de().optional()}),C2=Ae({issuer:h(),authorization_endpoint:He,token_endpoint:He,userinfo_endpoint:He.optional(),jwks_uri:He,registration_endpoint:He.optional(),scopes_supported:C(h()).optional(),response_types_supported:C(h()),response_modes_supported:C(h()).optional(),grant_types_supported:C(h()).optional(),acr_values_supported:C(h()).optional(),subject_types_supported:C(h()),id_token_signing_alg_values_supported:C(h()),id_token_encryption_alg_values_supported:C(h()).optional(),id_token_encryption_enc_values_supported:C(h()).optional(),userinfo_signing_alg_values_supported:C(h()).optional(),userinfo_encryption_alg_values_supported:C(h()).optional(),userinfo_encryption_enc_values_supported:C(h()).optional(),request_object_signing_alg_values_supported:C(h()).optional(),request_object_encryption_alg_values_supported:C(h()).optional(),request_object_encryption_enc_values_supported:C(h()).optional(),token_endpoint_auth_methods_supported:C(h()).optional(),token_endpoint_auth_signing_alg_values_supported:C(h()).optional(),display_values_supported:C(h()).optional(),claim_types_supported:C(h()).optional(),claims_supported:C(h()).optional(),service_documentation:h().optional(),claims_locales_supported:C(h()).optional(),ui_locales_supported:C(h()).optional(),claims_parameter_supported:de().optional(),request_parameter_supported:de().optional(),request_uri_parameter_supported:de().optional(),require_request_uri_registration:de().optional(),op_policy_uri:He.optional(),op_tos_uri:He.optional(),client_id_metadata_document_supported:de().optional()}),CE=A({...C2.shape,...Hh.pick({code_challenge_methods_supported:!0}).shape}),TE=A({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:Qc.number().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),AE=A({error:h(),error_description:h().optional(),error_uri:h().optional()}),PE=He.optional().or(D("").transform(()=>{})),T2=A({redirect_uris:C(He),token_endpoint_auth_method:h().optional(),grant_types:C(h()).optional(),response_types:C(h()).optional(),client_name:h().optional(),client_uri:He.optional(),logo_uri:PE,scope:h().optional(),contacts:C(h()).optional(),tos_uri:PE,policy_uri:h().optional(),jwks_uri:He.optional(),jwks:dw().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),A2=A({client_id:h(),client_secret:h().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),IE=T2.merge(A2),Lre=A({error:h(),error_description:h().optional()}).strip(),Fre=A({token:h(),token_type_hint:h().optional()}).strip();function $E(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function zE({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var Ce=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ii=class extends Ce{};Ii.errorCode="invalid_request";var Hn=class extends Ce{};Hn.errorCode="invalid_client";var Un=class extends Ce{};Un.errorCode="invalid_grant";var qn=class extends Ce{};qn.errorCode="unauthorized_client";var $i=class extends Ce{};$i.errorCode="unsupported_grant_type";var zi=class extends Ce{};zi.errorCode="invalid_scope";var Oi=class extends Ce{};Oi.errorCode="access_denied";var xr=class extends Ce{};xr.errorCode="server_error";var Di=class extends Ce{};Di.errorCode="temporarily_unavailable";var Mi=class extends Ce{};Mi.errorCode="unsupported_response_type";var Ni=class extends Ce{};Ni.errorCode="unsupported_token_type";var ji=class extends Ce{};ji.errorCode="invalid_token";var Li=class extends Ce{};Li.errorCode="method_not_allowed";var Fi=class extends Ce{};Fi.errorCode="too_many_requests";var Wn=class extends Ce{};Wn.errorCode="invalid_client_metadata";var Hi=class extends Ce{};Hi.errorCode="insufficient_scope";var Ui=class extends Ce{};Ui.errorCode="invalid_target";var OE={[Ii.errorCode]:Ii,[Hn.errorCode]:Hn,[Un.errorCode]:Un,[qn.errorCode]:qn,[$i.errorCode]:$i,[zi.errorCode]:zi,[Oi.errorCode]:Oi,[xr.errorCode]:xr,[Di.errorCode]:Di,[Mi.errorCode]:Mi,[Ni.errorCode]:Ni,[ji.errorCode]:ji,[Li.errorCode]:Li,[Fi.errorCode]:Fi,[Wn.errorCode]:Wn,[Hi.errorCode]:Hi,[Ui.errorCode]:Ui};var Qe=class extends Error{constructor(e){super(e??"Unauthorized")}};function I2(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Uh="code",qh="S256";function $2(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&I2(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function z2(t,e,r,n){let{client_id:o,client_secret:i}=e;switch(t){case"client_secret_basic":O2(o,i,r);return;case"client_secret_post":D2(o,i,n);return;case"none":M2(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function O2(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function D2(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function M2(t,e){e.set("client_id",t)}async function ME(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=AE.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:a}=n,c=OE[o]||xr;return new c(i||"",a)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new xr(o)}}async function wr(t,e){try{return await Wh(t,e)}catch(r){if(r instanceof Hn||r instanceof qn)return await t.invalidateCredentials?.("all"),await Wh(t,e);if(r instanceof Un)return await t.invalidateCredentials?.("tokens"),await Wh(t,e);throw r}}async function Wh(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){let a=await t.discoveryState?.(),c,u,l,d=o;if(!d&&a?.resourceMetadataUrl&&(d=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(u=a.authorizationServerUrl,c=a.resourceMetadata,l=a.authorizationServerMetadata??await jE(u,{fetchFn:i}),!c)try{c=await NE(e,{resourceMetadataUrl:d},i)}catch{}(l!==a.authorizationServerMetadata||c!==a.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let w=await q2(e,{resourceMetadataUrl:d,fetchFn:i});u=w.authorizationServerUrl,l=w.authorizationServerMetadata,c=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let p=await j2(e,t,c),m=n||c?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=l?.client_id_metadata_document_supported===!0,T=t.clientMetadataUrl;if(T&&!N2(T))throw new Wn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${T}`);if(w&&T)f={client_id:T},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await K2(u,{metadata:l,clientMetadata:t.clientMetadata,scope:m,fetchFn:i});await t.saveClientInformation(P),f=P}}let _=!t.redirectUrl;if(r!==void 0||_){let w=await V2(t,u,{metadata:l,resource:p,authorizationCode:r,fetchFn:i});return await t.saveTokens(w),"AUTHORIZED"}let g=await t.tokens();if(g?.refresh_token)try{let w=await B2(u,{metadata:l,clientInformation:f,refreshToken:g.refresh_token,resource:p,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Ce)||w instanceof xr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:x}=await W2(u,{metadata:l,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:m,resource:p});return await t.saveCodeVerifier(x),await t.redirectToAuthorization(S),"REDIRECT"}function N2(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function j2(t,e,r){let n=$E(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!zE({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function ss(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Zh(t,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let a=Zh(t,"scope")||void 0,c=Zh(t,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:c}}function Zh(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function NE(t,e,r=fetch){let n=await H2(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return EE.parse(await n.json())}async function Bh(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Bh(t,void 0,r):void 0;throw n}}function L2(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function DE(t,e,r=fetch){return await Bh(t,{"MCP-Protocol-Version":e},r)}function F2(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function H2(t,e,r,n){let o=new URL(t),i=n?.protocolVersion??Do,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let u=L2(e,o.pathname);a=new URL(u,n?.metadataServerUrl??o),a.search=o.search}let c=await DE(a,i,r);if(!n?.metadataUrl&&F2(c,o.pathname)){let u=new URL(`/.well-known/${e}`,o);c=await DE(u,i,r)}return c}function U2(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function jE(t,{fetchFn:e=fetch,protocolVersion:r=Do}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=U2(t);for(let{url:i,type:a}of o){let c=await Bh(i,n,e);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Hh.parse(await c.json()):CE.parse(await c.json())}}}async function q2(t,e){let r,n;try{r=await NE(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let o=await jE(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function W2(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:a}){let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Uh))throw new Error(`Incompatible auth server: does not support response type ${Uh}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(qh))throw new Error(`Incompatible auth server: does not support code challenge method ${qh}`)}else c=new URL("/authorize",t);let u=await Fh(),l=u.code_verifier,d=u.code_challenge;return c.searchParams.set("response_type",Uh),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",d),c.searchParams.set("code_challenge_method",qh),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:l}}function Z2(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function LE(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:a}){let c=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),o)await o(u,r,c,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],p=$2(n,d);z2(p,n,u,r)}let l=await(a??fetch)(c,{method:"POST",headers:u,body:r});if(!l.ok)throw await ME(l);return TE.parse(await l.json())}async function B2(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:a}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),u=await LE(t,{metadata:e,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:a});return{refresh_token:n,...u}}async function V2(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){let a=t.clientMetadata.scope,c;if(t.prepareTokenRequest&&(c=await t.prepareTokenRequest(a)),!c){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await t.codeVerifier();c=Z2(o,l,t.redirectUrl)}let u=await t.clientInformation();return LE(e,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:i})}async function K2(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let a=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!a.ok)throw await ME(a);return IE.parse(await a.json())}var qi=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},FE=10,G2=13,Zn=32;function Vh(t){}function tl(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Vh,onError:r=Vh,onRetry:n=Vh,onComment:o,maxBufferSize:i}=t,a=[],c=0,u=!0,l,d="",p=0,m,f=!1;function _(v){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(u&&(u=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),a.length===0){let J=y(v);J!==""&&(a.push(J),c=J.length),g();return}if(v.indexOf(`
600
+ `)===-1&&v.indexOf("\r")===-1){a.push(v),c+=v.length,g();return}a.push(v);let P=a.join("");a.length=0,c=0;let O=y(P);O!==""&&(a.push(O),c=O.length),g()}function g(){i!==void 0&&(c+d.length<=i||(f=!0,a.length=0,c=0,l=void 0,d="",p=0,m=void 0,r(new qi(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function y(v){let P=0;if(v.indexOf("\r")===-1){let O=v.indexOf(`
599
601
  `,P);for(;O!==-1;){if(P===O){p>0&&e({id:l,event:m,data:d}),l=void 0,d="",p=0,m=void 0,P=O+1,O=v.indexOf(`
600
- `,P);continue}let J=v.charCodeAt(P);if(TE(v,P,J)){let F=v.charCodeAt(P+5)===Wn?P+6:P+5,ie=v.slice(F,O);if(p===0&&v.charCodeAt(O+1)===CE){e({id:l,event:m,data:ie}),l=void 0,d="",m=void 0,P=O+2,O=v.indexOf(`
602
+ `,P);continue}let J=v.charCodeAt(P);if(HE(v,P,J)){let F=v.charCodeAt(P+5)===Zn?P+6:P+5,ie=v.slice(F,O);if(p===0&&v.charCodeAt(O+1)===FE){e({id:l,event:m,data:ie}),l=void 0,d="",m=void 0,P=O+2,O=v.indexOf(`
601
603
  `,P);continue}d=p===0?ie:`${d}
602
- ${ie}`,p++}else AE(v,P,J)?m=v.slice(v.charCodeAt(P+6)===Wn?P+7:P+6,O)||void 0:S(v,P,O);P=O+1,O=v.indexOf(`
604
+ ${ie}`,p++}else UE(v,P,J)?m=v.slice(v.charCodeAt(P+6)===Zn?P+7:P+6,O)||void 0:S(v,P,O);P=O+1,O=v.indexOf(`
603
605
  `,P)}return v.slice(P)}for(;P<v.length;){let O=v.indexOf("\r",P),J=v.indexOf(`
604
- `,P),F=-1;if(O!==-1&&J!==-1?F=O<J?O:J:O!==-1?O===v.length-1?F=-1:F=O:J!==-1&&(F=J),F===-1)break;S(v,P,F),P=F+1,v.charCodeAt(P-1)===h2&&v.charCodeAt(P)===CE&&P++}return v.slice(P)}function S(v,P,O){if(P===O){w();return}let J=v.charCodeAt(P);if(TE(v,P,J)){let Ct=v.charCodeAt(P+5)===Wn?P+6:P+5,E=v.slice(Ct,O);d=p===0?E:`${d}
605
- ${E}`,p++;return}if(AE(v,P,J)){m=v.slice(v.charCodeAt(P+6)===Wn?P+7:P+6,O)||void 0;return}if(J===105&&v.charCodeAt(P+1)===100&&v.charCodeAt(P+2)===58){let Ct=v.slice(v.charCodeAt(P+3)===Wn?P+4:P+3,O);l=Ct.includes("\0")?void 0:Ct;return}if(J===58){if(o){let Ct=v.slice(P,O);o(Ct.slice(v.charCodeAt(P+1)===Wn?2:1))}return}let F=v.slice(P,O),ie=F.indexOf(":");if(ie===-1){x(F,"",F);return}let pt=F.slice(0,ie),mt=F.charCodeAt(ie+1)===Wn?2:1,Kr=F.slice(ie+mt);x(pt,Kr,F)}function x(v,P,O){switch(v){case"event":m=P||void 0;break;case"data":d=p===0?P:`${d}
606
- ${P}`,p++;break;case"id":l=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new Ui(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:O}));break;default:r(new Ui(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:P,line:O}));break}}function w(){p>0&&e({id:l,event:m,data:d}),l=void 0,d="",p=0,m=void 0}function T(v={}){if(v.consume&&a.length>0){let P=a.join("");S(P,0,P.length)}u=!0,l=void 0,d="",p=0,m=void 0,a.length=0,c=0,f=!1}return{feed:_,reset:T}}function TE(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function AE(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var Xu=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=Yu({onEvent:c=>{a.enqueue(c)},onError(c){typeof e=="function"&&e(c),(e==="terminate"||c.type==="max-buffer-size-exceeded")&&a.error(c)},onRetry:r,onComment:n,maxBufferSize:o})},transform(a){i.feed(a)}})}};var g2={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Br=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Qu=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ju(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??g2}async _authThenStart(){if(!this._authProvider)throw new Xe("No auth provider");let e;try{e=await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Xe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ns(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Br(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:i}=r,a,c=!1,u=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new Xu({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:_}=await d.read();if(_)break;if(f.id&&(a=f.id,c=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let g=Mr.parse(JSON.parse(f.data));Pn(g)&&(u=!0,i!==void 0&&(g.id=i)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Xe("No auth provider");if(await xr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Vs(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let a={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,a),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){let m=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Br(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:f,scope:_}=os(c);if(this._resourceMetadataUrl=f,this._scope=_,await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:f,scope:_,error:g}=os(c);if(g==="insufficient_scope"){let y=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Br(403,"Server returned 403 after trying upscoping");if(_&&(this._scope=_),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Xe;return this.send(e)}}throw new Br(c.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),vw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let d=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,p=c.headers.get("content-type");if(d)if(p?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:o},!1);else if(p?.includes("application/json")){let m=await c.json(),f=Array.isArray(m)?m.map(_=>Mr.parse(_)):[Mr.parse(m)];for(let _ of f)this.onmessage?.(_)}else throw await c.body?.cancel(),new Br(-1,`Unexpected content type: ${p}`);else await c.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Br(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var tl=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(IE(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(IE(this),r)}};function _2(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Uh(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Uh).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Uh(t.cause)}`:t.message:`${t}`}function IE(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var zE=t=>{throw TypeError(t)},Jh=(t,e,r)=>e.has(t)||zE("Cannot "+r),X=(t,e,r)=>(Jh(t,e,"read from private field"),r?r.call(t):e.get(t)),$e=(t,e,r)=>e.has(t)?zE("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Re=(t,e,r,n)=>(Jh(t,e,"write to private field"),e.set(t,r),r),wr=(t,e,r)=>(Jh(t,e,"access private method"),r),it,Zn,ss,el,rl,Zi,cs,Bi,Vr,is,us,as,qi,qt,qh,Wh,Zh,$E,Bh,Vh,Wi,Kh,Gh,Bn=class extends EventTarget{constructor(e,r){var n,o;super(),$e(this,qt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,$e(this,it),$e(this,Zn),$e(this,ss),$e(this,el),$e(this,rl),$e(this,Zi),$e(this,cs),$e(this,Bi,null),$e(this,Vr),$e(this,is),$e(this,us,null),$e(this,as,null),$e(this,qi,null),$e(this,Wh,async i=>{var a;X(this,is).reset();let{body:c,redirected:u,status:l,headers:d}=i;if(l===204){wr(this,qt,Wi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Re(this,ss,new URL(i.url)):Re(this,ss,void 0),l!==200){wr(this,qt,Wi).call(this,`Non-200 status code (${l})`,l);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){wr(this,qt,Wi).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(X(this,it)===this.CLOSED)return;Re(this,it,this.OPEN);let p=new Event("open");if((a=X(this,qi))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){wr(this,qt,Wi).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}let m=new TextDecoder,f=c.getReader(),_=!0;do{let{done:g,value:y}=await f.read();y&&X(this,is).feed(m.decode(y,{stream:!g})),g&&(_=!1,X(this,is).reset(),wr(this,qt,Kh).call(this))}while(_)}),$e(this,Zh,i=>{Re(this,Vr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&wr(this,qt,Kh).call(this,Uh(i))}),$e(this,Bh,i=>{typeof i.id=="string"&&Re(this,Bi,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:X(this,ss)?X(this,ss).origin:X(this,Zn).origin,lastEventId:i.id||""});X(this,as)&&(!i.event||i.event==="message")&&X(this,as).call(this,a),this.dispatchEvent(a)}),$e(this,Vh,i=>{Re(this,Zi,i)}),$e(this,Gh,()=>{Re(this,cs,void 0),X(this,it)===this.CONNECTING&&wr(this,qt,qh).call(this)});try{if(e instanceof URL)Re(this,Zn,e);else if(typeof e=="string")Re(this,Zn,new URL(e,y2()));else throw new Error("Invalid URL")}catch{throw _2("An invalid or illegal string was specified")}Re(this,is,Yu({onEvent:X(this,Bh),onRetry:X(this,Vh)})),Re(this,it,this.CONNECTING),Re(this,Zi,3e3),Re(this,rl,(n=r?.fetch)!=null?n:globalThis.fetch),Re(this,el,(o=r?.withCredentials)!=null?o:!1),wr(this,qt,qh).call(this)}get readyState(){return X(this,it)}get url(){return X(this,Zn).href}get withCredentials(){return X(this,el)}get onerror(){return X(this,us)}set onerror(e){Re(this,us,e)}get onmessage(){return X(this,as)}set onmessage(e){Re(this,as,e)}get onopen(){return X(this,qi)}set onopen(e){Re(this,qi,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){X(this,cs)&&clearTimeout(X(this,cs)),X(this,it)!==this.CLOSED&&(X(this,Vr)&&X(this,Vr).abort(),Re(this,it,this.CLOSED),Re(this,Vr,void 0))}};it=new WeakMap,Zn=new WeakMap,ss=new WeakMap,el=new WeakMap,rl=new WeakMap,Zi=new WeakMap,cs=new WeakMap,Bi=new WeakMap,Vr=new WeakMap,is=new WeakMap,us=new WeakMap,as=new WeakMap,qi=new WeakMap,qt=new WeakSet,qh=function(){Re(this,it,this.CONNECTING),Re(this,Vr,new AbortController),X(this,rl)(X(this,Zn),wr(this,qt,$E).call(this)).then(X(this,Wh)).catch(X(this,Zh))},Wh=new WeakMap,Zh=new WeakMap,$E=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...X(this,Bi)?{"Last-Event-ID":X(this,Bi)}:void 0},cache:"no-store",signal:(t=X(this,Vr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Bh=new WeakMap,Vh=new WeakMap,Wi=function(t,e){var r;X(this,it)!==this.CLOSED&&Re(this,it,this.CLOSED);let n=new tl("error",{code:e,message:t});(r=X(this,us))==null||r.call(this,n),this.dispatchEvent(n)},Kh=function(t,e){var r;if(X(this,it)===this.CLOSED)return;Re(this,it,this.CONNECTING);let n=new tl("error",{code:e,message:t});(r=X(this,us))==null||r.call(this,n),this.dispatchEvent(n),Re(this,cs,setTimeout(X(this,Gh),X(this,Zi)))},Gh=new WeakMap,Bn.CONNECTING=0,Bn.OPEN=1,Bn.CLOSED=2;function y2(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var Yh=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},nl=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ju(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Xe("No auth provider");let e;try{e=await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Xe;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ns(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Bn(this._url.href,{...this._eventSourceInit,fetch:async(o,i)=>{let a=await this._commonHeaders();a.set("Accept","text/event-stream");let c=await e(o,{...i,headers:a});if(c.status===401&&c.headers.has("www-authenticate")){let{resourceMetadataUrl:u,scope:l}=os(c);this._resourceMetadataUrl=u,this._scope=l}return c}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let i=new Yh(o.code,o.message,o);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let i=o;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{let i=o,a;try{a=Mr.parse(JSON.parse(i.data))}catch(c){this.onerror?.(c);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Xe("No auth provider");if(await xr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xe("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let i=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:a,scope:c}=os(o);if(this._resourceMetadataUrl=a,this._scope=c,await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var Xh=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="McpProbeError"}code},OE=1e4,DE=1e4;async function LE(t,e={}){let r=await S2(t,e);if(r===null)return{ok:!1,phase:"not_found",message:`no MCP config; server "${t.server_name}" not found`};let n=io(r);if(!n.ok)return{ok:!1,phase:"parse",message:n.error};let o=n.config.mcpServers[t.server_name];if(!o)return{ok:!1,phase:"not_found",message:`server "${t.server_name}" not found in config`};let i=(e.buildTransport??x2)(o),a=new Bu({name:"silverhand-probe",version:"1"},{capabilities:{}});try{await jE(a.connect(i,{timeout:OE}),OE,"connect")}catch(c){return await ME(a),{ok:!1,phase:w2(c),message:NE(c)}}try{let c=a.getServerVersion(),u=c?{name:c.name,version:c.version}:void 0;if(!t.include_tools)return{ok:!0,phase:"initialize",server_info:u};try{let d=(await jE(a.listTools(void 0,{timeout:DE}),DE,"tools/list")).tools.map(p=>({name:p.name,description:p.description}));return{ok:!0,phase:"tools",server_info:u,tools:d}}catch(l){return{ok:!1,phase:"tools",server_info:u,message:NE(l)}}}finally{await ME(a)}}async function S2(t,e){let{source:r}=t,n=b2(Ge(r.agent_id,e),Tr);try{return await v2.readFile(n,"utf-8")}catch(o){if(o?.code==="ENOENT")return null;throw new Xh("fs_unavailable",o instanceof Error?o.message:String(o))}}function x2(t){if("url"in t){let e=new URL(t.url),r=t.headers;return t.type==="sse"?new nl(e,{requestInit:r?{headers:r}:void 0}):new Qu(e,{requestInit:r?{headers:r}:void 0})}return new Gu({command:t.command,args:t.args,env:t.env?{...$h(),...t.env}:void 0})}async function ME(t){try{await t.close()}catch{}}function w2(t){let e=(t instanceof Error?t.message:String(t)).toLowerCase();return/econn|enotfound|etimedout|ehostunreach|eai_again|fetch failed|socket hang|getaddrinfo|spawn|enoent|certificate|self-signed|tls|http \d{3}|timed out/.test(e)?"connect":"initialize"}function NE(t){let e=t instanceof Error?t.message:String(t);return e=e.replace(/(https?:\/\/[^\s?#]+)[^\s]*/gi,"$1"),e=e.replace(/bearer\s+[\w.\-+/=]+/gi,"Bearer <redacted>"),e.slice(0,500)}async function jE(t,e,r){let n,o=new Promise((i,a)=>{n=setTimeout(()=>a(new Error(`${r} timed out after ${e}ms`)),e)});try{return await Promise.race([t,o])}finally{n&&clearTimeout(n)}}var or=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="RuntimeStartResolveError"}code};function FE(t,e){let r=t.agent.id,n=Ge(r,e),o=Al(r),i=a=>{if(a.kind==="agent_home"){if(a.id!==o)throw new or("workspace_not_provisioned",`agent_home workspace ref '${a.id}' does not belong to agent '${r}' (expected '${o}'); refusing to resolve a foreign ref onto this agent's L1`);return{...a,path:n}}return{...a,path:e.resolveRegularWorkspacePath(a.id)}};return{...t,agent:{...t.agent,home_dir:n},workspace:i(t.workspace),workspace_memory_index:t.workspace_memory_index.map(i)}}import{existsSync as k2,mkdirSync as R2,readdirSync as HE,readFileSync as P2,renameSync as E2,unlinkSync as qE,writeFileSync as C2}from"node:fs";import{randomUUID as T2}from"node:crypto";import{homedir as A2}from"node:os";import{basename as I2,dirname as UE,join as Vi}from"node:path";function WE(){return Vi(A2(),".silverhand","daemon","runtime-pids")}function ZE(t,e=process.pid){return`${t}-${e}`}function BE(t,e,r,n){return Vi(t,e,`${encodeURIComponent(r)}-${encodeURIComponent(n)}.json`)}function VE(t){let e=BE(t.rootDir,t.daemonInstanceId,t.conversationId,t.agentId);R2(UE(e),{recursive:!0});let r={pid:t.pid,started_at:t.startedAt,conv:t.conversationId,agent:t.agentId,runtime:t.runtime,cmd:t.cmd},n=Vi(UE(e),`.${I2(e)}.${process.pid}.${T2()}.tmp`);try{C2(n,`${JSON.stringify(r)}
607
- `,{mode:384}),E2(n,e)}catch(o){try{qE(n)}catch{}throw o}return e}function KE(t){let e=BE(t.rootDir,t.daemonInstanceId,t.conversationId,t.agentId);ol(e)}function GE(t){let e={skipped:!1,scanned:0,unlinkedDead:0,unlinkedCorrupt:0,killedForeign:0,preservedSelf:0,preservedEperm:0,errors:0};if(!k2(t.rootDir))return e.skipped=!0,t.logger.info({runtime_pid_root:t.rootDir},"runtime pidfile root missing; skipping orphan reconcile"),e;let r;try{r=HE(t.rootDir,{withFileTypes:!0})}catch(n){return e.errors++,t.logger.warn({runtime_pid_root:t.rootDir,err:n.message},"failed to read runtime pidfile root; skipping orphan reconcile"),e}for(let n of r){if(!n.isDirectory())continue;let o=n.name,i=Vi(t.rootDir,o),a;try{a=HE(i,{withFileTypes:!0})}catch(c){e.errors++,t.logger.warn({runtime_pid_dir:i,daemon_instance:o,err:c.message},"failed to read runtime pidfile instance dir; continuing");continue}for(let c of a){if(!c.isFile()||!c.name.endsWith(".json"))continue;let u=Vi(i,c.name);e.scanned++;try{let l=$2(u);if(!l){ol(u),e.unlinkedCorrupt++,t.logger.warn({runtime_pidfile:u},"runtime pidfile corrupt; unlinked");continue}let d=z2(l.pid,t.deps);if(d==="dead"){ol(u),e.unlinkedDead++,t.logger.info({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile pointed at dead process; unlinked");continue}if(d==="eperm"){e.preservedEperm++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process exists but cannot be signaled; preserving");continue}if(d==="error"){e.errors++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process liveness check failed; preserving");continue}if(o===t.selfDaemonInstanceId){e.preservedSelf++;continue}let p=O2(l.pid,t.deps);if(p==="killed"||p==="gone"){ol(u),e.killedForeign++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o,self_daemon_instance:t.selfDaemonInstanceId,killed:p},"killed runtime child owned by prior daemon instance");continue}p==="eperm"?e.preservedEperm++:e.errors++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process could not be SIGKILLed; preserving")}catch(l){e.errors++,t.logger.warn({runtime_pidfile:u,err:l.message},"failed to reconcile runtime pidfile; continuing")}}}return e}function $2(t){try{let e=JSON.parse(P2(t,"utf8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.started_at!="number"||!Number.isInteger(e.started_at)||typeof e.conv!="string"||e.conv.length===0||typeof e.agent!="string"||e.agent.length===0||typeof e.runtime!="string"||e.runtime.length===0||typeof e.cmd!="string"||e.cmd.length===0?null:e}catch{return null}}function z2(t,e){try{return(e?.kill??process.kill)(t,0),"alive"}catch(r){let n=r.code;return n==="EPERM"?"eperm":n==="ESRCH"?"dead":"error"}}function O2(t,e){try{return(e?.kill??process.kill)(t,"SIGKILL"),"killed"}catch(r){let n=r.code;return n==="ESRCH"?"gone":n==="EPERM"?"eperm":"error"}}function ol(t){try{qE(t)}catch(e){if(e.code!=="ENOENT")throw e}}import{existsSync as eg,mkdirSync as D2,readFileSync as M2,renameSync as YE,writeFileSync as N2}from"node:fs";import{dirname as j2}from"node:path";var L2=s.object({proxy_url:s.string().nullable().default(null),proxy_runtimes:s.array(De).default([])}),Qh=Object.freeze({proxy_url:null,proxy_runtimes:[]});function XE(t){let e=L2.parse(t),r=F2(e.proxy_runtimes);return{proxy_url:e.proxy_url,proxy_runtimes:r}}function Ki(t,e){if(!t)return{...Qh};try{let r=M2(t,"utf8");return XE(JSON.parse(r))}catch(r){return r.code==="ENOENT"?{...Qh}:(e?.warn({err:r instanceof Error?r.message:String(r),path:t},"daemon proxy config read failed; falling back to empty config"),{...Qh})}}function tg(t,e){let r=XE(e);D2(j2(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;return N2(n,`${JSON.stringify(r,null,2)}
608
- `,{encoding:"utf8",mode:384}),YE(n,t),r}function rg(t){let e=t.legacyPath;if(!(!e||e===t.targetPath||!eg(e))){if(eg(t.targetPath)){JE(e,t.logger);return}try{let r=Ki(e,t.logger);tg(t.targetPath,r),JE(e,t.logger),t.logger?.info?.({legacy_path:e,target_path:t.targetPath},"daemon proxy config migrated to per-computer profile")}catch(r){t.logger?.warn({err:r instanceof Error?r.message:String(r),legacy_path:e,target_path:t.targetPath},"daemon proxy config migration failed; keeping legacy file untouched")}}}function JE(t,e){if(!eg(t))return;let r=`${t}.migrated`;try{YE(t,r)}catch(n){e?.warn({err:n instanceof Error?n.message:String(n),legacy_path:t,migrated_path:r},"daemon proxy config legacy marker rename failed")}}function F2(t){let e=[],r=new Set;for(let n of t)r.has(n)||(r.add(n),e.push(n));return e}import{createHash as H2}from"node:crypto";import{homedir as U2}from"node:os";import{join as ng}from"node:path";function og(){return ng(U2(),".silverhand")}function QE(t,e=og()){return ng(e,"computers",q2(t.host_id))}function sg(t,e=og()){return ng(QE(t,e),"proxy-config.json")}function e0(t,e=og()){return QE({host_id:t},e)}function q2(t){return t.replace(/[^A-Za-z0-9_.-]+/g,"_").slice(0,80)||W2(t)}function W2(t){return H2("sha256").update(t).digest("hex").slice(0,12)}import{existsSync as Z2}from"node:fs";import{dirname as B2,resolve as t0}from"node:path";import{fileURLToPath as V2}from"node:url";function r0(t){if(t.localLauncher)return t.localLauncher;if(t.serverLauncher)return t.serverLauncher;throw new Error("runtime_start: no silverhand CLI launcher supplied by server and no daemon-local launcher was resolved")}function n0(t={}){let e=t.entryUrl??import.meta.url,r=t.execPath??process.execPath,n=t.exists??Z2,o=B2(V2(e)),a=[{entry:t0(o,"cli.js")},{entry:t0(o,"..","silverhand-cli","cli.mjs"),env:{ELECTRON_RUN_AS_NODE:"1"}}].find(c=>n(c.entry));return a?{command:r,args:[a.entry],...a.env?{env:a.env}:{}}:null}function Y2(t,e){if(!t)return null;try{let r=K2(t,"utf8").trim();return r?new URL(r).origin:null}catch(r){return r.code!=="ENOENT"&&e.warn({filepath:t,err:r.message},"failed to read daemon-local control-plane URL; runtime_start will fail if no outbound binding is attached"),null}}function X2(t){let e=Y2(t.controlPlaneServerUrlPath,t.logger);if(e)return e;let r=t.registryBinding?.server_origin??null;if(!r)return null;try{let n=new URL(r);if(n.protocol==="http:"||n.protocol==="https:")return n.origin}catch{}return null}async function sl(t){let e=Date.now(),r=ZE(e),n=t.runtimePidRootDir===void 0?WE():t.runtimePidRootDir,o=t.daemonIdentityPath===void 0?Y_(n):t.daemonIdentityPath,i=t.daemonIdentity!==void 0?t.daemonIdentity??void 0:o===null?void 0:X_(o),a=Xa(r,i),c=()=>({event:"ready",...a,socket_path:t.socketPath,daemon_pid:process.pid,started_at:e}),u=t.logger??sy({dir:t.logDir,alsoStderr:t.alsoStderr??!1,base:{component:"silverhand-daemon",daemon_version:mn}}),l=n0();l?Ar(u,{action:"cli_launcher_resolved",pid:process.pid}):t.supervisorFactory&&Ar(u,{action:"cli_launcher_unavailable",pid:process.pid});let d=pg(t.pidFilePath);if(d.status==="conflict"){let E=new Error(`another silverhand-daemon is already running (pid=${d.conflictingPid})`);throw E.code="EALREADY",u.error({pidFilePath:t.pidFilePath,conflictingPid:d.conflictingPid},"refusing to start: pid file already owned by live daemon"),await u.close(),E}if(Ar(u,{action:"pid_claim",pid:process.pid,pid_file_path:t.pidFilePath}),n!==null)try{let E=GE({rootDir:n,selfDaemonInstanceId:r,logger:u});u.info({runtimePidRootDir:n,daemonInstanceId:r,...E},"runtime pidfile orphan reconcile completed")}catch(E){u.warn({runtimePidRootDir:n,daemonInstanceId:r,err:E.message},"runtime pidfile orphan reconcile failed; continuing daemon boot")}let p=()=>{},m=()=>{throw new Error("outbound dispatchCommand invoked before dispatcher was wired")},f=new kc({logger:u,readyEvent:c,dispatchCommand:E=>m(E)}),_=t.hostConfig?{server_origin:new URL(t.hostConfig.server_url).origin,host_id:t.hostConfig.host_id}:null,g=t.testHooks?.workspaceRegistryStateDir??(o!==null?o0(o):`${J2()}/.silverhand/daemon`),y=t.testHooks?.silverhandStateRoot??o0(g),S=G2(y,"workspaces"),x=t.agentHomeRootDir??void 0,w=i?.daemon_id??"local",T=()=>_??f.currentBinding(),v=()=>mt!=null?{server_origin:"local-embedded",host_id:T()?.host_id??w}:T(),P=()=>{if(t.proxyConfigPath)return t.proxyConfigPath;let E=v();if(E==null)return null;let ee=sg(E,y);return mt!=null&&E.host_id!==w&&rg({legacyPath:sg({host_id:w},y),targetPath:ee,logger:u}),rg({legacyPath:t.legacyProxyConfigPath,targetPath:ee,logger:u}),ee},O={homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x,resolveRegularWorkspacePath:E=>{let ee=v();if(ee==null)throw new or("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let at=new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});try{return at.resolve(E)}catch(Yi){throw Yi instanceof ae?new or(Yi.code==="not_provisioned"?"workspace_not_provisioned":"registry_unavailable",Yi.message):Yi}}},J=t.supervisorFactory?t.supervisorFactory({emit:E=>p(E),logger:u,daemonInstanceId:r,runtimePidRootDir:n,daemonSocketPath:t.socketPath,runtimeStartResolveDeps:O,proxyConfigPath:P,localSilverhandCliLauncher:l,controlPlaneServerUrl:()=>X2({registryBinding:v(),controlPlaneServerUrlPath:t.controlPlaneServerUrlPath,logger:u})}):void 0,F=new Qa({logger:u,startedAt:e,helloResult:a,supervisor:J,hostOutboundAttachHandler:E=>f.attach(E),hostOutboundDetachHandler:()=>f.detach(),hostOutboundReloadHandler:()=>f.reload(),hostProxyConfigGetHandler:()=>({config:Ki(P(),u)}),hostProxyConfigSetHandler:E=>{let ee=P();if(!ee)throw new Error("host proxy config path is not configured");return{config:tg(ee,E)}},agentMaterializeHandler:async E=>{let ee=t.testHooks?.agentMaterializeFaultInjector?.(E);if(ee)throw ee;return Kd(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},workspaceProvisionHandler:async E=>{let ee=v();if(ee==null)throw new bt("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let at=new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return Yd(E,{registry:at,logger:u})},agentWorkspaceIndexHandler:async E=>{let ee=v();if(ee==null)throw new xn("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let at=new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return Xd(E,{registry:at,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentWorkspaceTreeHandler:async E=>{let ee=E.workspace_id?v():null,at=ee?new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S}):void 0;return np(E,{registry:at,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentWorkspaceFileReadHandler:async E=>{let ee=E.workspace_id?v():null,at=ee?new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S}):void 0;return sp(E,{registry:at,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentL2SeedHandler:async E=>{let ee=v();if(ee==null)throw new St("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let at=new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return Qd(E,{registry:at})},agentFilesPurgeHandler:async E=>{let ee=v();if(ee==null)throw new zr("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let at=new zt({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return ep(E,{registry:at,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentProfileMcpReadHandler:async E=>Uv(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x}),agentProfileMcpWriteHandler:async E=>qv(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x}),mcpProbeHandler:async E=>LE(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})});m=E=>F.dispatch(E.id,String(E.kind),E.params);let ie=new tc({socketPath:t.socketPath,dispatcher:F,logger:u}),pt=t.hostConfig?new yo({config:t.hostConfig,logger:u,readyEvent:c,dispatchCommand:E=>m(E)}):null,mt=t.localOutboundSocketPath!=null?new Rc({socketPath:t.localOutboundSocketPath,dispatchCommand:E=>m(E),logger:u,readyEvent:c}):null;p=E=>{ie.broadcast(E),f.sendEvent(E),pt?.sendEvent(E),mt?.broadcast(E)};try{await ie.start()}catch(E){throw u.error({err:E.message,socketPath:t.socketPath},"failed to bind socket"),Qi(t.pidFilePath),await u.close(),E}if(mt)try{await mt.start()}catch(E){throw u.error({err:E.message,socketPath:t.localOutboundSocketPath},"failed to bind local outbound frame socket"),await ie.stop("local_outbound_bind_failed"),Qi(t.pidFilePath),await u.close(),E}if((t.writeStdoutHandshake??!0)&&process.stdout.write(Jt(c())),u.info({socketPath:t.socketPath,pidFilePath:t.pidFilePath,logFile:u.filePath},"daemon ready"),Ar(u,{action:"boot",pid:process.pid,socket_path:t.socketPath,pid_file_path:t.pidFilePath}),t.hostConfigPath){let E=f.attach({config_path:t.hostConfigPath});E.attached||u.warn({kind:"outbound_supervisor",action:"cli_auto_attach_failed",reason:E.reason,message:E.message},"daemon outbound CLI auto-attach failed; outbound is inactive until host_outbound_attach IPC arrives")}pt?.start();let Kr=!1,Ct=async E=>{if(!Kr){if(Kr=!0,Ar(u,{action:"shutting_down",pid:process.pid}),f.sendEvent({event:"shutting_down",reason:E}),f.stop(E),pt?.stop(E),mt)try{await mt.stop()}catch(ee){u.error({err:ee.message},"local outbound server stop threw; continuing teardown")}try{await ie.stop(E)}catch(ee){u.error({err:ee.message},"server.stop threw; continuing teardown")}Qi(t.pidFilePath),u.info({reason:E},"daemon stopped"),await u.close()}};return(t.installSignals??!0)&&mg(u,async E=>{await Ct(E)}),{socketPath:t.socketPath,pidFilePath:t.pidFilePath,logger:u,broadcast:E=>p(E),stop:Ct}}import{spawn as $Z}from"node:child_process";import{setTimeout as Vn}from"node:timers";import{randomUUID as zZ}from"node:crypto";import{stat as OZ,writeFile as DZ}from"node:fs/promises";import{randomUUID as eZ}from"node:crypto";function al(t,e){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]},...e?{session_id:e}:{}})}function cl(t,e={}){let r=t.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[],i=e.classifyError;switch(n.type){case"system":{n.subtype==="init"&&typeof n.session_id=="string"&&o.push({kind:"session_init",sessionId:n.session_id}),n.subtype==="api_error"&&o.push(Q2(n,e.runtimeLabel)),n.subtype==="status"&&n.status==="compacting"&&o.push({kind:"compaction_started"}),n.subtype==="compact_boundary"&&o.push({kind:"compaction_finished"});break}case"assistant":{let a=n.message?.content;if(Array.isArray(a))for(let c of a)c?.type==="thinking"&&typeof c.thinking=="string"?o.push({kind:"thinking",text:c.thinking}):c?.type==="text"&&typeof c.text=="string"?o.push({kind:"text",text:c.text}):c?.type==="tool_use"&&o.push({kind:"tool_call",name:typeof c.name=="string"?c.name:"unknown_tool",input:c.input,toolCallId:typeof c.id=="string"?c.id:void 0});break}case"user":{let a=n.message?.content;if(Array.isArray(a))for(let c of a)c?.type==="tool_result"&&o.push({kind:"tool_output",name:typeof c.name=="string"?c.name:void 0,toolCallId:typeof c.tool_use_id=="string"?c.tool_use_id:void 0});break}case"result":{let a=typeof n.subtype=="string"?n.subtype:"success",c=typeof n.stop_reason=="string"?n.stop_reason:null,u=l=>{if(c!=="max_tokens"){let d=il(n)||l;o.push({kind:"error",message:d,...i?i(d):{}})}};switch(a){case"success":n.is_error&&u("Execution failed");break;case"error_during_execution":u("Execution failed");break;case"error_max_budget_usd":o.push({kind:"error",message:il(n)||"Budget limit exceeded"});break;case"error_max_turns":o.push({kind:"error",message:il(n)||"Max turns exceeded"});break;case"error_max_structured_output_retries":o.push({kind:"error",message:il(n)||"Structured output retries exceeded"});break}o.push({kind:"turn_end",sessionId:typeof n.session_id=="string"?n.session_id:void 0});break}default:break}return o}function ul(t){let e=t.trim();if(!e)return null;let r;try{r=JSON.parse(e)}catch{return null}return r?.type==="system"&&r.subtype==="init"&&typeof r.session_id=="string"?"session_ready":r&&typeof r=="object"?"protocol_ready":null}function Q2(t,e){let r=typeof t.error?.cause?.code=="string"?t.error.cause.code:typeof t.cause?.code=="string"?t.cause.code:null,n=typeof t.retryAttempt=="number"&&Number.isFinite(t.retryAttempt)?t.retryAttempt:null,o=r==="ConnectionRefused"?"api_connection_refused":"api_error",i=e?`${e} API`:"API",a=r==="ConnectionRefused"?`${i} gateway unreachable; retrying`:`${i} request failed; retrying`;return{kind:"error",code:o,message:n!==null?`${a} (attempt ${n})`:a}}function il(t){let e=[];if(Array.isArray(t.errors))for(let r of t.errors)typeof r=="string"&&r.trim()&&e.push(r.trim());return typeof t.result=="string"&&t.result.trim()&&e.push(t.result.trim()),e.join(" | ")}var tZ=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(","),ll=class{kind="claude";binary="claude";kickoffMode="requires_first_message";busyDeliveryMode="gated";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=["--dangerously-skip-permissions","--allow-dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",e.model||"opus","--disallowed-tools",tZ,"--append-system-prompt-file",e.systemPromptPath];return e.cliSessionId&&r.push("--resume",e.cliSessionId),r}applyEnv(e){let r={...e};return delete r.CLAUDECODE,r}encodeStdinMessage(e,r){return al(e,r)}encodeInterruptControl(){return JSON.stringify({type:"control_request",request_id:eZ(),request:{subtype:"interrupt"}})}parseLine(e){return cl(e,{runtimeLabel:"Claude",classifyError:rZ})}classifyInitProgress(e){return ul(e)}};function rZ(t){return t.includes("No conversation found with session ID:")||t.includes("--resume requires a valid session ID")?{code:"session_not_found",fatal:!0}:{}}import{execSync as s0}from"node:child_process";import{existsSync as nZ,readFileSync as oZ}from"node:fs";import{join as sZ}from"node:path";var dl=class{kind="codex";binary="codex";kickoffMode="self_inits";busyDeliveryMode="direct";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=60*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;io=null;requestId=0;threadId=null;activeTurnId=null;initializeRequestId=null;pendingThreadRequest=null;pendingInitialPrompt=null;initialTurnStarted=!1;sessionAnnounced=!1;streamedAgentMessageIds=new Set;streamedReasoningIds=new Set;pendingFileChangeCounts=new Map;pendingWebSearchIds=new Set;buildArgs(e){let r=["app-server","--listen","stdio://"];return e.reasoningEffort&&r.push("-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`),e.fastMode===!0?r.push("--enable","fast_mode"):e.fastMode===!1&&r.push("--disable","fast_mode"),r}applyEnv(e){return{...e,NO_COLOR:"1"}}bindIO(e){aZ(e.spawnCtx.workspacePath),this.io=e,this.threadId=null,this.pendingInitialPrompt=e.spawnCtx.initialPrompt||null;let r=oZ(e.spawnCtx.systemPromptPath,"utf-8");this.pendingThreadRequest=this.buildThreadRequest(e.spawnCtx,r),queueMicrotask(()=>{this.initializeRequestId=this.sendRequest("initialize",{clientInfo:{name:"silverhand",version:"1.0.0"},capabilities:{experimentalApi:!0}})})}encodeStdinMessage(e,r){return this.threadId?this.activeTurnId?JSON.stringify({jsonrpc:"2.0",id:this.nextRequestId(),method:"turn/steer",params:{threadId:this.threadId,expectedTurnId:this.activeTurnId,input:[{type:"text",text:e}]}}):JSON.stringify({jsonrpc:"2.0",id:this.nextRequestId(),method:"turn/start",params:{threadId:this.threadId,input:[{type:"text",text:e}]}}):null}readyToEncode(){return this.threadId!==null}encodeInterruptControl(){return null}parseLine(e){let r=e.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[];if(n.result!==void 0){if(n.id===this.initializeRequestId)return this.initializeRequestId=null,this.sendNotification("initialized",{}),this.pendingThreadRequest&&(this.sendRequest(this.pendingThreadRequest.method,this.pendingThreadRequest.params),this.pendingThreadRequest=null),o;let i=n.result?.thread;if(i&&typeof i.id=="string")return this.handleThreadReady(i.id,o),o;let a=n.result?.turn;return a&&typeof a.id=="string"?(this.activeTurnId=a.id,o):(typeof n.result?.turnId=="string"&&(this.activeTurnId=n.result.turnId),o)}if(n.error){n.id===this.initializeRequestId&&(this.initializeRequestId=null,this.pendingThreadRequest=null);let i=typeof n.error?.message=="string"?n.error.message:"Codex app-server request failed";return o.push({kind:"error",message:i,...i0(i)}),o}switch(n.method){case"thread/started":{let i=n.params?.thread?.id;typeof i=="string"&&this.handleThreadReady(i,o);break}case"turn/started":{let i=n.params?.turn?.id;typeof i=="string"&&(this.activeTurnId=i),o.push({kind:"thinking",text:""});break}case"item/agentMessage/delta":{let i=n.params?.delta,a=n.params?.itemId;typeof a=="string"&&this.streamedAgentMessageIds.add(a),typeof i=="string"&&i.length>0&&o.push({kind:"text",text:i});break}case"item/reasoning/summaryTextDelta":case"item/reasoning/textDelta":{let i=n.params?.delta,a=n.params?.itemId;typeof a=="string"&&this.streamedReasoningIds.add(a),typeof i=="string"&&i.length>0&&o.push({kind:"thinking",text:i});break}case"item/started":case"item/completed":{let i=n.params?.item;if(!i||typeof i!="object"||typeof i.type!="string")break;this.handleItemEvent(n.method,i,o);break}case"turn/completed":{let i=n.params?.turn;i?.status==="failed"&&typeof i?.error?.message=="string"&&o.push({kind:"error",message:i.error.message}),this.activeTurnId=null,this.streamedAgentMessageIds.clear(),this.streamedReasoningIds.clear(),this.pendingFileChangeCounts.clear(),this.pendingWebSearchIds.clear(),o.push({kind:"turn_end",sessionId:this.threadId??void 0});break}case"error":{let i=n.params,a=typeof i?.message=="string"?i.message:typeof i?.error?.message=="string"?i.error.message:"Unknown Codex app-server error";o.push({kind:"error",message:a,...i0(a)});break}}return o}classifyInitProgress(e){let r=e.trim();if(!r)return null;let n;try{n=JSON.parse(r)}catch{return null}if(!n||typeof n!="object"||n.jsonrpc!=="2.0"&&!("method"in n)&&!("result"in n)&&!("error"in n))return null;let o=n.result?.thread;return o&&typeof o.id=="string"||n.method==="thread/started"&&typeof n.params?.thread?.id=="string"?"session_ready":"protocol_ready"}handleItemEvent(e,r,n){let o=e==="item/started",i=e==="item/completed";switch(r.type){case"reasoning":if(i&&typeof r.id=="string"&&!this.streamedReasoningIds.has(r.id)){let a=iZ(r);a&&n.push({kind:"thinking",text:a})}i&&typeof r.id=="string"&&this.streamedReasoningIds.delete(r.id);break;case"agentMessage":i&&typeof r.id=="string"&&!this.streamedAgentMessageIds.has(r.id)&&typeof r.text=="string"&&r.text.length>0&&n.push({kind:"text",text:r.text}),i&&typeof r.id=="string"&&this.streamedAgentMessageIds.delete(r.id);break;case"commandExecution":o&&typeof r.command=="string"&&n.push({kind:"tool_call",name:"shell",input:{command:r.command}}),i&&n.push({kind:"tool_output",name:"shell"});break;case"contextCompaction":o&&n.push({kind:"compaction_started"}),i&&n.push({kind:"compaction_finished"});break;case"fileChange":if(o&&Array.isArray(r.changes)){for(let a of r.changes)n.push({kind:"tool_call",name:"file_change",input:{path:a?.path,kind:a?.kind}});typeof r.id=="string"&&this.pendingFileChangeCounts.set(r.id,r.changes.length)}if(i&&typeof r.id=="string"){let a=this.pendingFileChangeCounts.get(r.id)??0;for(let c=0;c<a;c+=1)n.push({kind:"tool_output",name:"file_change"});this.pendingFileChangeCounts.delete(r.id)}break;case"mcpToolCall":{let a=r.server==="chat"?`mcp_chat_${r.tool}`:`mcp_${r.server}_${r.tool}`;o&&n.push({kind:"tool_call",name:a,input:r.arguments}),i&&n.push({kind:"tool_output",name:a});break}case"webSearch":if(o&&(n.push({kind:"tool_call",name:"web_search",input:{query:r.query}}),typeof r.id=="string"&&this.pendingWebSearchIds.add(r.id)),i){let a=typeof r.id=="string"?r.id:null;a&&this.pendingWebSearchIds.delete(a)&&n.push({kind:"tool_output",name:"web_search"})}break}}handleThreadReady(e,r){this.threadId=e,this.sessionAnnounced||(r.push({kind:"session_init",sessionId:e}),this.sessionAnnounced=!0),this.startInitialTurn()}startInitialTurn(){if(this.initialTurnStarted||!this.pendingInitialPrompt||!this.threadId)return;this.initialTurnStarted=!0;let e=this.pendingInitialPrompt;this.pendingInitialPrompt=null,this.sendRequest("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})}buildThreadRequest(e,r){let n={cwd:e.workspacePath,approvalPolicy:"never",sandbox:"danger-full-access",developerInstructions:r};return e.model?n.model=e.model:n.model="gpt-5.5",e.cliSessionId?{method:"thread/resume",params:{threadId:e.cliSessionId,...n}}:{method:"thread/start",params:n}}nextRequestId(){return this.requestId+=1,this.requestId}sendRequest(e,r){let n=this.nextRequestId();return this.io?.writeLine(JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:r})),n}sendNotification(e,r){this.io?.writeLine(JSON.stringify({jsonrpc:"2.0",method:e,params:r}))}};function i0(t){return/thread not found/i.test(t)?{code:"thread_not_found",fatal:!0}:{}}function iZ(t){let e=Array.isArray(t.summary)?t.summary.filter(n=>typeof n=="string"):[],r=Array.isArray(t.content)?t.content.filter(n=>typeof n=="string"):[];return[...e,...r].join(`
609
- `).trim()}function aZ(t){nZ(sZ(t,".git"))||(s0("git init",{cwd:t,stdio:"pipe"}),s0("git -c user.name=silverhand -c user.email=silverhand@local -c commit.gpgsign=false add -A && git -c user.name=silverhand -c user.email=silverhand@local -c commit.gpgsign=false commit --allow-empty -m 'init'",{cwd:t,stdio:"pipe"}))}import{readFileSync as cZ}from"node:fs";var pl=class{kind="cursor";binary="cursor-agent";kickoffMode="self_inits";busyDeliveryMode="none";oneShot=!0;supportsNativeStandingPrompt=!1;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=["--print","--output-format","stream-json","--yolo","--trust"];return e.model&&r.push("--model",e.model),e.cliSessionId&&r.push("--resume",e.cliSessionId),r.push(uZ(e)),r}applyEnv(e){return{...e,FORCE_COLOR:"0",NO_COLOR:"1"}}encodeStdinMessage(e,r){return null}encodeInterruptControl(){return null}parseLine(e){let r=e.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[];switch(n.type){case"system":n.subtype==="init"&&typeof n.session_id=="string"?o.push({kind:"session_init",sessionId:n.session_id}):n.subtype==="status"&&n.status==="compacting"?o.push({kind:"compaction_started"}):n.subtype==="compact_boundary"&&o.push({kind:"compaction_finished"});break;case"assistant":{let i=n.message?.content;if(Array.isArray(i))for(let a of i)a?.type==="thinking"&&typeof a.thinking=="string"?o.push({kind:"thinking",text:a.thinking}):a?.type==="text"&&typeof a.text=="string"?o.push({kind:"text",text:a.text}):a?.type==="tool_use"&&o.push({kind:"tool_call",name:typeof a.name=="string"?a.name:"unknown_tool",input:a.input,toolCallId:typeof a.id=="string"?a.id:void 0});break}case"result":{if((typeof n.subtype=="string"?n.subtype:"success")!=="success"||n.is_error){let a=[];if(Array.isArray(n.errors))for(let c of n.errors)typeof c=="string"&&c.trim()&&a.push(c.trim());typeof n.result=="string"&&n.result.trim()&&a.push(n.result.trim()),o.push({kind:"error",message:a.join(" | ")||"Execution failed"})}o.push({kind:"turn_end",sessionId:typeof n.session_id=="string"?n.session_id:void 0});break}default:break}return o}classifyInitProgress(e){let r=e.trim();if(!r)return null;let n;try{n=JSON.parse(r)}catch{return null}return n?.type==="system"&&n.subtype==="init"&&typeof n.session_id=="string"?"session_ready":n&&typeof n=="object"?"protocol_ready":null}};function uZ(t){let e=cZ(t.systemPromptPath,"utf-8"),r=t.initialPrompt.trim()||"You are now active in this channel. Read your MEMORY.md and stand by for further instructions.";return`${e}
606
+ `,P),F=-1;if(O!==-1&&J!==-1?F=O<J?O:J:O!==-1?O===v.length-1?F=-1:F=O:J!==-1&&(F=J),F===-1)break;S(v,P,F),P=F+1,v.charCodeAt(P-1)===G2&&v.charCodeAt(P)===FE&&P++}return v.slice(P)}function S(v,P,O){if(P===O){w();return}let J=v.charCodeAt(P);if(HE(v,P,J)){let Tt=v.charCodeAt(P+5)===Zn?P+6:P+5,E=v.slice(Tt,O);d=p===0?E:`${d}
607
+ ${E}`,p++;return}if(UE(v,P,J)){m=v.slice(v.charCodeAt(P+6)===Zn?P+7:P+6,O)||void 0;return}if(J===105&&v.charCodeAt(P+1)===100&&v.charCodeAt(P+2)===58){let Tt=v.slice(v.charCodeAt(P+3)===Zn?P+4:P+3,O);l=Tt.includes("\0")?void 0:Tt;return}if(J===58){if(o){let Tt=v.slice(P,O);o(Tt.slice(v.charCodeAt(P+1)===Zn?2:1))}return}let F=v.slice(P,O),ie=F.indexOf(":");if(ie===-1){x(F,"",F);return}let mt=F.slice(0,ie),ft=F.charCodeAt(ie+1)===Zn?2:1,Gr=F.slice(ie+ft);x(mt,Gr,F)}function x(v,P,O){switch(v){case"event":m=P||void 0;break;case"data":d=p===0?P:`${d}
608
+ ${P}`,p++;break;case"id":l=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new qi(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:O}));break;default:r(new qi(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:P,line:O}));break}}function w(){p>0&&e({id:l,event:m,data:d}),l=void 0,d="",p=0,m=void 0}function T(v={}){if(v.consume&&a.length>0){let P=a.join("");S(P,0,P.length)}u=!0,l=void 0,d="",p=0,m=void 0,a.length=0,c=0,f=!1}return{feed:_,reset:T}}function HE(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function UE(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var rl=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let i;super({start(a){i=tl({onEvent:c=>{a.enqueue(c)},onError(c){typeof e=="function"&&e(c),(e==="terminate"||c.type==="max-buffer-size-exceeded")&&a.error(c)},onRetry:r,onComment:n,maxBufferSize:o})},transform(a){i.feed(a)}})}};var J2={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Vr=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},nl=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=el(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??J2}async _authThenStart(){if(!this._authProvider)throw new Qe("No auth provider");let e;try{e=await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=os(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Vr(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:i}=r,a,c=!1,u=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new rl({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:_}=await d.read();if(_)break;if(f.id&&(a=f.id,c=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let g=Nr.parse(JSON.parse(f.data));En(g)&&(u=!0,i!==void 0&&(g.id=i)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Qe("No auth provider");if(await wr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Ks(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let a={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,a),u=c.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!c.ok){let m=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Vr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:f,scope:_}=ss(c);if(this._resourceMetadataUrl=f,this._scope=_,await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:f,scope:_,error:g}=ss(c);if(g==="insufficient_scope"){let y=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Vr(403,"Server returned 403 after trying upscoping");if(_&&(this._scope=_),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Qe;return this.send(e)}}throw new Vr(c.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Iw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let d=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,p=c.headers.get("content-type");if(d)if(p?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:o},!1);else if(p?.includes("application/json")){let m=await c.json(),f=Array.isArray(m)?m.map(_=>Nr.parse(_)):[Nr.parse(m)];for(let _ of f)this.onmessage?.(_)}else throw await c.body?.cancel(),new Vr(-1,`Unexpected content type: ${p}`);else await c.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Vr(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var sl=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(qE(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(qE(this),r)}};function Y2(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Kh(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Kh).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Kh(t.cause)}`:t.message:`${t}`}function qE(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var ZE=t=>{throw TypeError(t)},rg=(t,e,r)=>e.has(t)||ZE("Cannot "+r),X=(t,e,r)=>(rg(t,e,"read from private field"),r?r.call(t):e.get(t)),$e=(t,e,r)=>e.has(t)?ZE("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Re=(t,e,r,n)=>(rg(t,e,"write to private field"),e.set(t,r),r),kr=(t,e,r)=>(rg(t,e,"access private method"),r),at,Bn,is,ol,il,Bi,us,Vi,Kr,as,ls,cs,Wi,Wt,Gh,Jh,Yh,WE,Xh,Qh,Zi,eg,tg,Vn=class extends EventTarget{constructor(e,r){var n,o;super(),$e(this,Wt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,$e(this,at),$e(this,Bn),$e(this,is),$e(this,ol),$e(this,il),$e(this,Bi),$e(this,us),$e(this,Vi,null),$e(this,Kr),$e(this,as),$e(this,ls,null),$e(this,cs,null),$e(this,Wi,null),$e(this,Jh,async i=>{var a;X(this,as).reset();let{body:c,redirected:u,status:l,headers:d}=i;if(l===204){kr(this,Wt,Zi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Re(this,is,new URL(i.url)):Re(this,is,void 0),l!==200){kr(this,Wt,Zi).call(this,`Non-200 status code (${l})`,l);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){kr(this,Wt,Zi).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(X(this,at)===this.CLOSED)return;Re(this,at,this.OPEN);let p=new Event("open");if((a=X(this,Wi))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){kr(this,Wt,Zi).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}let m=new TextDecoder,f=c.getReader(),_=!0;do{let{done:g,value:y}=await f.read();y&&X(this,as).feed(m.decode(y,{stream:!g})),g&&(_=!1,X(this,as).reset(),kr(this,Wt,eg).call(this))}while(_)}),$e(this,Yh,i=>{Re(this,Kr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&kr(this,Wt,eg).call(this,Kh(i))}),$e(this,Xh,i=>{typeof i.id=="string"&&Re(this,Vi,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:X(this,is)?X(this,is).origin:X(this,Bn).origin,lastEventId:i.id||""});X(this,cs)&&(!i.event||i.event==="message")&&X(this,cs).call(this,a),this.dispatchEvent(a)}),$e(this,Qh,i=>{Re(this,Bi,i)}),$e(this,tg,()=>{Re(this,us,void 0),X(this,at)===this.CONNECTING&&kr(this,Wt,Gh).call(this)});try{if(e instanceof URL)Re(this,Bn,e);else if(typeof e=="string")Re(this,Bn,new URL(e,X2()));else throw new Error("Invalid URL")}catch{throw Y2("An invalid or illegal string was specified")}Re(this,as,tl({onEvent:X(this,Xh),onRetry:X(this,Qh)})),Re(this,at,this.CONNECTING),Re(this,Bi,3e3),Re(this,il,(n=r?.fetch)!=null?n:globalThis.fetch),Re(this,ol,(o=r?.withCredentials)!=null?o:!1),kr(this,Wt,Gh).call(this)}get readyState(){return X(this,at)}get url(){return X(this,Bn).href}get withCredentials(){return X(this,ol)}get onerror(){return X(this,ls)}set onerror(e){Re(this,ls,e)}get onmessage(){return X(this,cs)}set onmessage(e){Re(this,cs,e)}get onopen(){return X(this,Wi)}set onopen(e){Re(this,Wi,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){X(this,us)&&clearTimeout(X(this,us)),X(this,at)!==this.CLOSED&&(X(this,Kr)&&X(this,Kr).abort(),Re(this,at,this.CLOSED),Re(this,Kr,void 0))}};at=new WeakMap,Bn=new WeakMap,is=new WeakMap,ol=new WeakMap,il=new WeakMap,Bi=new WeakMap,us=new WeakMap,Vi=new WeakMap,Kr=new WeakMap,as=new WeakMap,ls=new WeakMap,cs=new WeakMap,Wi=new WeakMap,Wt=new WeakSet,Gh=function(){Re(this,at,this.CONNECTING),Re(this,Kr,new AbortController),X(this,il)(X(this,Bn),kr(this,Wt,WE).call(this)).then(X(this,Jh)).catch(X(this,Yh))},Jh=new WeakMap,Yh=new WeakMap,WE=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...X(this,Vi)?{"Last-Event-ID":X(this,Vi)}:void 0},cache:"no-store",signal:(t=X(this,Kr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Xh=new WeakMap,Qh=new WeakMap,Zi=function(t,e){var r;X(this,at)!==this.CLOSED&&Re(this,at,this.CLOSED);let n=new sl("error",{code:e,message:t});(r=X(this,ls))==null||r.call(this,n),this.dispatchEvent(n)},eg=function(t,e){var r;if(X(this,at)===this.CLOSED)return;Re(this,at,this.CONNECTING);let n=new sl("error",{code:e,message:t});(r=X(this,ls))==null||r.call(this,n),this.dispatchEvent(n),Re(this,us,setTimeout(X(this,tg),X(this,Bi)))},tg=new WeakMap,Vn.CONNECTING=0,Vn.OPEN=1,Vn.CLOSED=2;function X2(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var ng=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},al=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=el(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Qe("No auth provider");let e;try{e=await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Qe;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=os(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Vn(this._url.href,{...this._eventSourceInit,fetch:async(o,i)=>{let a=await this._commonHeaders();a.set("Accept","text/event-stream");let c=await e(o,{...i,headers:a});if(c.status===401&&c.headers.has("www-authenticate")){let{resourceMetadataUrl:u,scope:l}=ss(c);this._resourceMetadataUrl=u,this._scope=l}return c}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let i=new ng(o.code,o.message,o);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let i=o;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{let i=o,a;try{a=Nr.parse(JSON.parse(i.data))}catch(c){this.onerror?.(c);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Qe("No auth provider");if(await wr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Qe("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let i=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:a,scope:c}=ss(o);if(this._resourceMetadataUrl=a,this._scope=c,await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Qe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var og=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="McpProbeError"}code},BE=1e4,VE=1e4;async function YE(t,e={}){let r=await tZ(t,e);if(r===null)return{ok:!1,phase:"not_found",message:`no MCP config; server "${t.server_name}" not found`};let n=ao(r);if(!n.ok)return{ok:!1,phase:"parse",message:n.error};let o=n.config.mcpServers[t.server_name];if(!o)return{ok:!1,phase:"not_found",message:`server "${t.server_name}" not found in config`};let i=(e.buildTransport??rZ)(o),a=new Ju({name:"silverhand-probe",version:"1"},{capabilities:{}});try{await JE(a.connect(i,{timeout:BE}),BE,"connect")}catch(c){return await KE(a),{ok:!1,phase:nZ(c),message:GE(c)}}try{let c=a.getServerVersion(),u=c?{name:c.name,version:c.version}:void 0;if(!t.include_tools)return{ok:!0,phase:"initialize",server_info:u};try{let d=(await JE(a.listTools(void 0,{timeout:VE}),VE,"tools/list")).tools.map(p=>({name:p.name,description:p.description}));return{ok:!0,phase:"tools",server_info:u,tools:d}}catch(l){return{ok:!1,phase:"tools",server_info:u,message:GE(l)}}}finally{await KE(a)}}async function tZ(t,e){let{source:r}=t,n=eZ(Je(r.agent_id,e),Ar);try{return await Q2.readFile(n,"utf-8")}catch(o){if(o?.code==="ENOENT")return null;throw new og("fs_unavailable",o instanceof Error?o.message:String(o))}}function rZ(t){if("url"in t){let e=new URL(t.url),r=t.headers;return t.type==="sse"?new al(e,{requestInit:r?{headers:r}:void 0}):new nl(e,{requestInit:r?{headers:r}:void 0})}return new Qu({command:t.command,args:t.args,env:t.env?{...jh(),...t.env}:void 0})}async function KE(t){try{await t.close()}catch{}}function nZ(t){let e=(t instanceof Error?t.message:String(t)).toLowerCase();return/econn|enotfound|etimedout|ehostunreach|eai_again|fetch failed|socket hang|getaddrinfo|spawn|enoent|certificate|self-signed|tls|http \d{3}|timed out/.test(e)?"connect":"initialize"}function GE(t){let e=t instanceof Error?t.message:String(t);return e=e.replace(/(https?:\/\/[^\s?#]+)[^\s]*/gi,"$1"),e=e.replace(/bearer\s+[\w.\-+/=]+/gi,"Bearer <redacted>"),e.slice(0,500)}async function JE(t,e,r){let n,o=new Promise((i,a)=>{n=setTimeout(()=>a(new Error(`${r} timed out after ${e}ms`)),e)});try{return await Promise.race([t,o])}finally{n&&clearTimeout(n)}}var sr=class extends Pe{constructor(r,n){super(n);this.code=r;this.name="RuntimeStartResolveError"}code};function XE(t,e){let r=t.agent.id,n=Je(r,e),o=Ol(r),i=a=>{if(a.kind==="agent_home"){if(a.id!==o)throw new sr("workspace_not_provisioned",`agent_home workspace ref '${a.id}' does not belong to agent '${r}' (expected '${o}'); refusing to resolve a foreign ref onto this agent's L1`);return{...a,path:n}}return{...a,path:e.resolveRegularWorkspacePath(a.id)}};return{...t,agent:{...t.agent,home_dir:n},workspace:i(t.workspace),workspace_memory_index:t.workspace_memory_index.map(i)}}import{existsSync as oZ,mkdirSync as sZ,readdirSync as QE,readFileSync as iZ,renameSync as aZ,unlinkSync as t0,writeFileSync as cZ}from"node:fs";import{randomUUID as uZ}from"node:crypto";import{homedir as lZ}from"node:os";import{basename as dZ,dirname as e0,join as Ki}from"node:path";function r0(){return Ki(lZ(),".silverhand","daemon","runtime-pids")}function n0(t,e=process.pid){return`${t}-${e}`}function o0(t,e,r,n){return Ki(t,e,`${encodeURIComponent(r)}-${encodeURIComponent(n)}.json`)}function s0(t){let e=o0(t.rootDir,t.daemonInstanceId,t.conversationId,t.agentId);sZ(e0(e),{recursive:!0});let r={pid:t.pid,started_at:t.startedAt,conv:t.conversationId,agent:t.agentId,runtime:t.runtime,cmd:t.cmd},n=Ki(e0(e),`.${dZ(e)}.${process.pid}.${uZ()}.tmp`);try{cZ(n,`${JSON.stringify(r)}
609
+ `,{mode:384}),aZ(n,e)}catch(o){try{t0(n)}catch{}throw o}return e}function i0(t){let e=o0(t.rootDir,t.daemonInstanceId,t.conversationId,t.agentId);cl(e)}function a0(t){let e={skipped:!1,scanned:0,unlinkedDead:0,unlinkedCorrupt:0,killedForeign:0,preservedSelf:0,preservedEperm:0,errors:0};if(!oZ(t.rootDir))return e.skipped=!0,t.logger.info({runtime_pid_root:t.rootDir},"runtime pidfile root missing; skipping orphan reconcile"),e;let r;try{r=QE(t.rootDir,{withFileTypes:!0})}catch(n){return e.errors++,t.logger.warn({runtime_pid_root:t.rootDir,err:n.message},"failed to read runtime pidfile root; skipping orphan reconcile"),e}for(let n of r){if(!n.isDirectory())continue;let o=n.name,i=Ki(t.rootDir,o),a;try{a=QE(i,{withFileTypes:!0})}catch(c){e.errors++,t.logger.warn({runtime_pid_dir:i,daemon_instance:o,err:c.message},"failed to read runtime pidfile instance dir; continuing");continue}for(let c of a){if(!c.isFile()||!c.name.endsWith(".json"))continue;let u=Ki(i,c.name);e.scanned++;try{let l=pZ(u);if(!l){cl(u),e.unlinkedCorrupt++,t.logger.warn({runtime_pidfile:u},"runtime pidfile corrupt; unlinked");continue}let d=mZ(l.pid,t.deps);if(d==="dead"){cl(u),e.unlinkedDead++,t.logger.info({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile pointed at dead process; unlinked");continue}if(d==="eperm"){e.preservedEperm++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process exists but cannot be signaled; preserving");continue}if(d==="error"){e.errors++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process liveness check failed; preserving");continue}if(o===t.selfDaemonInstanceId){e.preservedSelf++;continue}let p=fZ(l.pid,t.deps);if(p==="killed"||p==="gone"){cl(u),e.killedForeign++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o,self_daemon_instance:t.selfDaemonInstanceId,killed:p},"killed runtime child owned by prior daemon instance");continue}p==="eperm"?e.preservedEperm++:e.errors++,t.logger.warn({runtime_pidfile:u,pid:l.pid,daemon_instance:o},"runtime pidfile process could not be SIGKILLed; preserving")}catch(l){e.errors++,t.logger.warn({runtime_pidfile:u,err:l.message},"failed to reconcile runtime pidfile; continuing")}}}return e}function pZ(t){try{let e=JSON.parse(iZ(t,"utf8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.started_at!="number"||!Number.isInteger(e.started_at)||typeof e.conv!="string"||e.conv.length===0||typeof e.agent!="string"||e.agent.length===0||typeof e.runtime!="string"||e.runtime.length===0||typeof e.cmd!="string"||e.cmd.length===0?null:e}catch{return null}}function mZ(t,e){try{return(e?.kill??process.kill)(t,0),"alive"}catch(r){let n=r.code;return n==="EPERM"?"eperm":n==="ESRCH"?"dead":"error"}}function fZ(t,e){try{return(e?.kill??process.kill)(t,"SIGKILL"),"killed"}catch(r){let n=r.code;return n==="ESRCH"?"gone":n==="EPERM"?"eperm":"error"}}function cl(t){try{t0(t)}catch(e){if(e.code!=="ENOENT")throw e}}import{existsSync as ig,mkdirSync as hZ,readFileSync as gZ,renameSync as u0,writeFileSync as _Z}from"node:fs";import{dirname as yZ}from"node:path";var vZ=s.object({proxy_url:s.string().nullable().default(null),proxy_runtimes:s.array(De).default([])}),sg=Object.freeze({proxy_url:null,proxy_runtimes:[]});function l0(t){let e=vZ.parse(t),r=bZ(e.proxy_runtimes);return{proxy_url:e.proxy_url,proxy_runtimes:r}}function Gi(t,e){if(!t)return{...sg};try{let r=gZ(t,"utf8");return l0(JSON.parse(r))}catch(r){return r.code==="ENOENT"?{...sg}:(e?.warn({err:r instanceof Error?r.message:String(r),path:t},"daemon proxy config read failed; falling back to empty config"),{...sg})}}function ag(t,e){let r=l0(e);hZ(yZ(t),{recursive:!0});let n=`${t}.tmp-${process.pid}-${Date.now()}`;return _Z(n,`${JSON.stringify(r,null,2)}
610
+ `,{encoding:"utf8",mode:384}),u0(n,t),r}function cg(t){let e=t.legacyPath;if(!(!e||e===t.targetPath||!ig(e))){if(ig(t.targetPath)){c0(e,t.logger);return}try{let r=Gi(e,t.logger);ag(t.targetPath,r),c0(e,t.logger),t.logger?.info?.({legacy_path:e,target_path:t.targetPath},"daemon proxy config migrated to per-computer profile")}catch(r){t.logger?.warn({err:r instanceof Error?r.message:String(r),legacy_path:e,target_path:t.targetPath},"daemon proxy config migration failed; keeping legacy file untouched")}}}function c0(t,e){if(!ig(t))return;let r=`${t}.migrated`;try{u0(t,r)}catch(n){e?.warn({err:n instanceof Error?n.message:String(n),legacy_path:t,migrated_path:r},"daemon proxy config legacy marker rename failed")}}function bZ(t){let e=[],r=new Set;for(let n of t)r.has(n)||(r.add(n),e.push(n));return e}import{createHash as SZ}from"node:crypto";import{homedir as xZ}from"node:os";import{join as ug}from"node:path";function lg(){return ug(xZ(),".silverhand")}function d0(t,e=lg()){return ug(e,"computers",wZ(t.host_id))}function dg(t,e=lg()){return ug(d0(t,e),"proxy-config.json")}function p0(t,e=lg()){return d0({host_id:t},e)}function wZ(t){return t.replace(/[^A-Za-z0-9_.-]+/g,"_").slice(0,80)||kZ(t)}function kZ(t){return SZ("sha256").update(t).digest("hex").slice(0,12)}import{existsSync as RZ}from"node:fs";import{dirname as PZ,resolve as m0}from"node:path";import{fileURLToPath as EZ}from"node:url";function f0(t){if(t.localLauncher)return t.localLauncher;if(t.serverLauncher)return t.serverLauncher;throw new Error("runtime_start: no silverhand CLI launcher supplied by server and no daemon-local launcher was resolved")}function h0(t={}){let e=t.entryUrl??import.meta.url,r=t.execPath??process.execPath,n=t.exists??RZ,o=PZ(EZ(e)),a=[{entry:m0(o,"cli.js")},{entry:m0(o,"..","silverhand-cli","cli.mjs"),env:{ELECTRON_RUN_AS_NODE:"1"}}].find(c=>n(c.entry));return a?{command:r,args:[a.entry],...a.env?{env:a.env}:{}}:null}function IZ(t,e){if(!t)return null;try{let r=CZ(t,"utf8").trim();return r?new URL(r).origin:null}catch(r){return r.code!=="ENOENT"&&e.warn({filepath:t,err:r.message},"failed to read daemon-local control-plane URL; runtime_start will fail if no outbound binding is attached"),null}}function $Z(t){let e=IZ(t.controlPlaneServerUrlPath,t.logger);if(e)return e;let r=t.registryBinding?.server_origin??null;if(!r)return null;try{let n=new URL(r);if(n.protocol==="http:"||n.protocol==="https:")return n.origin}catch{}return null}async function ul(t){let e=Date.now(),r=n0(e),n=t.runtimePidRootDir===void 0?r0():t.runtimePidRootDir,o=t.daemonIdentityPath===void 0?uy(n):t.daemonIdentityPath,i=t.daemonIdentity!==void 0?t.daemonIdentity??void 0:o===null?void 0:ly(o),a=rc(r,i),c=()=>({event:"ready",...a,socket_path:t.socketPath,daemon_pid:process.pid,started_at:e}),u=t.logger??_y({dir:t.logDir,alsoStderr:t.alsoStderr??!1,base:{component:"silverhand-daemon",daemon_version:fn}}),l=h0();l?Ir(u,{action:"cli_launcher_resolved",pid:process.pid}):t.supervisorFactory&&Ir(u,{action:"cli_launcher_unavailable",pid:process.pid});let d=_g(t.pidFilePath);if(d.status==="conflict"){let E=new Error(`another silverhand-daemon is already running (pid=${d.conflictingPid})`);throw E.code="EALREADY",u.error({pidFilePath:t.pidFilePath,conflictingPid:d.conflictingPid},"refusing to start: pid file already owned by live daemon"),await u.close(),E}if(Ir(u,{action:"pid_claim",pid:process.pid,pid_file_path:t.pidFilePath}),n!==null)try{let E=a0({rootDir:n,selfDaemonInstanceId:r,logger:u});u.info({runtimePidRootDir:n,daemonInstanceId:r,...E},"runtime pidfile orphan reconcile completed")}catch(E){u.warn({runtimePidRootDir:n,daemonInstanceId:r,err:E.message},"runtime pidfile orphan reconcile failed; continuing daemon boot")}let p=()=>{},m=()=>{throw new Error("outbound dispatchCommand invoked before dispatcher was wired")},f=new Cc({logger:u,readyEvent:c,dispatchCommand:E=>m(E)}),_=t.hostConfig?{server_origin:new URL(t.hostConfig.server_url).origin,host_id:t.hostConfig.host_id}:null,g=t.testHooks?.workspaceRegistryStateDir??(o!==null?g0(o):`${AZ()}/.silverhand/daemon`),y=t.testHooks?.silverhandStateRoot??g0(g),S=TZ(y,"workspaces"),x=t.agentHomeRootDir??void 0,w=i?.daemon_id??"local",T=()=>_??f.currentBinding(),v=()=>ft!=null?{server_origin:"local-embedded",host_id:T()?.host_id??w}:T(),P=()=>{if(t.proxyConfigPath)return t.proxyConfigPath;let E=v();if(E==null)return null;let ee=dg(E,y);return ft!=null&&E.host_id!==w&&cg({legacyPath:dg({host_id:w},y),targetPath:ee,logger:u}),cg({legacyPath:t.legacyProxyConfigPath,targetPath:ee,logger:u}),ee},O={homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x,resolveRegularWorkspacePath:E=>{let ee=v();if(ee==null)throw new sr("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let ct=new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});try{return ct.resolve(E)}catch(Xi){throw Xi instanceof ae?new sr(Xi.code==="not_provisioned"?"workspace_not_provisioned":"registry_unavailable",Xi.message):Xi}}},J=t.supervisorFactory?t.supervisorFactory({emit:E=>p(E),logger:u,daemonInstanceId:r,runtimePidRootDir:n,daemonSocketPath:t.socketPath,runtimeStartResolveDeps:O,proxyConfigPath:P,localSilverhandCliLauncher:l,controlPlaneServerUrl:()=>$Z({registryBinding:v(),controlPlaneServerUrlPath:t.controlPlaneServerUrlPath,logger:u})}):void 0,F=new nc({logger:u,startedAt:e,helloResult:a,supervisor:J,hostOutboundAttachHandler:E=>f.attach(E),hostOutboundDetachHandler:()=>f.detach(),hostOutboundReloadHandler:()=>f.reload(),hostProxyConfigGetHandler:()=>({config:Gi(P(),u)}),hostProxyConfigSetHandler:E=>{let ee=P();if(!ee)throw new Error("host proxy config path is not configured");return{config:ag(ee,E)}},agentMaterializeHandler:async E=>{let ee=t.testHooks?.agentMaterializeFaultInjector?.(E);if(ee)throw ee;return ep(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},workspaceProvisionHandler:async E=>{let ee=v();if(ee==null)throw new St("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let ct=new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return np(E,{registry:ct,logger:u})},agentWorkspaceIndexHandler:async E=>{let ee=v();if(ee==null)throw new wn("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let ct=new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return op(E,{registry:ct,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentWorkspaceTreeHandler:async E=>{let ee=E.workspace_id?v():null,ct=ee?new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S}):void 0;return up(E,{registry:ct,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentWorkspaceFileReadHandler:async E=>{let ee=E.workspace_id?v():null,ct=ee?new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S}):void 0;return dp(E,{registry:ct,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentL2SeedHandler:async E=>{let ee=v();if(ee==null)throw new xt("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let ct=new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return sp(E,{registry:ct})},agentFilesPurgeHandler:async E=>{let ee=v();if(ee==null)throw new Or("registry_unavailable","daemon not attached to a control plane; cannot resolve workspace registry binding");let ct=new Ot({stateDir:g,binding:ee,silverhandStateRoot:y,legacyWorkspacesRoot:S});return ip(E,{registry:ct,homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})},agentProfileMcpReadHandler:async E=>eb(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x}),agentProfileMcpWriteHandler:async E=>tb(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x}),mcpProbeHandler:async E=>YE(E,{homeDir:t.testHooks?.agentMaterializeHomeDir,agentHomeRootDir:x})});m=E=>F.dispatch(E.id,String(E.kind),E.params);let ie=new sc({socketPath:t.socketPath,dispatcher:F,logger:u}),mt=t.hostConfig?new vo({config:t.hostConfig,logger:u,readyEvent:c,dispatchCommand:E=>m(E)}):null,ft=t.localOutboundSocketPath!=null?new Tc({socketPath:t.localOutboundSocketPath,dispatchCommand:E=>m(E),logger:u,readyEvent:c}):null;p=E=>{ie.broadcast(E),f.sendEvent(E),mt?.sendEvent(E),ft?.broadcast(E)};try{await ie.start()}catch(E){throw u.error({err:E.message,socketPath:t.socketPath},"failed to bind socket"),ea(t.pidFilePath),await u.close(),E}if(ft)try{await ft.start()}catch(E){throw u.error({err:E.message,socketPath:t.localOutboundSocketPath},"failed to bind local outbound frame socket"),await ie.stop("local_outbound_bind_failed"),ea(t.pidFilePath),await u.close(),E}if((t.writeStdoutHandshake??!0)&&process.stdout.write(Yt(c())),u.info({socketPath:t.socketPath,pidFilePath:t.pidFilePath,logFile:u.filePath},"daemon ready"),Ir(u,{action:"boot",pid:process.pid,socket_path:t.socketPath,pid_file_path:t.pidFilePath}),t.hostConfigPath){let E=f.attach({config_path:t.hostConfigPath});E.attached||u.warn({kind:"outbound_supervisor",action:"cli_auto_attach_failed",reason:E.reason,message:E.message},"daemon outbound CLI auto-attach failed; outbound is inactive until host_outbound_attach IPC arrives")}mt?.start();let Gr=!1,Tt=async E=>{if(!Gr){if(Gr=!0,Ir(u,{action:"shutting_down",pid:process.pid}),f.sendEvent({event:"shutting_down",reason:E}),f.stop(E),mt?.stop(E),ft)try{await ft.stop()}catch(ee){u.error({err:ee.message},"local outbound server stop threw; continuing teardown")}try{await ie.stop(E)}catch(ee){u.error({err:ee.message},"server.stop threw; continuing teardown")}ea(t.pidFilePath),u.info({reason:E},"daemon stopped"),await u.close()}};return(t.installSignals??!0)&&yg(u,async E=>{await Tt(E)}),{socketPath:t.socketPath,pidFilePath:t.pidFilePath,logger:u,broadcast:E=>p(E),stop:Tt}}import{spawn as i4}from"node:child_process";import{setTimeout as Kn}from"node:timers";import{randomUUID as a4}from"node:crypto";import{stat as c4,writeFile as u4}from"node:fs/promises";import{randomUUID as OZ}from"node:crypto";function dl(t,e){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]},...e?{session_id:e}:{}})}function pl(t,e={}){let r=t.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[],i=e.classifyError;switch(n.type){case"system":{n.subtype==="init"&&typeof n.session_id=="string"&&o.push({kind:"session_init",sessionId:n.session_id}),n.subtype==="api_error"&&o.push(zZ(n,e.runtimeLabel)),n.subtype==="status"&&n.status==="compacting"&&o.push({kind:"compaction_started"}),n.subtype==="compact_boundary"&&o.push({kind:"compaction_finished"});break}case"assistant":{let a=n.message?.content;if(Array.isArray(a))for(let c of a)c?.type==="thinking"&&typeof c.thinking=="string"?o.push({kind:"thinking",text:c.thinking}):c?.type==="text"&&typeof c.text=="string"?o.push({kind:"text",text:c.text}):c?.type==="tool_use"&&o.push({kind:"tool_call",name:typeof c.name=="string"?c.name:"unknown_tool",input:c.input,toolCallId:typeof c.id=="string"?c.id:void 0});break}case"user":{let a=n.message?.content;if(Array.isArray(a))for(let c of a)c?.type==="tool_result"&&o.push({kind:"tool_output",name:typeof c.name=="string"?c.name:void 0,toolCallId:typeof c.tool_use_id=="string"?c.tool_use_id:void 0});break}case"result":{let a=typeof n.subtype=="string"?n.subtype:"success",c=typeof n.stop_reason=="string"?n.stop_reason:null,u=l=>{if(c!=="max_tokens"){let d=ll(n)||l;o.push({kind:"error",message:d,...i?i(d):{}})}};switch(a){case"success":n.is_error&&u("Execution failed");break;case"error_during_execution":u("Execution failed");break;case"error_max_budget_usd":o.push({kind:"error",message:ll(n)||"Budget limit exceeded"});break;case"error_max_turns":o.push({kind:"error",message:ll(n)||"Max turns exceeded"});break;case"error_max_structured_output_retries":o.push({kind:"error",message:ll(n)||"Structured output retries exceeded"});break}o.push({kind:"turn_end",sessionId:typeof n.session_id=="string"?n.session_id:void 0});break}default:break}return o}function ml(t){let e=t.trim();if(!e)return null;let r;try{r=JSON.parse(e)}catch{return null}return r?.type==="system"&&r.subtype==="init"&&typeof r.session_id=="string"?"session_ready":r&&typeof r=="object"?"protocol_ready":null}function zZ(t,e){let r=typeof t.error?.cause?.code=="string"?t.error.cause.code:typeof t.cause?.code=="string"?t.cause.code:null,n=typeof t.retryAttempt=="number"&&Number.isFinite(t.retryAttempt)?t.retryAttempt:null,o=r==="ConnectionRefused"?"api_connection_refused":"api_error",i=e?`${e} API`:"API",a=r==="ConnectionRefused"?`${i} gateway unreachable; retrying`:`${i} request failed; retrying`;return{kind:"error",code:o,message:n!==null?`${a} (attempt ${n})`:a}}function ll(t){let e=[];if(Array.isArray(t.errors))for(let r of t.errors)typeof r=="string"&&r.trim()&&e.push(r.trim());return typeof t.result=="string"&&t.result.trim()&&e.push(t.result.trim()),e.join(" | ")}var DZ=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(","),fl=class{kind="claude";binary="claude";kickoffMode="requires_first_message";busyDeliveryMode="gated";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=["--dangerously-skip-permissions","--allow-dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",e.model||"opus","--disallowed-tools",DZ,"--append-system-prompt-file",e.systemPromptPath];return e.cliSessionId&&r.push("--resume",e.cliSessionId),r}applyEnv(e){let r={...e};return delete r.CLAUDECODE,r}encodeStdinMessage(e,r){return dl(e,r)}encodeInterruptControl(){return JSON.stringify({type:"control_request",request_id:OZ(),request:{subtype:"interrupt"}})}parseLine(e){return pl(e,{runtimeLabel:"Claude",classifyError:MZ})}classifyInitProgress(e){return ml(e)}};function MZ(t){return t.includes("No conversation found with session ID:")||t.includes("--resume requires a valid session ID")?{code:"session_not_found",fatal:!0}:{}}import{execSync as _0}from"node:child_process";import{existsSync as NZ,readFileSync as jZ}from"node:fs";import{join as LZ}from"node:path";var hl=class{kind="codex";binary="codex";kickoffMode="self_inits";busyDeliveryMode="direct";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=60*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;io=null;requestId=0;threadId=null;activeTurnId=null;initializeRequestId=null;pendingThreadRequest=null;pendingInitialPrompt=null;initialTurnStarted=!1;sessionAnnounced=!1;streamedAgentMessageIds=new Set;streamedReasoningIds=new Set;pendingFileChangeCounts=new Map;pendingWebSearchIds=new Set;buildArgs(e){let r=["app-server","--listen","stdio://"];return e.reasoningEffort&&r.push("-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`),e.fastMode===!0?r.push("--enable","fast_mode"):e.fastMode===!1&&r.push("--disable","fast_mode"),r}applyEnv(e){return{...e,NO_COLOR:"1"}}bindIO(e){HZ(e.spawnCtx.workspacePath),this.io=e,this.threadId=null,this.pendingInitialPrompt=e.spawnCtx.initialPrompt||null;let r=jZ(e.spawnCtx.systemPromptPath,"utf-8");this.pendingThreadRequest=this.buildThreadRequest(e.spawnCtx,r),queueMicrotask(()=>{this.initializeRequestId=this.sendRequest("initialize",{clientInfo:{name:"silverhand",version:"1.0.0"},capabilities:{experimentalApi:!0}})})}encodeStdinMessage(e,r){return this.threadId?this.activeTurnId?JSON.stringify({jsonrpc:"2.0",id:this.nextRequestId(),method:"turn/steer",params:{threadId:this.threadId,expectedTurnId:this.activeTurnId,input:[{type:"text",text:e}]}}):JSON.stringify({jsonrpc:"2.0",id:this.nextRequestId(),method:"turn/start",params:{threadId:this.threadId,input:[{type:"text",text:e}]}}):null}readyToEncode(){return this.threadId!==null}encodeInterruptControl(){return null}parseLine(e){let r=e.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[];if(n.result!==void 0){if(n.id===this.initializeRequestId)return this.initializeRequestId=null,this.sendNotification("initialized",{}),this.pendingThreadRequest&&(this.sendRequest(this.pendingThreadRequest.method,this.pendingThreadRequest.params),this.pendingThreadRequest=null),o;let i=n.result?.thread;if(i&&typeof i.id=="string")return this.handleThreadReady(i.id,o),o;let a=n.result?.turn;return a&&typeof a.id=="string"?(this.activeTurnId=a.id,o):(typeof n.result?.turnId=="string"&&(this.activeTurnId=n.result.turnId),o)}if(n.error){n.id===this.initializeRequestId&&(this.initializeRequestId=null,this.pendingThreadRequest=null);let i=typeof n.error?.message=="string"?n.error.message:"Codex app-server request failed";return o.push({kind:"error",message:i,...y0(i)}),o}switch(n.method){case"thread/started":{let i=n.params?.thread?.id;typeof i=="string"&&this.handleThreadReady(i,o);break}case"turn/started":{let i=n.params?.turn?.id;typeof i=="string"&&(this.activeTurnId=i),o.push({kind:"thinking",text:""});break}case"item/agentMessage/delta":{let i=n.params?.delta,a=n.params?.itemId;typeof a=="string"&&this.streamedAgentMessageIds.add(a),typeof i=="string"&&i.length>0&&o.push({kind:"text",text:i});break}case"item/reasoning/summaryTextDelta":case"item/reasoning/textDelta":{let i=n.params?.delta,a=n.params?.itemId;typeof a=="string"&&this.streamedReasoningIds.add(a),typeof i=="string"&&i.length>0&&o.push({kind:"thinking",text:i});break}case"item/started":case"item/completed":{let i=n.params?.item;if(!i||typeof i!="object"||typeof i.type!="string")break;this.handleItemEvent(n.method,i,o);break}case"turn/completed":{let i=n.params?.turn;i?.status==="failed"&&typeof i?.error?.message=="string"&&o.push({kind:"error",message:i.error.message}),this.activeTurnId=null,this.streamedAgentMessageIds.clear(),this.streamedReasoningIds.clear(),this.pendingFileChangeCounts.clear(),this.pendingWebSearchIds.clear(),o.push({kind:"turn_end",sessionId:this.threadId??void 0});break}case"error":{let i=n.params,a=typeof i?.message=="string"?i.message:typeof i?.error?.message=="string"?i.error.message:"Unknown Codex app-server error";o.push({kind:"error",message:a,...y0(a)});break}}return o}classifyInitProgress(e){let r=e.trim();if(!r)return null;let n;try{n=JSON.parse(r)}catch{return null}if(!n||typeof n!="object"||n.jsonrpc!=="2.0"&&!("method"in n)&&!("result"in n)&&!("error"in n))return null;let o=n.result?.thread;return o&&typeof o.id=="string"||n.method==="thread/started"&&typeof n.params?.thread?.id=="string"?"session_ready":"protocol_ready"}handleItemEvent(e,r,n){let o=e==="item/started",i=e==="item/completed";switch(r.type){case"reasoning":if(i&&typeof r.id=="string"&&!this.streamedReasoningIds.has(r.id)){let a=FZ(r);a&&n.push({kind:"thinking",text:a})}i&&typeof r.id=="string"&&this.streamedReasoningIds.delete(r.id);break;case"agentMessage":i&&typeof r.id=="string"&&!this.streamedAgentMessageIds.has(r.id)&&typeof r.text=="string"&&r.text.length>0&&n.push({kind:"text",text:r.text}),i&&typeof r.id=="string"&&this.streamedAgentMessageIds.delete(r.id);break;case"commandExecution":o&&typeof r.command=="string"&&n.push({kind:"tool_call",name:"shell",input:{command:r.command}}),i&&n.push({kind:"tool_output",name:"shell"});break;case"contextCompaction":o&&n.push({kind:"compaction_started"}),i&&n.push({kind:"compaction_finished"});break;case"fileChange":if(o&&Array.isArray(r.changes)){for(let a of r.changes)n.push({kind:"tool_call",name:"file_change",input:{path:a?.path,kind:a?.kind}});typeof r.id=="string"&&this.pendingFileChangeCounts.set(r.id,r.changes.length)}if(i&&typeof r.id=="string"){let a=this.pendingFileChangeCounts.get(r.id)??0;for(let c=0;c<a;c+=1)n.push({kind:"tool_output",name:"file_change"});this.pendingFileChangeCounts.delete(r.id)}break;case"mcpToolCall":{let a=r.server==="chat"?`mcp_chat_${r.tool}`:`mcp_${r.server}_${r.tool}`;o&&n.push({kind:"tool_call",name:a,input:r.arguments}),i&&n.push({kind:"tool_output",name:a});break}case"webSearch":if(o&&(n.push({kind:"tool_call",name:"web_search",input:{query:r.query}}),typeof r.id=="string"&&this.pendingWebSearchIds.add(r.id)),i){let a=typeof r.id=="string"?r.id:null;a&&this.pendingWebSearchIds.delete(a)&&n.push({kind:"tool_output",name:"web_search"})}break}}handleThreadReady(e,r){this.threadId=e,this.sessionAnnounced||(r.push({kind:"session_init",sessionId:e}),this.sessionAnnounced=!0),this.startInitialTurn()}startInitialTurn(){if(this.initialTurnStarted||!this.pendingInitialPrompt||!this.threadId)return;this.initialTurnStarted=!0;let e=this.pendingInitialPrompt;this.pendingInitialPrompt=null,this.sendRequest("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})}buildThreadRequest(e,r){let n={cwd:e.workspacePath,approvalPolicy:"never",sandbox:"danger-full-access",developerInstructions:r};return e.model?n.model=e.model:n.model="gpt-5.5",e.cliSessionId?{method:"thread/resume",params:{threadId:e.cliSessionId,...n}}:{method:"thread/start",params:n}}nextRequestId(){return this.requestId+=1,this.requestId}sendRequest(e,r){let n=this.nextRequestId();return this.io?.writeLine(JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:r})),n}sendNotification(e,r){this.io?.writeLine(JSON.stringify({jsonrpc:"2.0",method:e,params:r}))}};function y0(t){return/thread not found/i.test(t)?{code:"thread_not_found",fatal:!0}:{}}function FZ(t){let e=Array.isArray(t.summary)?t.summary.filter(n=>typeof n=="string"):[],r=Array.isArray(t.content)?t.content.filter(n=>typeof n=="string"):[];return[...e,...r].join(`
611
+ `).trim()}function HZ(t){NZ(LZ(t,".git"))||(_0("git init",{cwd:t,stdio:"pipe"}),_0("git -c user.name=silverhand -c user.email=silverhand@local -c commit.gpgsign=false add -A && git -c user.name=silverhand -c user.email=silverhand@local -c commit.gpgsign=false commit --allow-empty -m 'init'",{cwd:t,stdio:"pipe"}))}import{readFileSync as UZ}from"node:fs";var gl=class{kind="cursor";binary="cursor-agent";kickoffMode="self_inits";busyDeliveryMode="none";oneShot=!0;supportsNativeStandingPrompt=!1;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=["--print","--output-format","stream-json","--yolo","--trust"];return e.model&&r.push("--model",e.model),e.cliSessionId&&r.push("--resume",e.cliSessionId),r.push(qZ(e)),r}applyEnv(e){return{...e,FORCE_COLOR:"0",NO_COLOR:"1"}}encodeStdinMessage(e,r){return null}encodeInterruptControl(){return null}parseLine(e){let r=e.trim();if(!r)return[];let n;try{n=JSON.parse(r)}catch{return[{kind:"unknown",raw:r}]}let o=[];switch(n.type){case"system":n.subtype==="init"&&typeof n.session_id=="string"?o.push({kind:"session_init",sessionId:n.session_id}):n.subtype==="status"&&n.status==="compacting"?o.push({kind:"compaction_started"}):n.subtype==="compact_boundary"&&o.push({kind:"compaction_finished"});break;case"assistant":{let i=n.message?.content;if(Array.isArray(i))for(let a of i)a?.type==="thinking"&&typeof a.thinking=="string"?o.push({kind:"thinking",text:a.thinking}):a?.type==="text"&&typeof a.text=="string"?o.push({kind:"text",text:a.text}):a?.type==="tool_use"&&o.push({kind:"tool_call",name:typeof a.name=="string"?a.name:"unknown_tool",input:a.input,toolCallId:typeof a.id=="string"?a.id:void 0});break}case"result":{if((typeof n.subtype=="string"?n.subtype:"success")!=="success"||n.is_error){let a=[];if(Array.isArray(n.errors))for(let c of n.errors)typeof c=="string"&&c.trim()&&a.push(c.trim());typeof n.result=="string"&&n.result.trim()&&a.push(n.result.trim()),o.push({kind:"error",message:a.join(" | ")||"Execution failed"})}o.push({kind:"turn_end",sessionId:typeof n.session_id=="string"?n.session_id:void 0});break}default:break}return o}classifyInitProgress(e){let r=e.trim();if(!r)return null;let n;try{n=JSON.parse(r)}catch{return null}return n?.type==="system"&&n.subtype==="init"&&typeof n.session_id=="string"?"session_ready":n&&typeof n=="object"?"protocol_ready":null}};function qZ(t){let e=UZ(t.systemPromptPath,"utf-8"),r=t.initialPrompt.trim()||"You are now active in this channel. Read your MEMORY.md and stand by for further instructions.";return`${e}
610
612
 
611
613
  ---
612
614
 
613
- ${r}`}import{readFileSync as lZ}from"node:fs";var dZ=["EnterPlanMode","ExitPlanMode","CronCreate","CronList","CronDelete","CreateGoal","GetGoal","UpdateGoal"].join(","),ml=class{kind="qoder";binary="qodercli";kickoffMode="requires_first_message";busyDeliveryMode="gated";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=lZ(e.systemPromptPath,"utf-8"),n=["--dangerously-skip-permissions","--permission-mode","bypass_permissions","--output-format","stream-json","--input-format","stream-json","--disallowed-tools",dZ,"--append-system-prompt",r];return e.model&&n.push("--model",e.model),e.reasoningEffort&&n.push("--reasoning-effort",e.reasoningEffort),e.cliSessionId&&n.push("--resume",e.cliSessionId),n}applyEnv(e){return{...e}}encodeStdinMessage(e,r){return al(e,r)}encodeInterruptControl(){return null}parseLine(e){return cl(e,{runtimeLabel:"Qoder"})}classifyInitProgress(e){return ul(e)}};var pZ={claude:()=>new ll,codex:()=>new dl,cursor:()=>new pl,qoder:()=>new ml};function a0(t){let e=pZ[t];if(!e)throw new Error(`no driver registered for runtime "${t}"`);return e()}import{spawn as u0}from"node:child_process";import{stat as mZ}from"node:fs/promises";var c0={claude:"claude",codex:"codex",cursor:"cursor-agent",gemini:"gemini",qoder:"qodercli"},fZ={codex:{darwin:["/Applications/Codex.app/Contents/Resources/codex"]}};async function hZ(t){try{return(await mZ(t)).isFile()}catch{return!1}}async function gZ(t){return new Promise(e=>{let r=u0("which",[t],{stdio:["ignore","pipe","ignore"]}),n="";r.stdout.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("close",o=>{let i=n.trim();e(o===0&&i?i:null)})})}async function _Z(t,e){let r=fZ[t]?.[process.platform]??[];for(let n of r)if(await hZ(n))return n;return gZ(e)}async function yZ(t){return new Promise(e=>{let r=u0(t,["--version"],{stdio:["ignore","pipe","pipe"]}),n="",o="";r.stdout.on("data",a=>{n+=a.toString()}),r.stderr.on("data",a=>{o+=a.toString()}),r.on("error",()=>e(null));let i=setTimeout(()=>{r.kill(),e(null)},3e4);r.on("close",()=>{clearTimeout(i);let a=(n||o).trim(),c=a.match(/\d+\.\d+(?:\.\d+)?/);e(c?c[0]:a.split(`
614
- `)[0]?.trim()??null)})})}async function l0(){let t=Object.keys(c0);return await Promise.all(t.map(async r=>{let n=c0[r],o=await _Z(r,n);if(!o)return{kind:r,installed:!1,binary:null,version:null};let i=await yZ(o);return{kind:r,installed:!0,binary:o,version:i}}))}import{readFile as d0}from"node:fs/promises";import{join as fl}from"node:path";var vZ=16*1024;async function bZ(t,e){let r;try{r=await d0(t)}catch(o){let i=o?.code;return i==="ENOENT"?{kind:"missing"}:{kind:"unreadable",reason:i??o?.message??"unknown error"}}if(r.byteLength<=e)return{kind:"present",body:r.toString("utf-8")};let n=e;for(;n>0&&r[n]!==void 0&&(r[n]&192)===128;)n-=1;return{kind:"present",body:`${r.subarray(0,n).toString("utf-8")}
615
- \u2026(truncated)`}}async function p0(t){let e=await d0(fl(t.agent.home_dir,"system_prompt.md"),"utf-8").catch(()=>""),r=await bZ(fl(m0(t.workspace,t.agent.id),"MEMORY.md"),vZ);return{agentId:t.agent.id,agentName:t.agent.name,activeProfileDir:xZ(t.workspace,t.agent.id),roleSystemPrompt:e,currentMemory:r,workspaceMemoryIndex:SZ(t),sessionContext:{conversationId:t.session.conversation_id,channelName:t.session.kind==="dm_channel"?t.session.title:t.workspace.name,channelKind:t.session.kind==="dm_channel"?"dm":"regular",sessionTitle:t.session.title,members:t.session.members,selfAgentId:t.agent.id}}}function SZ(t){return t.workspace_memory_index.map(e=>{let r=e.id===t.workspace.id,n=e.kind==="agent_home"?`${e.name} (DM)`:e.name;return{label:r?`${n} (current)`:n,memoryPath:fl(m0(e,t.agent.id),"MEMORY.md")}})}function xZ(t,e){return t.kind==="agent_home"?".":`./.silverhand/agents/${e}`}function m0(t,e){return t.kind==="agent_home"?t.path:fl(t.path,".silverhand","agents",e)}import{delimiter as wZ}from"node:path";function f0(t){let e=t.options,r=t.driver.applyEnv(t.baseProcessEnv??process.env);if(t.proxyConfig?.proxy_url&&t.proxyConfig.proxy_runtimes.includes(e.driver.kind)){let i=$_(t.proxyConfig.proxy_url);i&&(r={...r,...i})}let n=r.PATH??process.env.PATH??"",o=t.controlPlaneServerUrl;if(!o)throw new Error("runtime_start: no silverhand server URL supplied by server and no daemon-local control-plane URL is attached");return{...r,[f_]:t.conversationId,[h_]:t.agentId,[g_]:o,[__]:e.env_policy.silverhand.auth_token,...t.daemonSocketPath?{[v_]:t.daemonSocketPath}:{},...t.lastDeliveredSeqPath?{[y_]:t.lastDeliveredSeqPath}:{},PATH:n?`${t.binDir}${wZ}${n}`:t.binDir}}import{chmod as kZ,mkdir as h0,mkdtemp as RZ,rm as PZ,writeFile as g0}from"node:fs/promises";import{tmpdir as EZ}from"node:os";import{join as ls}from"node:path";async function y0(t){let e=ls(EZ(),"silverhand",t.conversationId,t.agentId);await h0(e,{recursive:!0});let r=await RZ(ls(e,"spawn-")),n=ls(r,"system-prompt.md"),o=ls(r,"last-delivered-seq"),i=ls(r,"bin"),a=ls(i,"silverhand"),c=CZ(t.silverhandCli);return await Promise.all([h0(i,{recursive:!0}),g0(n,t.systemPromptText,"utf-8")]),await g0(a,c,"utf-8"),await kZ(a,493),{systemPromptPath:n,lastDeliveredSeqPath:o,binDir:i,dir:r,cleanup:async()=>{await PZ(r,{recursive:!0,force:!0}).catch(()=>{})}}}function CZ(t){let e=Object.entries(t.env??{}).map(([n,o])=>`export ${TZ(n)}=${_0(o)}`).join(`
616
- `),r=[t.command,...t.args].map(n=>_0(n)).join(" ");return["#!/bin/sh","set -eu",e,`exec ${r} "$@"`,""].filter(n=>n.length>0).join(`
617
- `)}function TZ(t){if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))return t;throw new Error(`invalid env var name for silverhand shim: ${t}`)}function _0(t){return`'${t.replace(/'/g,"'\\''")}'`}import{readFile as AZ,writeFile as IZ}from"node:fs/promises";import{join as v0}from"node:path";async function b0(t){let{runtimeKind:e,agentHomeDir:r,spawnDir:n,agentId:o,logger:i}=t,a=v0(r,Tr),c;try{c=await AZ(a,"utf-8")}catch(d){return d?.code==="ENOENT"?{args:[]}:(i.warn({agentId:o,runtimeKind:e,filePath:a,err:String(d)},"profile MCP: failed to read mcp.json; skipping the entire MCP layer (agent still spawns)"),{args:[]})}let u=io(c);if(!u.ok)return i.warn({agentId:o,runtimeKind:e,filePath:a,error:u.error},"profile MCP: mcp.json failed validation; skipping the entire MCP layer (agent still spawns)"),{args:[]};let l=Object.keys(u.config.mcpServers);if(l.length===0)return{args:[]};for(let d of l)i.debug({agentId:o,runtimeKind:e,mapping:`profile/${d} -> ${wa("profile",d)}`},"profile MCP: loading server");try{switch(e){case"claude":case"qoder":{let d=P_(u.config,"profile");if(!d)return{args:[]};let p=v0(n,"profile-mcp.json");return await IZ(p,JSON.stringify(d,null,2),"utf-8"),{args:["--mcp-config",p]}}case"codex":return{args:E_(u.config,"profile").flatMap(p=>["-c",p])};default:return i.warn({agentId:o,runtimeKind:e,servers:l.length},"profile MCP: runtime has no MCP adapter; skipping the layer"),{args:[]}}}catch(d){return i.warn({agentId:o,runtimeKind:e,filePath:a,err:String(d)},"profile MCP: failed to build runtime config; skipping the entire MCP layer (agent still spawns)"),{args:[]}}}var MZ=5e3,NZ=1e4,jZ=30*1e3,LZ=300*1e3,FZ=30*1e3,HZ=1,UZ=3,qZ=300*1e3,WZ=300*1e3,ug=200,S0=ug*4,ZZ="silverhand message send";function dt(t,e){return`${t}\0${e}`}function ig(t){return Number.isSafeInteger(t)&&t!==void 0&&t>0?t:null}var Ji="main",BZ=4096,hl={kind:"channel"};function lg(t){return[...new Set(t)].sort()}function VZ(t){return t.startsWith("thread:")?t.slice(7):null}function x0(t){switch(t.kind){case"thread":return[t.streamKey];case"ambiguous":return[...t.streamKeys];case"channel":return[]}}function KZ(t){let e=[...lg(t).flatMap(r=>{let n=VZ(r);return n?[`thread:${n}`]:[]}),"channel"];return JSON.stringify({error:{code:"validation_error",message:"bare message send has an ambiguous default target; rerun with an explicit --target",details:{subkind:"ambiguous_default_target",candidate_targets:e,hint:"Use --target thread:<id> for one listed thread, or --target channel for the main line."}}})}function ag(t){return t?`thread:${t}`:Ji}function w0(t,e){return`thread:${e??t}`}function GZ(t){return t.kind==="thinking"||t.kind==="text"||t.kind==="tool_call"||t.kind==="error"&&t.fatal!==!0}function JZ(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function YZ(t){let r=JZ(t)?.error;if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r.details;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n;if(o.subkind!=="message_stale")return null;let i=o.stale_event_id,a=o.current_seq;return typeof i!="string"||i.length===0||typeof a!="number"||!Number.isSafeInteger(a)||a<=0?null:{id:i,currentSeq:a}}async function k0(t){try{return await t.text()}catch{return""}}var ds=class{handles=new Map;emit;logger;runtimeStartResolveDeps;driverFor;resolveBinary;spawnFn;now;sigtermToSigkillMs;sigkillTimeoutMs;daemonInstanceId;runtimePidRootDir;proxyConfigPath;localSilverhandCliLauncher;controlPlaneServerUrl;daemonSocketPath;initRetryStates=new Map;lifecycleTails=new Map;initWatchdogMs;initLivenessSilenceMs;initPreProtocolCapMs;initPostProtocolMs;initMaxRetries;initFailureCooldownThreshold;initFailureCooldownMs;compactionStaleMs;emitRawRuntimeOutput;constructor(e){this.emit=e.emit,this.logger=e.logger,this.runtimeStartResolveDeps=e.runtimeStartResolveDeps,this.driverFor=e.driverFor??a0,this.resolveBinary=e.resolveBinary??r4,this.spawnFn=e.spawnFn??$Z,this.now=e.now??Date.now,this.sigtermToSigkillMs=e.sigtermToSigkillMs??MZ,this.sigkillTimeoutMs=e.sigkillTimeoutMs??NZ,this.daemonInstanceId=e.daemonInstanceId??null,this.runtimePidRootDir=e.runtimePidRootDir??null;let r=e.proxyConfigPath??null;this.proxyConfigPath=typeof r=="function"?r:()=>r,this.localSilverhandCliLauncher=e.localSilverhandCliLauncher??null,this.controlPlaneServerUrl=e.controlPlaneServerUrl??(()=>null),this.daemonSocketPath=e.daemonSocketPath??null,this.initWatchdogMs=e.initWatchdogMs??null,this.initLivenessSilenceMs=e.initLivenessSilenceMs,this.initPreProtocolCapMs=e.initPreProtocolCapMs,this.initPostProtocolMs=e.initPostProtocolMs,this.initMaxRetries=e.initMaxRetries??HZ,this.initFailureCooldownThreshold=e.initFailureCooldownThreshold??UZ,this.initFailureCooldownMs=e.initFailureCooldownMs??qZ,this.compactionStaleMs=e.compactionStaleMs??WZ,this.emitRawRuntimeOutput=e.emitRawRuntimeOutput??!1}recordObservedStream(e,r,n,o){let i=ig(n);if(i===null)return;let a=ga(i),c=e.observedSeqByStream.get(r);c!==void 0&&c>=a||(e.observedSeqByStream.set(r,a),this.logger.warn({kind:"process",action:"freshness_observed_seq_advanced",conversationId:e.conversationId,agent_id:e.agentId,source:o,stream_key:r,previous_seq:c??null,observed_seq:a},"runtime freshness observed seq advanced"))}advanceObservedStream(e,r,n,o){this.recordObservedStream(e,r,n,o),ig(n)!==null&&(e.inputTurnActive=!0)}queueAdmissionStream(e,r,n,o){let i=ig(n);if(i===null)return;let a=ga(i),c=e.pendingAdmissionSeqByStream.get(r);c!==void 0&&c>=a||(e.pendingAdmissionSeqByStream.set(r,a),this.logger.warn({kind:"process",action:"freshness_pending_admission_queued",conversationId:e.conversationId,agent_id:e.agentId,source:o,stream_key:r,previous_pending_seq:c??null,pending_admission_seq:a},"runtime freshness pending admission queued"))}admitPendingSeqForNewTurn(e,r){if(e.pendingAdmissionSeqByStream.size>0){let n=[...e.pendingAdmissionSeqByStream.entries()];e.pendingAdmissionSeqByStream.clear();for(let[o,i]of n)this.advanceObservedStream(e,o,i,r)}e.pendingDefaultReplyTarget!==void 0&&(e.defaultReplyTarget=e.pendingDefaultReplyTarget,e.pendingDefaultReplyTarget=void 0)}rememberReplyTargetStream(e,r,n){let o=e.replyTargetStreamByMessageId;for(o.delete(r),o.set(r,n);o.size>BZ;){let i=o.keys().next().value;if(i===void 0)break;o.delete(i)}}inferDefaultReplyTarget(e){if(!e||e.length===0)return;let r=new Map,n=!1;for(let c of e){if(c.delivery_kind!=="turn"||(n=!0,!c.thread_root_id))continue;let u=ag(c.thread_root_id),l=r.get(u);(!l||c.seq>=l.seq)&&r.set(u,c)}if(!n)return;if(r.size===0)return hl;if(r.size>1)return{kind:"ambiguous",streamKeys:[...r.keys()].sort()};let o=r.entries().next().value;if(!o)return;let[i,a]=o;return{kind:"thread",messageId:a.message_id,streamKey:i}}mergePendingDefaultReplyTarget(e,r){if(r===void 0)return;let n=e.pendingDefaultReplyTarget;if(n===void 0){e.pendingDefaultReplyTarget=r;return}if(n.kind==="ambiguous"||r.kind==="ambiguous"){let o=[...x0(n),...x0(r)];e.pendingDefaultReplyTarget=o.length===0?{kind:"ambiguous",streamKeys:[]}:{kind:"ambiguous",streamKeys:lg(o)};return}if(n.kind==="channel"){e.pendingDefaultReplyTarget=r;return}if(r.kind==="channel"){e.pendingDefaultReplyTarget=n;return}e.pendingDefaultReplyTarget=n.streamKey===r.streamKey?r:{kind:"ambiguous",streamKeys:lg([n.streamKey,r.streamKey])}}effectiveMessageTarget(e,r){if(r.reply_to_message_id!==void 0)return{kind:"thread",messageId:r.reply_to_message_id};let n=r.target;return n&&typeof n=="object"&&"kind"in n?n.kind==="thread"?{kind:"thread",messageId:n.message_id}:{kind:"channel"}:n!==void 0?{kind:"legacy",target:n}:e.pendingDefaultReplyTarget?e.pendingDefaultReplyTarget.kind==="ambiguous"?{kind:"ambiguous",streamKeys:e.pendingDefaultReplyTarget.streamKeys}:e.pendingDefaultReplyTarget.kind==="channel"?{kind:"channel"}:{kind:"thread",messageId:e.pendingDefaultReplyTarget.messageId,source:"pending_default"}:e.defaultReplyTarget.kind==="ambiguous"?{kind:"ambiguous",streamKeys:e.defaultReplyTarget.streamKeys}:e.defaultReplyTarget.kind==="thread"?{kind:"thread",messageId:e.defaultReplyTarget.messageId,source:"current_default"}:{kind:"channel"}}admitDeliveryBatch(e,r,n,o,i){let a=this.inferDefaultReplyTarget(r);if(o?(e.defaultReplyTarget=a??hl,e.pendingDefaultReplyTarget=void 0):this.mergePendingDefaultReplyTarget(e,a),r&&r.length>0){for(let c of r){this.rememberReplyTargetStream(e,c.message_id,w0(c.message_id,c.thread_root_id));let u=ag(c.thread_root_id);o?this.advanceObservedStream(e,u,c.seq,i):this.queueAdmissionStream(e,u,c.seq,i)}return}o?this.advanceObservedStream(e,Ji,n,i):this.queueAdmissionStream(e,Ji,n,i)}assertDeliveryMetadataConsistent(e,r,n,o,i){if(!o)return;let a=new Set(n),c=new Set(o.map(l=>l.delivery_id)),u=a.size!==c.size;if(!u){for(let l of a)if(!c.has(l)){u=!0;break}}if(u)throw this.logger.error({kind:"process",action:"delivery_metadata_mismatch",conversationId:e,agent_id:r,context:i,delivery_ids:[...a],metadata_ids:[...c]},"delivery metadata id-set does not match delivery_ids (backend bug)"),new Error(`delivery metadata mismatch in ${i}: delivery_ids=[${[...a].join(",")}] deliveries=[${[...c].join(",")}]`)}shouldAdmitDeliveryImmediately(e){return e.inputTurnActive!==!0}getHandleForAgentIntent(e,r){let n=this.handles.get(dt(e,r));if(!n||n.phase==="exited")throw new Error(`agent side-effect requested for non-running runtime ${e}/${r}`);return n}async backendPost(e,r,n){let o=this.controlPlaneServerUrl();if(!o)throw new Error("agent side-effect requested before daemon has a control-plane server URL");return fetch(`${o}${r}`,{method:"POST",headers:{[m_]:`Bearer ${e.spawnParams.options.env_policy.silverhand.auth_token}`,"X-Agent-Hub-Caller":"silverhand-daemon","Content-Type":"application/json"},body:JSON.stringify(n)})}async agentMessageSend(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=r.pendingStaleEvent,o=this.effectiveMessageTarget(r,e);if(o.kind==="ambiguous")return{ok:!1,status:422,body_text:KZ(o.streamKeys)};let i=o.kind==="thread"?o.messageId:void 0,a=i?r.replyTargetStreamByMessageId.get(i):Ji,c=a!==void 0,u=c&&r.observedSeqByStream.has(a),l=c&&(a!==Ji||u),d=l&&o.kind==="thread"&&o.source==="pending_default"?Math.max(r.observedSeqByStream.get(a)??0,r.pendingAdmissionSeqByStream.get(a)??0):l?r.observedSeqByStream.get(a)??0:void 0;i&&!c&&this.logger.info({kind:"process",action:"missing_reply_target_message",conversationId:r.conversationId,agent_id:r.agentId,target_message_id:i},"reply target unknown to daemon \u2014 sending without per-stream freshness (Case A)");let p=o.kind==="thread"?{kind:"thread",message_id:o.messageId}:o.kind==="channel"?{kind:"channel"}:o.target,m={content:e.content,...p?{target:p}:{},...e.attachment_ids?{attachment_ids:e.attachment_ids}:{},...e.freshness_bypass?{freshness_bypass:!0}:l?{seen_up_to_seq:d,stream_key:a}:{},...n?{stale_event_id:n.id,...e.freshness_bypass?{stale_resolution_reason:"force_send"}:e.stale_resolution_reason?{stale_resolution_reason:e.stale_resolution_reason}:{}}:{}},f=await this.backendPost(r,Tl.agentSendConversationMessage(e.conversation_id,e.agent_id),m);if(!f.ok){let x=await k0(f),w=f.status===409?YZ(x):null;return w?(r.pendingStaleEvent=w,l&&this.advanceObservedStream(r,a,w.currentSeq,"message_stale_response")):n&&(r.pendingStaleEvent=null),{ok:!1,status:f.status,body_text:x}}let _=await f.json(),g=_.message_id,y=_.message_seq;if(typeof g!="string"||g.length===0)throw new Error("backend send-message response missing message_id");let S=typeof _.thread_root_id=="string"?_.thread_root_id:null;if(i){let x=S?`thread:${S}`:w0(i,null);this.rememberReplyTargetStream(r,i,x),this.rememberReplyTargetStream(r,g,x)}return l&&typeof y=="number"&&this.advanceObservedStream(r,a,y,"message_send_commit"),r.pendingStaleEvent=null,{ok:!0,message_id:g,...typeof y=="number"?{message_seq:y}:{},thread_root_id:S}}async agentStaleResolve(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=r.pendingStaleEvent,o=e.stale_event_id??n?.id;if(!o)return{ok:!0,resolved:!1,reason:"no_pending_stale_event"};let i=await this.backendPost(r,Tl.agentResolveStaleMessage(e.conversation_id,e.agent_id),{stale_event_id:o,resolution_reason:e.resolution_reason});return i.ok?((!e.stale_event_id||n?.id===e.stale_event_id)&&(r.pendingStaleEvent=null),{ok:!0,resolved:!0}):{ok:!1,status:i.status,body_text:await k0(i)}}async agentStreamObserved(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=ag(e.thread_root_id);this.recordObservedStream(r,n,e.observed_seq,"pull_history_observed");for(let o of e.reply_target_messages)this.rememberReplyTargetStream(r,o,n);return{ok:!0}}async start(e){return this.startWithLock(e,0)}startWithLock(e,r){let n=dt(e.conversation_id,e.agent_id);return this.withLifecycleLock(n,()=>this.startUnlocked(e,r))}async startUnlocked(e,r){let n=dt(e.conversation_id,e.agent_id),o=!!e.startup_delivery,i=this.handles.get(n);if(i&&i.phase!=="exited")return{started:!0,pid:i.pid,started_at:i.startedAt,...o?{startup_delivery_accepted:!1}:{}};if(i&&i.phase==="exited"&&this.handles.delete(n),r===0&&this.isInitCoolingDown(n)){let pt=this.initRetryStates.get(n)?.cooldownUntil??this.now();return this.logger.info({kind:"process",action:"start_blocked_by_cooldown",conversationId:e.conversation_id,agent_id:e.agent_id,cooldown_until:pt},"start refused: init failure cooldown active"),{started:!1,reason:"init_cooldown",cooldown_until:pt}}let a=e.options,c=a.driver.kind,u=FE(a,this.runtimeStartResolveDeps);await QZ(u.workspace);let l=this.driverFor(c),d=await this.resolveBinary(c,l.binary);if(!d)throw new Error(`runtime_start: binary "${l.binary}" for runtime "${c}" not found on PATH`);let p=await p0(u),m=I_(c,p),f=a.env_policy.silverhand_cli,_=f?{command:f.command,args:f.args,...f.env_vars?{env:f.env_vars}:{}}:null,g=await y0({conversationId:e.conversation_id,agentId:e.agent_id,systemPromptText:m,silverhandCli:r0({serverLauncher:_,localLauncher:this.localSilverhandCliLauncher})}),y={agentId:e.agent_id,agentName:a.agent.name,workspacePath:u.workspace.path,cliSessionId:a.driver.cli_session_id,model:a.driver.model,reasoningEffort:a.driver.reasoning_effort,fastMode:a.driver.fast_mode,systemPromptPath:g.systemPromptPath,initialPrompt:l.oneShot?e.startup_delivery?.text??"":""},S=l.buildArgs(y),x=await b0({runtimeKind:c,agentHomeDir:u.agent.home_dir,spawnDir:g.dir,agentId:e.agent_id,logger:this.logger});S.push(...x.args);let w=f0({driver:l,options:a,conversationId:e.conversation_id,agentId:e.agent_id,daemonSocketPath:this.daemonSocketPath??void 0,lastDeliveredSeqPath:g.lastDeliveredSeqPath,binDir:g.binDir,controlPlaneServerUrl:this.controlPlaneServerUrl(),proxyConfig:Ki(this.proxyConfigPath(),this.logger)}),T=this.now(),v=this.spawnFn(d,S,{cwd:y.workspacePath,env:w,stdio:["pipe","pipe","pipe"]}),P=ie=>{this.logger.warn({kind:"process",action:"child_error_before_handle",conversationId:e.conversation_id,agent_id:e.agent_id,runtime:c,binary:d,workspace_path:y.workspacePath,error_message:ie.message},"child process emitted error before runtime handle was registered")};v.once("error",P);let O=v.pid;if(typeof O!="number")throw new Error(`runtime_start: child spawned without a pid for runtime "${c}"`);try{this.writeRuntimePidfile({conversationId:e.conversation_id,agentId:e.agent_id,pid:O,startedAt:T,runtime:c,cmd:d})}catch(ie){try{v.kill("SIGKILL")}catch{}throw new Error(`runtime_start: failed to write runtime pidfile for "${e.conversation_id}/${e.agent_id}": ${ie.message}`)}e.startup_delivery&&this.assertDeliveryMetadataConsistent(e.conversation_id,e.agent_id,e.startup_delivery.delivery_ids,e.startup_delivery.deliveries,"startup_delivery");let J=e.startup_delivery&&!l.oneShot?{deliveryIds:[...e.startup_delivery.delivery_ids],deliveredUpToSeq:e.startup_delivery.delivered_up_to_seq,deliveries:e.startup_delivery.deliveries,text:e.startup_delivery.text}:null,F={conversationId:e.conversation_id,agentId:e.agent_id,pid:O,startedAt:T,driver:l,child:v,lastDeliveredSeqPath:g.lastDeliveredSeqPath,observedSeqByStream:new Map,pendingAdmissionSeqByStream:new Map,replyTargetStreamByMessageId:new Map,defaultReplyTarget:hl,pendingDefaultReplyTarget:void 0,inputTurnActive:l.oneShot&&!!e.startup_delivery,pendingStaleEvent:null,phase:J?"startup_pending":"spawning",outputPaused:!1,exitCode:null,intentionalExit:!1,sigkillTimer:null,startupDelivery:J,startupAwaitingInit:!1,readyForDrainEmitted:!1,initObserved:!1,cliSessionId:y.cliSessionId,stdoutLineBuffer:"",runState:null,activitySnippetBuffer:null,busy:{outstandingToolUses:0,compacting:!1},spawnParams:{conversation_id:e.conversation_id,agent_id:e.agent_id,options:e.options},initWatchdogArmed:!1,initStartedAt:T,initProtocolObserved:!1,initTimedOut:!1,initTimeoutReason:null,initLivenessSilenceTimer:null,initPreProtocolCapTimer:null,initPostProtocolTimer:null,initAttempt:r,initRetryPlanned:!1,compactionWatchdog:null};return this.handles.set(n,F),this.logger.info({kind:"process",action:"spawn",pid:O,conversationId:F.conversationId,agent_id:F.agentId,runtime:c,startup_delivery:J?J.deliveryIds:null},"spawned agent runtime"),this.emitState(F),this.attachChildListeners(F),v.off("error",P),l.oneShot&&e.startup_delivery&&(this.admitDeliveryBatch(F,e.startup_delivery.deliveries,e.startup_delivery.delivered_up_to_seq,!0,"oneshot_startup_admitted"),this.writeLastDeliveredSeq(F,e.startup_delivery.delivered_up_to_seq),this.emitStartupDeliveryConsumed(F,e.startup_delivery.delivery_ids)),F.driver.bindIO&&F.driver.bindIO({writeLine:ie=>{if(ie.endsWith(`
618
- `))throw new Error('driver.writeLine: line must not end with "\\n" (writeStdinPayload appends the newline)');return this.writeStdinPayload(F,ie)},spawnCtx:y}),F.driver.kickoffMode!=="requires_first_message"&&this.startInitWatchdog(F),setImmediate(()=>{F.phase!=="spawning"&&F.phase!=="startup_pending"||(F.phase="ready",this.emitState(F),this.maybeEmitReadyForDrain(F))}),J&&this.consumeStartupDelivery(F),{started:!0,pid:O,started_at:T,...o?{startup_delivery_accepted:!0}:{}}}async consumeStartupDelivery(e){let r=e.startupDelivery;if(!r)return;let n=r.deliveryIds;if(e.phase==="exited"||e.phase==="draining"){this.emitStartupDeliveryFailed(e,n,"child_exit"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}if(!Gi(e.driver)){this.logger.info({kind:"process",action:"startup_delivery_defer_pre_ready",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n]},"startup_delivery deferred: driver not ready to encode (e.g. codex pre-thread/started)");return}let i=e.driver.encodeStdinMessage(r.text,e.cliSessionId);if(i===null){this.logger.warn({kind:"process",action:"startup_delivery_driver_refused",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n],text_bytes:r.text.length},"startup_delivery encode returned null after driver claimed ready (driver bug?)"),this.emitStartupDeliveryFailed(e,n,"driver_refused"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}try{await this.writeStdinPayload(e,i),this.admitDeliveryBatch(e,r.deliveries,r.deliveredUpToSeq,!0,"startup_delivery_admitted"),await this.writeLastDeliveredSeq(e,r.deliveredUpToSeq)}catch(a){this.logger.warn({kind:"process",action:"startup_delivery_write_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n],error_message:a.message},"startup_delivery stdin write failed"),this.emitStartupDeliveryFailed(e,n,"write_failed"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}if(this.ensureInitWatchdogArmed(e),e.driver.kickoffMode==="requires_first_message"&&!e.initObserved){e.startupAwaitingInit=!0,this.logger.info({kind:"process",action:"startup_delivery_awaiting_init",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n]},"startup_delivery written; deferring consumed until session_init");return}this.emitStartupDeliveryConsumed(e,n),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e)}tryConsumeStartupDelivery(e){e.startupDelivery&&(e.startupAwaitingInit||Gi(e.driver)&&this.consumeStartupDelivery(e))}clearStartupGate(e){e.startupDelivery=null,e.startupAwaitingInit=!1}emitStartupDeliveryConsumed(e,r){this.emit({event:"runtime_startup_delivery_consumed",conversation_id:e.conversationId,agent_id:e.agentId,delivery_ids:[...r],ts:this.now()})}emitStartupDeliveryFailed(e,r,n){this.emit({event:"runtime_startup_delivery_failed",conversation_id:e.conversationId,agent_id:e.agentId,delivery_ids:[...r],reason:n,ts:this.now()})}maybeEmitReadyForDrain(e){e.readyForDrainEmitted||e.phase==="ready"&&(e.driver.oneShot||e.startupDelivery===null&&Gi(e.driver)&&(e.readyForDrainEmitted=!0,this.emit({event:"runtime_ready_for_drain",conversation_id:e.conversationId,agent_id:e.agentId,ts:this.now()})))}async stop(e){if(e.mode==="soft")return this.softStopHandle(e);let r=dt(e.conversation_id,e.agent_id);return this.withLifecycleLock(r,async()=>{let n=this.handles.get(r);return!n||n.phase==="exited"?{mode:"hard",stopped:!1,exit_code:null}:this.hardStopHandle(n)})}async softStopHandle(e){let r=dt(e.conversation_id,e.agent_id),n=this.handles.get(r);if(!n||n.phase==="exited"||n.phase==="draining")return{mode:"soft",directive_delivered:!1,reason:"not_running"};if(e.soft_directive===void 0)return{mode:"soft",directive_delivered:!1,reason:"driver_refused"};if(!Gi(n.driver))return this.logger.info({kind:"process",action:"soft_stop_driver_not_ready",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId},"soft stop refused: driver not ready to encode (mapping to driver_refused per Cindy `wYjG20JdGjLpwq8K`)"),{mode:"soft",directive_delivered:!1,reason:"driver_refused"};let o=n.driver.encodeStdinMessage(e.soft_directive,n.cliSessionId);if(o===null)return this.logger.warn({kind:"process",action:"soft_stop_driver_refused",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,text_bytes:e.soft_directive.length},"soft stop encode returned null after driver claimed ready (driver bug?)"),{mode:"soft",directive_delivered:!1,reason:"driver_refused"};try{await this.writeStdinPayload(n,o)}catch(i){return this.logger.warn({kind:"process",action:"soft_stop_write_failed",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,error_message:i.message},"soft stop directive write failed"),{mode:"soft",directive_delivered:!1,reason:"write_failed"}}return{mode:"soft",directive_delivered:!0}}hardStopHandle(e){e.intentionalExit=!0,e.phase="draining",this.clearInitWatchdog(e),this.clearCompactionWatchdog(e),this.emitState(e);let r=new Promise(n=>{let o=a=>{n({mode:"hard",stopped:!0,exit_code:a})};e.child.once("exit",o),Vn(()=>{e.phase!=="exited"&&(this.logger.warn({kind:"process",action:"sigkill_timeout",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,timeout_ms:this.sigkillTimeoutMs},"child did not exit within sigkill timeout"),n({mode:"hard",stopped:!1,exit_code:null}))},this.sigkillTimeoutMs).unref()});this.logger.info({kind:"process",action:"sigterm",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId},"sending SIGTERM to runtime");try{e.child.kill("SIGTERM")}catch{}return e.sigkillTimer=Vn(()=>{if(e.sigkillTimer=null,e.phase!=="exited"){this.logger.warn({kind:"process",action:"sigkill",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId},"escalating to SIGKILL after grace period");try{e.child.kill("SIGKILL")}catch{}}},this.sigtermToSigkillMs),e.sigkillTimer.unref(),r}async wake(e){let r=dt(e.conversation_id,e.agent_id),n=this.handles.get(r),o=[...e.delivery_ids];if(this.assertDeliveryMetadataConsistent(e.conversation_id,e.agent_id,e.delivery_ids,e.deliveries,"runtime_wake"),!n||n.phase==="exited")return{delivered:!1,reason:"not_running",delivery_ids:o};if(n.startupDelivery!==null)return{delivered:!1,reason:"startup_pending",delivery_ids:o};if(n.phase==="draining")return{delivered:!1,reason:"draining",delivery_ids:o};if(!Gi(n.driver))return this.logger.info({kind:"process",action:"wake_driver_not_ready",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o},"wake refused: driver not ready to encode (backend keeps pending)"),{delivered:!1,reason:"driver_not_ready",delivery_ids:o};let i=n.driver.encodeStdinMessage(e.text,n.cliSessionId);if(i===null)return this.logger.warn({kind:"process",action:"wake_driver_refused",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o,text_bytes:e.text.length},"wake encode returned null after driver claimed ready (driver bug?)"),{delivered:!1,reason:"driver_refused",delivery_ids:o};let a=this.shouldAdmitDeliveryImmediately(n);try{await this.writeStdinPayload(n,i),this.admitDeliveryBatch(n,e.deliveries,e.delivered_up_to_seq,a,a?"wake_delivery_admitted":"wake_delivery_deferred"),await this.writeLastDeliveredSeq(n,e.delivered_up_to_seq)}catch(c){return this.logger.warn({kind:"process",action:"wake_write_failed",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o,error_message:c.message},"wake stdin write failed"),{delivered:!1,reason:"driver_refused",delivery_ids:o}}return this.ensureInitWatchdogArmed(n),{delivered:!0,delivery_ids:o}}async writeLastDeliveredSeq(e,r){if(!(r===void 0||!Number.isSafeInteger(r)||r<=0))try{await DZ(e.lastDeliveredSeqPath,`${r}
619
- `,"utf-8")}catch(n){this.logger.warn({kind:"process",action:"last_delivered_seq_write_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivered_up_to_seq:r,path:e.lastDeliveredSeqPath,error_message:n.message},"failed to update runtime last-delivered seq file")}}status(e){let r=[];for(let n of this.handles.values())e.conversation_id&&e.conversation_id!==n.conversationId||e.agent_id&&e.agent_id!==n.agentId||r.push({conversation_id:n.conversationId,agent_id:n.agentId,pid:n.phase==="exited"?null:n.pid,phase:n.phase,run_state:n.runState,started_at:n.startedAt});return{runtimes:r}}async clearSession(e){let r=dt(e.conversation_id,e.agent_id);return this.withLifecycleLock(r,async()=>{let n=this.handles.get(r);return!n||n.phase==="exited"?{cleared:!1}:(await this.hardStopHandle(n),{cleared:!0})})}async stopAll(e){let r=[];for(let[o,i]of this.handles)i.phase!=="exited"&&r.push(o);let n=r.length;return await Promise.all(r.map(o=>this.withLifecycleLock(o,async()=>{let i=this.handles.get(o);!i||i.phase==="exited"||await this.hardStopHandle(i)}))),{stopped_count:n}}closeActivityLog(e){return{flushed:!0}}pauseOutput(e){let r=dt(e.conversation_id,e.agent_id),n=this.handles.get(r);return!n||n.phase==="exited"?{paused:!1}:n.outputPaused?{paused:!0}:(n.outputPaused=!0,this.emit({event:"runtime_output_paused",conversation_id:n.conversationId,agent_id:n.agentId}),{paused:!0})}resumeOutput(e){let r=dt(e.conversation_id,e.agent_id),n=this.handles.get(r);return!n||n.phase==="exited"?{resumed:!1}:n.outputPaused?(n.outputPaused=!1,this.emit({event:"runtime_output_resumed",conversation_id:n.conversationId,agent_id:n.agentId}),{resumed:!0}):{resumed:!0}}attachChildListeners(e){let{child:r}=e;r.stdout&&r.stdout.on("data",n=>{this.onChildBytes(e,"stdout",n)}),r.stderr&&r.stderr.on("data",n=>{this.onChildBytes(e,"stderr",n)}),r.once("exit",(n,o)=>{this.onChildExit(e,n,o)}),r.on("error",n=>{this.logger.warn({kind:"process",action:"child_error",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,error_message:n.message},"child process emitted error")})}onChildBytes(e,r,n){let o=typeof n=="string"?n:n.toString("utf-8");o.length!==0&&(this.refreshInitLiveness(e),this.emitRawRuntimeOutput&&!e.outputPaused&&this.emit({event:"runtime_output",conversation_id:e.conversationId,agent_id:e.agentId,stream:r,chunk:o,ts:this.now()}),r==="stdout"&&this.consumeStdoutForParse(e,o))}consumeStdoutForParse(e,r){if(e.phase==="exited")return;let n=e.stdoutLineBuffer+r,o=n.lastIndexOf(`
615
+ ${r}`}import{readFileSync as WZ}from"node:fs";var ZZ=["EnterPlanMode","ExitPlanMode","CronCreate","CronList","CronDelete","CreateGoal","GetGoal","UpdateGoal"].join(","),_l=class{kind="qoder";binary="qodercli";kickoffMode="requires_first_message";busyDeliveryMode="gated";oneShot=!1;supportsNativeStandingPrompt=!0;initLivenessSilenceMs=30*1e3;initPreProtocolCapMs=300*1e3;initPostProtocolMs=60*1e3;buildArgs(e){let r=WZ(e.systemPromptPath,"utf-8"),n=["--dangerously-skip-permissions","--permission-mode","bypass_permissions","--output-format","stream-json","--input-format","stream-json","--disallowed-tools",ZZ,"--append-system-prompt",r];return e.model&&n.push("--model",e.model),e.reasoningEffort&&n.push("--reasoning-effort",e.reasoningEffort),e.cliSessionId&&n.push("--resume",e.cliSessionId),n}applyEnv(e){return{...e}}encodeStdinMessage(e,r){return dl(e,r)}encodeInterruptControl(){return null}parseLine(e){return pl(e,{runtimeLabel:"Qoder"})}classifyInitProgress(e){return ml(e)}};var BZ={claude:()=>new fl,codex:()=>new hl,cursor:()=>new gl,qoder:()=>new _l};function v0(t){let e=BZ[t];if(!e)throw new Error(`no driver registered for runtime "${t}"`);return e()}import{readFile as b0}from"node:fs/promises";import{join as yl}from"node:path";var VZ=16*1024;async function KZ(t,e){let r;try{r=await b0(t)}catch(o){let i=o?.code;return i==="ENOENT"?{kind:"missing"}:{kind:"unreadable",reason:i??o?.message??"unknown error"}}if(r.byteLength<=e)return{kind:"present",body:r.toString("utf-8")};let n=e;for(;n>0&&r[n]!==void 0&&(r[n]&192)===128;)n-=1;return{kind:"present",body:`${r.subarray(0,n).toString("utf-8")}
616
+ \u2026(truncated)`}}async function S0(t){let e=await b0(yl(t.agent.home_dir,"system_prompt.md"),"utf-8").catch(()=>""),r=await KZ(yl(x0(t.workspace,t.agent.id),"MEMORY.md"),VZ);return{agentId:t.agent.id,agentName:t.agent.name,activeProfileDir:JZ(t.workspace,t.agent.id),roleSystemPrompt:e,currentMemory:r,workspaceMemoryIndex:GZ(t),sessionContext:{conversationId:t.session.conversation_id,channelName:t.session.kind==="dm_channel"?t.session.title:t.workspace.name,channelKind:t.session.kind==="dm_channel"?"dm":"regular",sessionTitle:t.session.title,members:t.session.members,selfAgentId:t.agent.id}}}function GZ(t){return t.workspace_memory_index.map(e=>{let r=e.id===t.workspace.id,n=e.kind==="agent_home"?`${e.name} (DM)`:e.name;return{label:r?`${n} (current)`:n,memoryPath:yl(x0(e,t.agent.id),"MEMORY.md")}})}function JZ(t,e){return t.kind==="agent_home"?".":`./.silverhand/agents/${e}`}function x0(t,e){return t.kind==="agent_home"?t.path:yl(t.path,".silverhand","agents",e)}import{delimiter as YZ}from"node:path";function w0(t){let e=t.options,r=t.driver.applyEnv(t.baseProcessEnv??process.env);if(t.proxyConfig?.proxy_url&&t.proxyConfig.proxy_runtimes.includes(e.driver.kind)){let i=L_(t.proxyConfig.proxy_url);i&&(r={...r,...i})}let n=r.PATH??process.env.PATH??"",o=t.controlPlaneServerUrl;if(!o)throw new Error("runtime_start: no silverhand server URL supplied by server and no daemon-local control-plane URL is attached");return{...r,[S_]:t.conversationId,[x_]:t.agentId,[w_]:o,[k_]:e.env_policy.silverhand.auth_token,...t.daemonSocketPath?{[P_]:t.daemonSocketPath}:{},...t.lastDeliveredSeqPath?{[R_]:t.lastDeliveredSeqPath}:{},PATH:n?`${t.binDir}${YZ}${n}`:t.binDir}}import{chmod as XZ,mkdir as k0,mkdtemp as QZ,rm as e4,writeFile as R0}from"node:fs/promises";import{tmpdir as t4}from"node:os";import{join as ds}from"node:path";async function E0(t){let e=ds(t4(),"silverhand",t.conversationId,t.agentId);await k0(e,{recursive:!0});let r=await QZ(ds(e,"spawn-")),n=ds(r,"system-prompt.md"),o=ds(r,"last-delivered-seq"),i=ds(r,"bin"),a=ds(i,"silverhand"),c=r4(t.silverhandCli);return await Promise.all([k0(i,{recursive:!0}),R0(n,t.systemPromptText,"utf-8")]),await R0(a,c,"utf-8"),await XZ(a,493),{systemPromptPath:n,lastDeliveredSeqPath:o,binDir:i,dir:r,cleanup:async()=>{await e4(r,{recursive:!0,force:!0}).catch(()=>{})}}}function r4(t){let e=Object.entries(t.env??{}).map(([n,o])=>`export ${n4(n)}=${P0(o)}`).join(`
617
+ `),r=[t.command,...t.args].map(n=>P0(n)).join(" ");return["#!/bin/sh","set -eu",e,`exec ${r} "$@"`,""].filter(n=>n.length>0).join(`
618
+ `)}function n4(t){if(/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))return t;throw new Error(`invalid env var name for silverhand shim: ${t}`)}function P0(t){return`'${t.replace(/'/g,"'\\''")}'`}import{readFile as o4,writeFile as s4}from"node:fs/promises";import{join as C0}from"node:path";async function T0(t){let{runtimeKind:e,agentHomeDir:r,spawnDir:n,agentId:o,logger:i}=t,a=C0(r,Ar),c;try{c=await o4(a,"utf-8")}catch(d){return d?.code==="ENOENT"?{args:[]}:(i.warn({agentId:o,runtimeKind:e,filePath:a,err:String(d)},"profile MCP: failed to read mcp.json; skipping the entire MCP layer (agent still spawns)"),{args:[]})}let u=ao(c);if(!u.ok)return i.warn({agentId:o,runtimeKind:e,filePath:a,error:u.error},"profile MCP: mcp.json failed validation; skipping the entire MCP layer (agent still spawns)"),{args:[]};let l=Object.keys(u.config.mcpServers);if(l.length===0)return{args:[]};for(let d of l)i.debug({agentId:o,runtimeKind:e,mapping:`profile/${d} -> ${ka("profile",d)}`},"profile MCP: loading server");try{switch(e){case"claude":case"qoder":{let d=z_(u.config,"profile");if(!d)return{args:[]};let p=C0(n,"profile-mcp.json");return await s4(p,JSON.stringify(d,null,2),"utf-8"),{args:["--mcp-config",p]}}case"codex":return{args:O_(u.config,"profile").flatMap(p=>["-c",p])};default:return i.warn({agentId:o,runtimeKind:e,servers:l.length},"profile MCP: runtime has no MCP adapter; skipping the layer"),{args:[]}}}catch(d){return i.warn({agentId:o,runtimeKind:e,filePath:a,err:String(d)},"profile MCP: failed to build runtime config; skipping the entire MCP layer (agent still spawns)"),{args:[]}}}var l4=5e3,d4=1e4,p4=30*1e3,m4=300*1e3,f4=30*1e3,h4=1,g4=3,_4=300*1e3,y4=300*1e3,fg=200,A0=fg*4,v4="silverhand message send";function pt(t,e){return`${t}\0${e}`}function pg(t){return Number.isSafeInteger(t)&&t!==void 0&&t>0?t:null}var Yi="main",b4=4096,vl={kind:"channel"};function hg(t){return[...new Set(t)].sort()}function S4(t){return t.startsWith("thread:")?t.slice(7):null}function I0(t){switch(t.kind){case"thread":return[t.streamKey];case"ambiguous":return[...t.streamKeys];case"channel":return[]}}function x4(t){let e=[...hg(t).flatMap(r=>{let n=S4(r);return n?[`thread:${n}`]:[]}),"channel"];return JSON.stringify({error:{code:"validation_error",message:"bare message send has an ambiguous default target; rerun with an explicit --target",details:{subkind:"ambiguous_default_target",candidate_targets:e,hint:"Use --target thread:<id> for one listed thread, or --target channel for the main line."}}})}function mg(t){return t?`thread:${t}`:Yi}function $0(t,e){return`thread:${e??t}`}function w4(t){return t.kind==="thinking"||t.kind==="text"||t.kind==="tool_call"||t.kind==="error"&&t.fatal!==!0}function k4(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function R4(t){let r=k4(t)?.error;if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r.details;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n;if(o.subkind!=="message_stale")return null;let i=o.stale_event_id,a=o.current_seq;return typeof i!="string"||i.length===0||typeof a!="number"||!Number.isSafeInteger(a)||a<=0?null:{id:i,currentSeq:a}}async function z0(t){try{return await t.text()}catch{return""}}var ps=class{handles=new Map;emit;logger;runtimeStartResolveDeps;driverFor;resolveBinary;spawnFn;now;sigtermToSigkillMs;sigkillTimeoutMs;daemonInstanceId;runtimePidRootDir;proxyConfigPath;localSilverhandCliLauncher;controlPlaneServerUrl;daemonSocketPath;initRetryStates=new Map;lifecycleTails=new Map;initWatchdogMs;initLivenessSilenceMs;initPreProtocolCapMs;initPostProtocolMs;initMaxRetries;initFailureCooldownThreshold;initFailureCooldownMs;compactionStaleMs;emitRawRuntimeOutput;constructor(e){this.emit=e.emit,this.logger=e.logger,this.runtimeStartResolveDeps=e.runtimeStartResolveDeps,this.driverFor=e.driverFor??v0,this.resolveBinary=e.resolveBinary??A4,this.spawnFn=e.spawnFn??i4,this.now=e.now??Date.now,this.sigtermToSigkillMs=e.sigtermToSigkillMs??l4,this.sigkillTimeoutMs=e.sigkillTimeoutMs??d4,this.daemonInstanceId=e.daemonInstanceId??null,this.runtimePidRootDir=e.runtimePidRootDir??null;let r=e.proxyConfigPath??null;this.proxyConfigPath=typeof r=="function"?r:()=>r,this.localSilverhandCliLauncher=e.localSilverhandCliLauncher??null,this.controlPlaneServerUrl=e.controlPlaneServerUrl??(()=>null),this.daemonSocketPath=e.daemonSocketPath??null,this.initWatchdogMs=e.initWatchdogMs??null,this.initLivenessSilenceMs=e.initLivenessSilenceMs,this.initPreProtocolCapMs=e.initPreProtocolCapMs,this.initPostProtocolMs=e.initPostProtocolMs,this.initMaxRetries=e.initMaxRetries??h4,this.initFailureCooldownThreshold=e.initFailureCooldownThreshold??g4,this.initFailureCooldownMs=e.initFailureCooldownMs??_4,this.compactionStaleMs=e.compactionStaleMs??y4,this.emitRawRuntimeOutput=e.emitRawRuntimeOutput??!1}recordObservedStream(e,r,n,o){let i=pg(n);if(i===null)return;let a=_a(i),c=e.observedSeqByStream.get(r);c!==void 0&&c>=a||(e.observedSeqByStream.set(r,a),this.logger.warn({kind:"process",action:"freshness_observed_seq_advanced",conversationId:e.conversationId,agent_id:e.agentId,source:o,stream_key:r,previous_seq:c??null,observed_seq:a},"runtime freshness observed seq advanced"))}advanceObservedStream(e,r,n,o){this.recordObservedStream(e,r,n,o),pg(n)!==null&&(e.inputTurnActive=!0)}queueAdmissionStream(e,r,n,o){let i=pg(n);if(i===null)return;let a=_a(i),c=e.pendingAdmissionSeqByStream.get(r);c!==void 0&&c>=a||(e.pendingAdmissionSeqByStream.set(r,a),this.logger.warn({kind:"process",action:"freshness_pending_admission_queued",conversationId:e.conversationId,agent_id:e.agentId,source:o,stream_key:r,previous_pending_seq:c??null,pending_admission_seq:a},"runtime freshness pending admission queued"))}admitPendingSeqForNewTurn(e,r){if(e.pendingAdmissionSeqByStream.size>0){let n=[...e.pendingAdmissionSeqByStream.entries()];e.pendingAdmissionSeqByStream.clear();for(let[o,i]of n)this.advanceObservedStream(e,o,i,r)}e.pendingDefaultReplyTarget!==void 0&&(e.defaultReplyTarget=e.pendingDefaultReplyTarget,e.pendingDefaultReplyTarget=void 0)}rememberReplyTargetStream(e,r,n){let o=e.replyTargetStreamByMessageId;for(o.delete(r),o.set(r,n);o.size>b4;){let i=o.keys().next().value;if(i===void 0)break;o.delete(i)}}inferDefaultReplyTarget(e){if(!e||e.length===0)return;let r=new Map,n=!1;for(let c of e){if(c.delivery_kind!=="turn"||(n=!0,!c.thread_root_id))continue;let u=mg(c.thread_root_id),l=r.get(u);(!l||c.seq>=l.seq)&&r.set(u,c)}if(!n)return;if(r.size===0)return vl;if(r.size>1)return{kind:"ambiguous",streamKeys:[...r.keys()].sort()};let o=r.entries().next().value;if(!o)return;let[i,a]=o;return{kind:"thread",messageId:a.message_id,streamKey:i}}mergePendingDefaultReplyTarget(e,r){if(r===void 0)return;let n=e.pendingDefaultReplyTarget;if(n===void 0){e.pendingDefaultReplyTarget=r;return}if(n.kind==="ambiguous"||r.kind==="ambiguous"){let o=[...I0(n),...I0(r)];e.pendingDefaultReplyTarget=o.length===0?{kind:"ambiguous",streamKeys:[]}:{kind:"ambiguous",streamKeys:hg(o)};return}if(n.kind==="channel"){e.pendingDefaultReplyTarget=r;return}if(r.kind==="channel"){e.pendingDefaultReplyTarget=n;return}e.pendingDefaultReplyTarget=n.streamKey===r.streamKey?r:{kind:"ambiguous",streamKeys:hg([n.streamKey,r.streamKey])}}effectiveMessageTarget(e,r){if(r.reply_to_message_id!==void 0)return{kind:"thread",messageId:r.reply_to_message_id};let n=r.target;return n&&typeof n=="object"&&"kind"in n?n.kind==="thread"?{kind:"thread",messageId:n.message_id}:{kind:"channel"}:n!==void 0?{kind:"legacy",target:n}:e.pendingDefaultReplyTarget?e.pendingDefaultReplyTarget.kind==="ambiguous"?{kind:"ambiguous",streamKeys:e.pendingDefaultReplyTarget.streamKeys}:e.pendingDefaultReplyTarget.kind==="channel"?{kind:"channel"}:{kind:"thread",messageId:e.pendingDefaultReplyTarget.messageId,source:"pending_default"}:e.defaultReplyTarget.kind==="ambiguous"?{kind:"ambiguous",streamKeys:e.defaultReplyTarget.streamKeys}:e.defaultReplyTarget.kind==="thread"?{kind:"thread",messageId:e.defaultReplyTarget.messageId,source:"current_default"}:{kind:"channel"}}admitDeliveryBatch(e,r,n,o,i){let a=this.inferDefaultReplyTarget(r);if(o?(e.defaultReplyTarget=a??vl,e.pendingDefaultReplyTarget=void 0):this.mergePendingDefaultReplyTarget(e,a),r&&r.length>0){for(let c of r){this.rememberReplyTargetStream(e,c.message_id,$0(c.message_id,c.thread_root_id));let u=mg(c.thread_root_id);o?this.advanceObservedStream(e,u,c.seq,i):this.queueAdmissionStream(e,u,c.seq,i)}return}o?this.advanceObservedStream(e,Yi,n,i):this.queueAdmissionStream(e,Yi,n,i)}assertDeliveryMetadataConsistent(e,r,n,o,i){if(!o)return;let a=new Set(n),c=new Set(o.map(l=>l.delivery_id)),u=a.size!==c.size;if(!u){for(let l of a)if(!c.has(l)){u=!0;break}}if(u)throw this.logger.error({kind:"process",action:"delivery_metadata_mismatch",conversationId:e,agent_id:r,context:i,delivery_ids:[...a],metadata_ids:[...c]},"delivery metadata id-set does not match delivery_ids (backend bug)"),new Error(`delivery metadata mismatch in ${i}: delivery_ids=[${[...a].join(",")}] deliveries=[${[...c].join(",")}]`)}shouldAdmitDeliveryImmediately(e){return e.inputTurnActive!==!0}getHandleForAgentIntent(e,r){let n=this.handles.get(pt(e,r));if(!n||n.phase==="exited")throw new Error(`agent side-effect requested for non-running runtime ${e}/${r}`);return n}async backendPost(e,r,n){let o=this.controlPlaneServerUrl();if(!o)throw new Error("agent side-effect requested before daemon has a control-plane server URL");return fetch(`${o}${r}`,{method:"POST",headers:{[b_]:`Bearer ${e.spawnParams.options.env_policy.silverhand.auth_token}`,"X-Agent-Hub-Caller":"silverhand-daemon","Content-Type":"application/json"},body:JSON.stringify(n)})}async agentMessageSend(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=r.pendingStaleEvent,o=this.effectiveMessageTarget(r,e);if(o.kind==="ambiguous")return{ok:!1,status:422,body_text:x4(o.streamKeys)};let i=o.kind==="thread"?o.messageId:void 0,a=i?r.replyTargetStreamByMessageId.get(i):Yi,c=a!==void 0,u=c&&r.observedSeqByStream.has(a),l=c&&(a!==Yi||u),d=l&&o.kind==="thread"&&o.source==="pending_default"?Math.max(r.observedSeqByStream.get(a)??0,r.pendingAdmissionSeqByStream.get(a)??0):l?r.observedSeqByStream.get(a)??0:void 0;i&&!c&&this.logger.info({kind:"process",action:"missing_reply_target_message",conversationId:r.conversationId,agent_id:r.agentId,target_message_id:i},"reply target unknown to daemon \u2014 sending without per-stream freshness (Case A)");let p=o.kind==="thread"?{kind:"thread",message_id:o.messageId}:o.kind==="channel"?{kind:"channel"}:o.target,m={content:e.content,...p?{target:p}:{},...e.attachment_ids?{attachment_ids:e.attachment_ids}:{},...e.freshness_bypass?{freshness_bypass:!0}:l?{seen_up_to_seq:d,stream_key:a}:{},...n?{stale_event_id:n.id,...e.freshness_bypass?{stale_resolution_reason:"force_send"}:e.stale_resolution_reason?{stale_resolution_reason:e.stale_resolution_reason}:{}}:{}},f=await this.backendPost(r,zl.agentSendConversationMessage(e.conversation_id,e.agent_id),m);if(!f.ok){let x=await z0(f),w=f.status===409?R4(x):null;return w?(r.pendingStaleEvent=w,l&&this.advanceObservedStream(r,a,w.currentSeq,"message_stale_response")):n&&(r.pendingStaleEvent=null),{ok:!1,status:f.status,body_text:x}}let _=await f.json(),g=_.message_id,y=_.message_seq;if(typeof g!="string"||g.length===0)throw new Error("backend send-message response missing message_id");let S=typeof _.thread_root_id=="string"?_.thread_root_id:null;if(i){let x=S?`thread:${S}`:$0(i,null);this.rememberReplyTargetStream(r,i,x),this.rememberReplyTargetStream(r,g,x)}return l&&typeof y=="number"&&this.advanceObservedStream(r,a,y,"message_send_commit"),r.pendingStaleEvent=null,{ok:!0,message_id:g,...typeof y=="number"?{message_seq:y}:{},thread_root_id:S}}async agentStaleResolve(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=r.pendingStaleEvent,o=e.stale_event_id??n?.id;if(!o)return{ok:!0,resolved:!1,reason:"no_pending_stale_event"};let i=await this.backendPost(r,zl.agentResolveStaleMessage(e.conversation_id,e.agent_id),{stale_event_id:o,resolution_reason:e.resolution_reason});return i.ok?((!e.stale_event_id||n?.id===e.stale_event_id)&&(r.pendingStaleEvent=null),{ok:!0,resolved:!0}):{ok:!1,status:i.status,body_text:await z0(i)}}async agentStreamObserved(e){let r=this.getHandleForAgentIntent(e.conversation_id,e.agent_id),n=mg(e.thread_root_id);this.recordObservedStream(r,n,e.observed_seq,"pull_history_observed");for(let o of e.reply_target_messages)this.rememberReplyTargetStream(r,o,n);return{ok:!0}}async start(e){return this.startWithLock(e,0)}startWithLock(e,r){let n=pt(e.conversation_id,e.agent_id);return this.withLifecycleLock(n,()=>this.startUnlocked(e,r))}async startUnlocked(e,r){let n=pt(e.conversation_id,e.agent_id),o=!!e.startup_delivery,i=this.handles.get(n);if(i&&i.phase!=="exited")return{started:!0,pid:i.pid,started_at:i.startedAt,...o?{startup_delivery_accepted:!1}:{}};if(i&&i.phase==="exited"&&this.handles.delete(n),r===0&&this.isInitCoolingDown(n)){let mt=this.initRetryStates.get(n)?.cooldownUntil??this.now();return this.logger.info({kind:"process",action:"start_blocked_by_cooldown",conversationId:e.conversation_id,agent_id:e.agent_id,cooldown_until:mt},"start refused: init failure cooldown active"),{started:!1,reason:"init_cooldown",cooldown_until:mt}}let a=e.options,c=a.driver.kind,u=XE(a,this.runtimeStartResolveDeps);await E4(u.workspace);let l=this.driverFor(c),d=await this.resolveBinary(c,l.binary);if(!d)throw new Error(`runtime_start: binary "${l.binary}" for runtime "${c}" not found on PATH`);let p=await S0(u),m=j_(c,p),f=a.env_policy.silverhand_cli,_=f?{command:f.command,args:f.args,...f.env_vars?{env:f.env_vars}:{}}:null,g=await E0({conversationId:e.conversation_id,agentId:e.agent_id,systemPromptText:m,silverhandCli:f0({serverLauncher:_,localLauncher:this.localSilverhandCliLauncher})}),y={agentId:e.agent_id,agentName:a.agent.name,workspacePath:u.workspace.path,cliSessionId:a.driver.cli_session_id,model:a.driver.model,reasoningEffort:a.driver.reasoning_effort,fastMode:a.driver.fast_mode,systemPromptPath:g.systemPromptPath,initialPrompt:l.oneShot?e.startup_delivery?.text??"":""},S=l.buildArgs(y),x=await T0({runtimeKind:c,agentHomeDir:u.agent.home_dir,spawnDir:g.dir,agentId:e.agent_id,logger:this.logger});S.push(...x.args);let w=w0({driver:l,options:a,conversationId:e.conversation_id,agentId:e.agent_id,daemonSocketPath:this.daemonSocketPath??void 0,lastDeliveredSeqPath:g.lastDeliveredSeqPath,binDir:g.binDir,controlPlaneServerUrl:this.controlPlaneServerUrl(),proxyConfig:Gi(this.proxyConfigPath(),this.logger)}),T=this.now(),v=this.spawnFn(d,S,{cwd:y.workspacePath,env:w,stdio:["pipe","pipe","pipe"]}),P=ie=>{this.logger.warn({kind:"process",action:"child_error_before_handle",conversationId:e.conversation_id,agent_id:e.agent_id,runtime:c,binary:d,workspace_path:y.workspacePath,error_message:ie.message},"child process emitted error before runtime handle was registered")};v.once("error",P);let O=v.pid;if(typeof O!="number")throw new Error(`runtime_start: child spawned without a pid for runtime "${c}"`);try{this.writeRuntimePidfile({conversationId:e.conversation_id,agentId:e.agent_id,pid:O,startedAt:T,runtime:c,cmd:d})}catch(ie){try{v.kill("SIGKILL")}catch{}throw new Error(`runtime_start: failed to write runtime pidfile for "${e.conversation_id}/${e.agent_id}": ${ie.message}`)}e.startup_delivery&&this.assertDeliveryMetadataConsistent(e.conversation_id,e.agent_id,e.startup_delivery.delivery_ids,e.startup_delivery.deliveries,"startup_delivery");let J=e.startup_delivery&&!l.oneShot?{deliveryIds:[...e.startup_delivery.delivery_ids],deliveredUpToSeq:e.startup_delivery.delivered_up_to_seq,deliveries:e.startup_delivery.deliveries,text:e.startup_delivery.text}:null,F={conversationId:e.conversation_id,agentId:e.agent_id,pid:O,startedAt:T,driver:l,child:v,lastDeliveredSeqPath:g.lastDeliveredSeqPath,observedSeqByStream:new Map,pendingAdmissionSeqByStream:new Map,replyTargetStreamByMessageId:new Map,defaultReplyTarget:vl,pendingDefaultReplyTarget:void 0,inputTurnActive:l.oneShot&&!!e.startup_delivery,pendingStaleEvent:null,phase:J?"startup_pending":"spawning",outputPaused:!1,exitCode:null,intentionalExit:!1,sigkillTimer:null,startupDelivery:J,startupAwaitingInit:!1,readyForDrainEmitted:!1,initObserved:!1,cliSessionId:y.cliSessionId,stdoutLineBuffer:"",runState:null,activitySnippetBuffer:null,busy:{outstandingToolUses:0,compacting:!1},spawnParams:{conversation_id:e.conversation_id,agent_id:e.agent_id,options:e.options},initWatchdogArmed:!1,initStartedAt:T,initProtocolObserved:!1,initTimedOut:!1,initTimeoutReason:null,initLivenessSilenceTimer:null,initPreProtocolCapTimer:null,initPostProtocolTimer:null,initAttempt:r,initRetryPlanned:!1,compactionWatchdog:null};return this.handles.set(n,F),this.logger.info({kind:"process",action:"spawn",pid:O,conversationId:F.conversationId,agent_id:F.agentId,runtime:c,startup_delivery:J?J.deliveryIds:null},"spawned agent runtime"),this.emitState(F),this.attachChildListeners(F),v.off("error",P),l.oneShot&&e.startup_delivery&&(this.admitDeliveryBatch(F,e.startup_delivery.deliveries,e.startup_delivery.delivered_up_to_seq,!0,"oneshot_startup_admitted"),this.writeLastDeliveredSeq(F,e.startup_delivery.delivered_up_to_seq),this.emitStartupDeliveryConsumed(F,e.startup_delivery.delivery_ids)),F.driver.bindIO&&F.driver.bindIO({writeLine:ie=>{if(ie.endsWith(`
619
+ `))throw new Error('driver.writeLine: line must not end with "\\n" (writeStdinPayload appends the newline)');return this.writeStdinPayload(F,ie)},spawnCtx:y}),F.driver.kickoffMode!=="requires_first_message"&&this.startInitWatchdog(F),setImmediate(()=>{F.phase!=="spawning"&&F.phase!=="startup_pending"||(F.phase="ready",this.emitState(F),this.maybeEmitReadyForDrain(F))}),J&&this.consumeStartupDelivery(F),{started:!0,pid:O,started_at:T,...o?{startup_delivery_accepted:!0}:{}}}async consumeStartupDelivery(e){let r=e.startupDelivery;if(!r)return;let n=r.deliveryIds;if(e.phase==="exited"||e.phase==="draining"){this.emitStartupDeliveryFailed(e,n,"child_exit"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}if(!Ji(e.driver)){this.logger.info({kind:"process",action:"startup_delivery_defer_pre_ready",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n]},"startup_delivery deferred: driver not ready to encode (e.g. codex pre-thread/started)");return}let i=e.driver.encodeStdinMessage(r.text,e.cliSessionId);if(i===null){this.logger.warn({kind:"process",action:"startup_delivery_driver_refused",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n],text_bytes:r.text.length},"startup_delivery encode returned null after driver claimed ready (driver bug?)"),this.emitStartupDeliveryFailed(e,n,"driver_refused"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}try{await this.writeStdinPayload(e,i),this.admitDeliveryBatch(e,r.deliveries,r.deliveredUpToSeq,!0,"startup_delivery_admitted"),await this.writeLastDeliveredSeq(e,r.deliveredUpToSeq)}catch(a){this.logger.warn({kind:"process",action:"startup_delivery_write_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n],error_message:a.message},"startup_delivery stdin write failed"),this.emitStartupDeliveryFailed(e,n,"write_failed"),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e);return}if(this.ensureInitWatchdogArmed(e),e.driver.kickoffMode==="requires_first_message"&&!e.initObserved){e.startupAwaitingInit=!0,this.logger.info({kind:"process",action:"startup_delivery_awaiting_init",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivery_ids:[...n]},"startup_delivery written; deferring consumed until session_init");return}this.emitStartupDeliveryConsumed(e,n),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e)}tryConsumeStartupDelivery(e){e.startupDelivery&&(e.startupAwaitingInit||Ji(e.driver)&&this.consumeStartupDelivery(e))}clearStartupGate(e){e.startupDelivery=null,e.startupAwaitingInit=!1}emitStartupDeliveryConsumed(e,r){this.emit({event:"runtime_startup_delivery_consumed",conversation_id:e.conversationId,agent_id:e.agentId,delivery_ids:[...r],ts:this.now()})}emitStartupDeliveryFailed(e,r,n){this.emit({event:"runtime_startup_delivery_failed",conversation_id:e.conversationId,agent_id:e.agentId,delivery_ids:[...r],reason:n,ts:this.now()})}maybeEmitReadyForDrain(e){e.readyForDrainEmitted||e.phase==="ready"&&(e.driver.oneShot||e.startupDelivery===null&&Ji(e.driver)&&(e.readyForDrainEmitted=!0,this.emit({event:"runtime_ready_for_drain",conversation_id:e.conversationId,agent_id:e.agentId,ts:this.now()})))}async stop(e){if(e.mode==="soft")return this.softStopHandle(e);let r=pt(e.conversation_id,e.agent_id);return this.withLifecycleLock(r,async()=>{let n=this.handles.get(r);return!n||n.phase==="exited"?{mode:"hard",stopped:!1,exit_code:null}:this.hardStopHandle(n)})}async softStopHandle(e){let r=pt(e.conversation_id,e.agent_id),n=this.handles.get(r);if(!n||n.phase==="exited"||n.phase==="draining")return{mode:"soft",directive_delivered:!1,reason:"not_running"};if(e.soft_directive===void 0)return{mode:"soft",directive_delivered:!1,reason:"driver_refused"};if(!Ji(n.driver))return this.logger.info({kind:"process",action:"soft_stop_driver_not_ready",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId},"soft stop refused: driver not ready to encode (mapping to driver_refused per Cindy `wYjG20JdGjLpwq8K`)"),{mode:"soft",directive_delivered:!1,reason:"driver_refused"};let o=n.driver.encodeStdinMessage(e.soft_directive,n.cliSessionId);if(o===null)return this.logger.warn({kind:"process",action:"soft_stop_driver_refused",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,text_bytes:e.soft_directive.length},"soft stop encode returned null after driver claimed ready (driver bug?)"),{mode:"soft",directive_delivered:!1,reason:"driver_refused"};try{await this.writeStdinPayload(n,o)}catch(i){return this.logger.warn({kind:"process",action:"soft_stop_write_failed",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,error_message:i.message},"soft stop directive write failed"),{mode:"soft",directive_delivered:!1,reason:"write_failed"}}return{mode:"soft",directive_delivered:!0}}hardStopHandle(e){e.intentionalExit=!0,e.phase="draining",this.clearInitWatchdog(e),this.clearCompactionWatchdog(e),this.emitState(e);let r=new Promise(n=>{let o=a=>{n({mode:"hard",stopped:!0,exit_code:a})};e.child.once("exit",o),Kn(()=>{e.phase!=="exited"&&(this.logger.warn({kind:"process",action:"sigkill_timeout",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,timeout_ms:this.sigkillTimeoutMs},"child did not exit within sigkill timeout"),n({mode:"hard",stopped:!1,exit_code:null}))},this.sigkillTimeoutMs).unref()});this.logger.info({kind:"process",action:"sigterm",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId},"sending SIGTERM to runtime");try{e.child.kill("SIGTERM")}catch{}return e.sigkillTimer=Kn(()=>{if(e.sigkillTimer=null,e.phase!=="exited"){this.logger.warn({kind:"process",action:"sigkill",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId},"escalating to SIGKILL after grace period");try{e.child.kill("SIGKILL")}catch{}}},this.sigtermToSigkillMs),e.sigkillTimer.unref(),r}async wake(e){let r=pt(e.conversation_id,e.agent_id),n=this.handles.get(r),o=[...e.delivery_ids];if(this.assertDeliveryMetadataConsistent(e.conversation_id,e.agent_id,e.delivery_ids,e.deliveries,"runtime_wake"),!n||n.phase==="exited")return{delivered:!1,reason:"not_running",delivery_ids:o};if(n.startupDelivery!==null)return{delivered:!1,reason:"startup_pending",delivery_ids:o};if(n.phase==="draining")return{delivered:!1,reason:"draining",delivery_ids:o};if(!Ji(n.driver))return this.logger.info({kind:"process",action:"wake_driver_not_ready",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o},"wake refused: driver not ready to encode (backend keeps pending)"),{delivered:!1,reason:"driver_not_ready",delivery_ids:o};let i=n.driver.encodeStdinMessage(e.text,n.cliSessionId);if(i===null)return this.logger.warn({kind:"process",action:"wake_driver_refused",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o,text_bytes:e.text.length},"wake encode returned null after driver claimed ready (driver bug?)"),{delivered:!1,reason:"driver_refused",delivery_ids:o};let a=this.shouldAdmitDeliveryImmediately(n);try{await this.writeStdinPayload(n,i),this.admitDeliveryBatch(n,e.deliveries,e.delivered_up_to_seq,a,a?"wake_delivery_admitted":"wake_delivery_deferred"),await this.writeLastDeliveredSeq(n,e.delivered_up_to_seq)}catch(c){return this.logger.warn({kind:"process",action:"wake_write_failed",pid:n.pid,conversationId:n.conversationId,agent_id:n.agentId,delivery_ids:o,error_message:c.message},"wake stdin write failed"),{delivered:!1,reason:"driver_refused",delivery_ids:o}}return this.ensureInitWatchdogArmed(n),{delivered:!0,delivery_ids:o}}async writeLastDeliveredSeq(e,r){if(!(r===void 0||!Number.isSafeInteger(r)||r<=0))try{await u4(e.lastDeliveredSeqPath,`${r}
620
+ `,"utf-8")}catch(n){this.logger.warn({kind:"process",action:"last_delivered_seq_write_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,delivered_up_to_seq:r,path:e.lastDeliveredSeqPath,error_message:n.message},"failed to update runtime last-delivered seq file")}}status(e){let r=[];for(let n of this.handles.values())e.conversation_id&&e.conversation_id!==n.conversationId||e.agent_id&&e.agent_id!==n.agentId||r.push({conversation_id:n.conversationId,agent_id:n.agentId,pid:n.phase==="exited"?null:n.pid,phase:n.phase,run_state:n.runState,started_at:n.startedAt});return{runtimes:r}}async clearSession(e){let r=pt(e.conversation_id,e.agent_id);return this.withLifecycleLock(r,async()=>{let n=this.handles.get(r);return!n||n.phase==="exited"?{cleared:!1}:(await this.hardStopHandle(n),{cleared:!0})})}async stopAll(e){let r=[];for(let[o,i]of this.handles)i.phase!=="exited"&&r.push(o);let n=r.length;return await Promise.all(r.map(o=>this.withLifecycleLock(o,async()=>{let i=this.handles.get(o);!i||i.phase==="exited"||await this.hardStopHandle(i)}))),{stopped_count:n}}closeActivityLog(e){return{flushed:!0}}pauseOutput(e){let r=pt(e.conversation_id,e.agent_id),n=this.handles.get(r);return!n||n.phase==="exited"?{paused:!1}:n.outputPaused?{paused:!0}:(n.outputPaused=!0,this.emit({event:"runtime_output_paused",conversation_id:n.conversationId,agent_id:n.agentId}),{paused:!0})}resumeOutput(e){let r=pt(e.conversation_id,e.agent_id),n=this.handles.get(r);return!n||n.phase==="exited"?{resumed:!1}:n.outputPaused?(n.outputPaused=!1,this.emit({event:"runtime_output_resumed",conversation_id:n.conversationId,agent_id:n.agentId}),{resumed:!0}):{resumed:!0}}attachChildListeners(e){let{child:r}=e;r.stdout&&r.stdout.on("data",n=>{this.onChildBytes(e,"stdout",n)}),r.stderr&&r.stderr.on("data",n=>{this.onChildBytes(e,"stderr",n)}),r.once("exit",(n,o)=>{this.onChildExit(e,n,o)}),r.on("error",n=>{this.logger.warn({kind:"process",action:"child_error",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,error_message:n.message},"child process emitted error")})}onChildBytes(e,r,n){let o=typeof n=="string"?n:n.toString("utf-8");o.length!==0&&(this.refreshInitLiveness(e),this.emitRawRuntimeOutput&&!e.outputPaused&&this.emit({event:"runtime_output",conversation_id:e.conversationId,agent_id:e.agentId,stream:r,chunk:o,ts:this.now()}),r==="stdout"&&this.consumeStdoutForParse(e,o))}consumeStdoutForParse(e,r){if(e.phase==="exited")return;let n=e.stdoutLineBuffer+r,o=n.lastIndexOf(`
620
621
  `);if(o===-1){e.stdoutLineBuffer=n;return}let i=n.slice(0,o);e.stdoutLineBuffer=n.slice(o+1);let a=i.split(`
621
- `);for(let c of a)c.length!==0&&this.dispatchParsedLine(e,c)}dispatchParsedLine(e,r){this.observeInitProgress(e,r);let n;try{n=e.driver.parseLine(r)}catch(o){this.logger.warn({kind:"process",action:"parse_line_threw",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,error_message:o.message},"driver.parseLine threw on stdout line");return}for(let o of n){let i=so.safeParse(o);if(!i.success){this.logger.warn({kind:"process",action:"parse_event_invalid",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,issue:i.error.issues[0]?.message??"unknown"},"driver.parseLine produced event that fails ParsedEventSchema");continue}this.updateRunStateFromParsed(e,i.data),this.emitParsedEvent(e,i.data)}}emitParsedEvent(e,r){let n={event:"runtime_parsed_event",conversation_id:e.conversationId,agent_id:e.agentId,parsed:r,ts:this.now()},o=null;try{o=Jt(n)}catch(c){this.logger.warn({kind:"process",action:"parse_event_too_large",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,parsed_kind:r.kind,error_message:c.message},"parsed event exceeds frame cap; emitting dropped marker")}if(o!==null){this.emit(n);return}let i=JSON.stringify({event:"runtime_parsed_event",conversation_id:e.conversationId,agent_id:e.agentId,parsed:r,ts:this.now()}),a=Buffer.byteLength(i,"utf-8")+1;this.emit({event:"runtime_parsed_event_dropped",conversation_id:e.conversationId,agent_id:e.agentId,parsed_kind:r.kind,encoded_bytes:a,reason:"frame_too_large",ts:this.now()})}updateRunStateFromParsed(e,r){if(r.kind==="session_init"){if(!e.initObserved){if(e.initObserved=!0,e.cliSessionId=r.sessionId,this.clearInitWatchdog(e),this.clearInitRetryState(e.conversationId,e.agentId),this.logger.info({kind:"process",action:"session_init",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,cli_session_id:r.sessionId},"agent: session_init received"),e.startupAwaitingInit&&e.startupDelivery){let n=e.startupDelivery.deliveryIds;this.emitStartupDeliveryConsumed(e,n),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e)}this.tryConsumeStartupDelivery(e),this.maybeEmitReadyForDrain(e)}return}switch(!e.inputTurnActive&&GZ(r)&&this.admitPendingSeqForNewTurn(e,"queued_delivery_admitted_on_activity"),r.kind){case"thinking":this.recordActivitySnippet(e,"thinking",r.text);break;case"text":this.recordActivitySnippet(e,"text",r.text);break;case"tool_call":e.busy.outstandingToolUses+=1;let n=r.name===ZZ?e.runState?.toolCallCounts:e4(e.runState?.toolCallCounts,r.name);this.transitionRunState(e,{status:"tool_running",detail:r.name,...n?{toolCallCounts:n}:{}});break;case"tool_output":e.busy.outstandingToolUses=Math.max(0,e.busy.outstandingToolUses-1),e.busy.outstandingToolUses===0&&!e.busy.compacting&&this.transitionRunState(e,{status:"thinking",detail:null});break;case"compaction_started":e.busy.compacting=!0,this.startCompactionWatchdog(e),this.transitionRunState(e,{compacting:!0,compactingSince:this.now(),compactionStale:!1});break;case"compaction_finished":e.busy.compacting=!1,this.clearCompactionWatchdog(e),this.transitionRunState(e,{compacting:!1,compactingSince:null,compactionStale:!1,...e.busy.outstandingToolUses===0?{status:"thinking",detail:null}:{}});break;case"turn_end":e.busy.outstandingToolUses=0,e.busy.compacting=!1,this.resolveRun(e,"turn_ended");break;case"error":r.fatal!==!0&&this.transitionRunState(e,{status:"thinking",detail:null,activitySnippet:r.message});break;case"unknown":break}}transitionRunState(e,r){let n=this.now();if(!e.runState){let c=r.status??"thinking";e.runState={runId:zZ(),agentId:e.agentId,conversationId:e.conversationId,status:c,startedAt:n,updatedAt:n,lastActivityAt:n,...r.detail&&r.detail!==null?{detail:r.detail}:{},...r.terminalReason?{terminalReason:r.terminalReason}:{},...r.activitySnippet?{activitySnippet:r.activitySnippet}:{},...r.toolCallCounts?{toolCallCounts:r.toolCallCounts}:{},...r.compacting!==void 0?{compacting:r.compacting}:{},...r.compactingSince!==void 0&&r.compactingSince!==null?{compactingSince:r.compactingSince}:{},...r.compactionStale===!0?{compactionStale:!0}:{}},this.emitState(e);return}let o=e.runState,i={...o,updatedAt:n,lastActivityAt:n};r.status!==void 0&&(i.status=r.status),r.detail===null?delete i.detail:r.detail!==void 0&&(i.detail=r.detail),r.terminalReason!==void 0&&(i.terminalReason=r.terminalReason),r.activitySnippet===null?delete i.activitySnippet:r.activitySnippet!==void 0&&(i.activitySnippet=r.activitySnippet),r.toolCallCounts===null?delete i.toolCallCounts:r.toolCallCounts!==void 0&&(i.toolCallCounts=r.toolCallCounts),r.compacting!==void 0&&(i.compacting=r.compacting),r.compactingSince===null?delete i.compactingSince:r.compactingSince!==void 0&&(i.compactingSince=r.compactingSince),r.compactionStale===!0?i.compactionStale=!0:r.compactionStale===!1&&delete i.compactionStale,e.runState=i,(o.status!==i.status||o.detail!==i.detail||o.terminalReason!==i.terminalReason||o.activitySnippet!==i.activitySnippet||JSON.stringify(o.toolCallCounts??{})!==JSON.stringify(i.toolCallCounts??{})||o.compacting!==i.compacting||o.compactionStale!==i.compactionStale)&&this.emitState(e)}recordActivitySnippet(e,r,n){e.runState||this.transitionRunState(e,{status:"thinking",detail:null});let o=e.runState?.runId;if(!o)return;let i=this.appendActivitySnippetBuffer(e,o,r,n);this.transitionRunState(e,i?{activitySnippet:i}:{status:"thinking"})}appendActivitySnippetBuffer(e,r,n,o){let i=e.activitySnippetBuffer,a=i?.runId===r&&i.kind===n?`${i.text}${o}`:o,c=a.length<=S0?a:a.slice(-S0);return e.activitySnippetBuffer={runId:r,kind:n,text:c},t4(c)}clearActivitySnippetBuffer(e,r){let n=e.activitySnippetBuffer;n&&(r&&n.runId!==r||(e.activitySnippetBuffer=null))}resolveRun(e,r){let n=r==="replied"||r==="turn_ended"||r==="replaced"?"idle":"failed",o=this.now(),i=e.runState?{...e.runState,status:n,updatedAt:o,lastActivityAt:o,terminalReason:r,compacting:!1}:{runId:`real-${e.pid}-${e.startedAt}`,agentId:e.agentId,conversationId:e.conversationId,status:n,startedAt:e.startedAt,updatedAt:o,lastActivityAt:o,terminalReason:r};this.emit({event:"runtime_state",conversation_id:e.conversationId,agent_id:e.agentId,state:i,ts:o}),this.clearActivitySnippetBuffer(e,i.runId),e.runState=null,e.busy.outstandingToolUses=0,e.busy.compacting=!1,e.inputTurnActive=!1,e.defaultReplyTarget=hl,e.pendingDefaultReplyTarget=void 0}writeStdinPayload(e,r){return new Promise((n,o)=>{let i=e.child.stdin;if(!i||i.destroyed){o(new Error("child stdin is not writable"));return}let a=typeof r=="string"?r:JSON.stringify(r);i.write(a+`
622
- `,u=>u?o(u):n())||i.once("drain",()=>n())})}writeRuntimePidfile(e){!this.runtimePidRootDir||!this.daemonInstanceId||VE({rootDir:this.runtimePidRootDir,daemonInstanceId:this.daemonInstanceId,...e})}unlinkRuntimePidfileForHandle(e){if(!(!this.runtimePidRootDir||!this.daemonInstanceId))try{KE({rootDir:this.runtimePidRootDir,daemonInstanceId:this.daemonInstanceId,conversationId:e.conversationId,agentId:e.agentId})}catch(r){this.logger.warn({kind:"process",action:"runtime_pidfile_unlink_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,err:r.message},"failed to unlink runtime pidfile during child finalization")}}onChildExit(e,r,n){if(e.phase==="exited")return;if(e.sigkillTimer&&(clearTimeout(e.sigkillTimer),e.sigkillTimer=null),this.clearInitWatchdog(e),this.clearCompactionWatchdog(e),e.stdoutLineBuffer.length>0){let u=e.stdoutLineBuffer;e.stdoutLineBuffer="",this.dispatchParsedLine(e,u)}e.phase="exited",e.exitCode=r,this.unlinkRuntimePidfileForHandle(e);let o=e.intentionalExit,i=this.now(),a=dt(e.conversationId,e.agentId);if(this.logger.info({kind:"process",action:"exit",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,exit_code:r,signal:n??null,intentional:o,init_timed_out:e.initTimedOut,init_retry_planned:e.initRetryPlanned},"child exited"),e.startupDelivery!==null&&(this.emitStartupDeliveryFailed(e,e.startupDelivery.deliveryIds,e.initTimedOut?"init_watchdog":"child_exit"),this.clearStartupGate(e)),e.initTimedOut&&e.initRetryPlanned&&!e.intentionalExit){let u=e.initAttempt+1;this.emit({event:"runtime_init_retrying",conversation_id:e.conversationId,agent_id:e.agentId,retry_attempt:u,max_retries:this.initMaxRetries,delay_ms:0,ts:this.now()}),this.handles.delete(a),this.resolveRun(e,"timeout"),this.emit({event:"runtime_exit",conversation_id:e.conversationId,agent_id:e.agentId,code:r,intentional:!1,ts:i}),this.internalRespawnForRetry(e.spawnParams,u);return}if(e.initTimedOut){let u=this.initRetryStates.get(a);u&&u.cooldownUntil>this.now()&&this.emit({event:"runtime_init_cooldown",conversation_id:e.conversationId,agent_id:e.agentId,cooldown_until:u.cooldownUntil,attempts_exhausted:u.failures,ts:this.now()})}let c=e.initTimedOut?"timeout":o?"stopped":r===0?"replied":"crashed";this.resolveRun(e,c),this.emit({event:"runtime_exit",conversation_id:e.conversationId,agent_id:e.agentId,code:r,intentional:o,ts:i})}emitState(e){let r=this.now(),n=e.runState?{...e.runState,updatedAt:r}:{runId:`real-${e.pid}-${e.startedAt}`,agentId:e.agentId,conversationId:e.conversationId,status:XZ(e.phase),startedAt:e.startedAt,updatedAt:r,lastActivityAt:r};this.emit({event:"runtime_state",conversation_id:e.conversationId,agent_id:e.agentId,state:n,ts:r})}initTimeoutFor(e,r,n){if(this.initWatchdogMs!==null)return this.initWatchdogMs;let i={initLivenessSilenceMs:this.initLivenessSilenceMs,initPreProtocolCapMs:this.initPreProtocolCapMs,initPostProtocolMs:this.initPostProtocolMs}[r];return i!==void 0?i:e[r]??n}startInitWatchdog(e){this.clearInitWatchdog(e),e.initWatchdogArmed=!0,e.initStartedAt=this.now(),this.armInitLivenessSilenceWatchdog(e);let r=this.initTimeoutFor(e.driver,"initPreProtocolCapMs",LZ);e.initPreProtocolCapTimer=Vn(()=>{e.initPreProtocolCapTimer=null,this.failInitWatchdog(e,"pre_protocol_cap",r)},r),e.initPreProtocolCapTimer.unref()}clearInitWatchdog(e){e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null),e.initPreProtocolCapTimer&&(clearTimeout(e.initPreProtocolCapTimer),e.initPreProtocolCapTimer=null),e.initPostProtocolTimer&&(clearTimeout(e.initPostProtocolTimer),e.initPostProtocolTimer=null)}armInitLivenessSilenceWatchdog(e){e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null);let r=this.initTimeoutFor(e.driver,"initLivenessSilenceMs",jZ);e.initLivenessSilenceTimer=Vn(()=>{e.initLivenessSilenceTimer=null,this.failInitWatchdog(e,"silence",r)},r),e.initLivenessSilenceTimer.unref()}refreshInitLiveness(e){e.initWatchdogArmed&&(e.initObserved||e.initProtocolObserved||e.initTimedOut||this.armInitLivenessSilenceWatchdog(e))}observeInitProgress(e,r){if(!e.initWatchdogArmed||e.initObserved||e.initTimedOut)return;let n=e.driver.classifyInitProgress(r);n&&(this.markInitProtocolReady(e),n==="session_ready"&&this.clearInitWatchdog(e))}markInitProtocolReady(e){if(e.initProtocolObserved)return;e.initProtocolObserved=!0,e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null),e.initPreProtocolCapTimer&&(clearTimeout(e.initPreProtocolCapTimer),e.initPreProtocolCapTimer=null);let r=this.initTimeoutFor(e.driver,"initPostProtocolMs",FZ);e.initPostProtocolTimer=Vn(()=>{e.initPostProtocolTimer=null,this.failInitWatchdog(e,"post_protocol",r)},r),e.initPostProtocolTimer.unref()}ensureInitWatchdogArmed(e){e.initWatchdogArmed||e.initObserved||e.initTimedOut||this.startInitWatchdog(e)}failInitWatchdog(e,r,n){let o=dt(e.conversationId,e.agentId);if(!this.handles.has(o)||e.initObserved||e.initTimedOut)return;this.clearInitWatchdog(e),e.initTimedOut=!0,e.initTimeoutReason=r,e.phase="draining",this.emitState(e);let{retry:i,cooldownUntilOnEvent:a}=this.recordInitTimeout(e);e.initRetryPlanned=i;let c=this.now()-e.initStartedAt;this.logger.warn({kind:"process",action:"init_watchdog_fired",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,timeout_reason:r,elapsed_ms:c,timeout_ms:n,retry_attempt:e.initAttempt,retrying:i},"init watchdog fired; killing child"),this.emit({event:"runtime_init_timeout",conversation_id:e.conversationId,agent_id:e.agentId,timeout_reason:r,elapsed_ms:c,timeout_ms:n,retrying:i,retry_attempt:e.initAttempt,max_retries:this.initMaxRetries,...a!==null?{cooldown_until:a}:{},ts:this.now()});try{e.child.kill("SIGTERM")}catch{}Vn(()=>{if(this.handles.has(o)&&e.phase!=="exited")try{e.child.kill("SIGKILL")}catch{}},this.sigtermToSigkillMs).unref()}recordInitTimeout(e){let r=dt(e.conversationId,e.agentId),n=this.now(),o=this.initRetryStates.get(r)??{failures:0,cooldownUntil:0};o.failures+=1,o.failures>=this.initFailureCooldownThreshold&&(o.cooldownUntil=n+this.initFailureCooldownMs),this.initRetryStates.set(r,o);let i=o.cooldownUntil>n;return{retry:!i&&e.initAttempt<this.initMaxRetries&&!e.intentionalExit,cooldownUntilOnEvent:i?o.cooldownUntil:null}}clearInitRetryState(e,r){this.initRetryStates.delete(dt(e,r))}isInitCoolingDown(e){let r=this.initRetryStates.get(e);return!!r&&r.cooldownUntil>this.now()}async internalRespawnForRetry(e,r){try{await this.startWithLock(e,r)}catch(n){this.logger.error({kind:"process",action:"init_retry_respawn_failed",conversationId:e.conversation_id,agent_id:e.agent_id,retry_attempt:r,error_message:n.message},"init watchdog retry respawn failed")}}async withLifecycleLock(e,r){let n=this.lifecycleTails.get(e),o,i=new Promise(a=>{o=a});this.lifecycleTails.set(e,i);try{if(n)try{await n}catch{}return await r()}finally{o(),this.lifecycleTails.get(e)===i&&this.lifecycleTails.delete(e)}}startCompactionWatchdog(e){this.clearCompactionWatchdog(e);let r=this.now();e.compactionWatchdog=Vn(()=>{e.compactionWatchdog=null,this.fireCompactionStale(e,r)},this.compactionStaleMs),e.compactionWatchdog.unref()}clearCompactionWatchdog(e){e.compactionWatchdog&&(clearTimeout(e.compactionWatchdog),e.compactionWatchdog=null)}fireCompactionStale(e,r){if(!e.busy.compacting||e.phase==="exited"||e.phase==="draining")return;let n=this.now()-r;this.logger.warn({kind:"process",action:"compaction_stale",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,elapsed_ms:n},"compaction has been running past the stale window with no finish event"),this.emit({event:"runtime_compaction_stale",conversation_id:e.conversationId,agent_id:e.agentId,elapsed_ms:n,ts:this.now()}),this.transitionRunState(e,{compactionStale:!0})}};function XZ(t){switch(t){case"spawning":case"startup_pending":return"starting";case"ready":case"draining":case"exited":return"idle"}}function Gi(t){return t.readyToEncode?.()??!0}async function QZ(t){try{if((await OZ(t.path)).isDirectory())return;throw new or("workspace_path_missing",`runtime_start: resolved ${t.kind} workspace "${t.name}" (${t.id}) path is not a directory: ${t.path}`)}catch(e){if(e instanceof or)throw e;let r=typeof e=="object"&&e!==null&&"code"in e?String(e.code):null;throw r==="ENOENT"||r==="ENOTDIR"?new or("workspace_path_missing",`runtime_start: resolved ${t.kind} workspace "${t.name}" (${t.id}) path does not exist: ${t.path}`):new Error(`runtime_start: failed to access resolved ${t.kind} workspace "${t.name}" (${t.id}) path ${t.path}: `+(e instanceof Error?e.message:String(e)))}}function e4(t,e){return{...t??{},[e]:(t?.[e]??0)+1}}function t4(t){let e=t.replace(/\s+/g," ").trim();if(e)return e.length<=ug?e:e.slice(-ug)}var cg=null;async function r4(t,e){return cg||(cg=l0().then(n=>{let o=new Map;for(let i of n)i.installed&&i.binary&&o.set(i.kind,i.binary);return o})),(await cg).get(t)??null}import{mkdirSync as n4}from"node:fs";import{hostname as o4}from"node:os";import{join as ps}from"node:path";function s4(t){let e=null,r=null,n=null,o=!0;for(let i=0;i<t.length;i++){let a=t[i];switch(a){case"-h":case"--help":return{ok:!1,exitCode:0,message:gl()};case"--server-url":e=t[++i]??null;break;case"--connect-token":r=t[++i]??null;break;case"--data-root":n=t[++i]??null;break;case"--quiet":o=!1;break;case"--stderr":o=!0;break;default:return{ok:!1,exitCode:1,message:`unknown connect argument: ${a}
622
+ `);for(let c of a)c.length!==0&&this.dispatchParsedLine(e,c)}dispatchParsedLine(e,r){this.observeInitProgress(e,r);let n;try{n=e.driver.parseLine(r)}catch(o){this.logger.warn({kind:"process",action:"parse_line_threw",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,error_message:o.message},"driver.parseLine threw on stdout line");return}for(let o of n){let i=io.safeParse(o);if(!i.success){this.logger.warn({kind:"process",action:"parse_event_invalid",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,issue:i.error.issues[0]?.message??"unknown"},"driver.parseLine produced event that fails ParsedEventSchema");continue}this.updateRunStateFromParsed(e,i.data),this.emitParsedEvent(e,i.data)}}emitParsedEvent(e,r){let n={event:"runtime_parsed_event",conversation_id:e.conversationId,agent_id:e.agentId,parsed:r,ts:this.now()},o=null;try{o=Yt(n)}catch(c){this.logger.warn({kind:"process",action:"parse_event_too_large",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,parsed_kind:r.kind,error_message:c.message},"parsed event exceeds frame cap; emitting dropped marker")}if(o!==null){this.emit(n);return}let i=JSON.stringify({event:"runtime_parsed_event",conversation_id:e.conversationId,agent_id:e.agentId,parsed:r,ts:this.now()}),a=Buffer.byteLength(i,"utf-8")+1;this.emit({event:"runtime_parsed_event_dropped",conversation_id:e.conversationId,agent_id:e.agentId,parsed_kind:r.kind,encoded_bytes:a,reason:"frame_too_large",ts:this.now()})}updateRunStateFromParsed(e,r){if(r.kind==="session_init"){if(!e.initObserved){if(e.initObserved=!0,e.cliSessionId=r.sessionId,this.clearInitWatchdog(e),this.clearInitRetryState(e.conversationId,e.agentId),this.logger.info({kind:"process",action:"session_init",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,cli_session_id:r.sessionId},"agent: session_init received"),e.startupAwaitingInit&&e.startupDelivery){let n=e.startupDelivery.deliveryIds;this.emitStartupDeliveryConsumed(e,n),this.clearStartupGate(e),this.maybeEmitReadyForDrain(e)}this.tryConsumeStartupDelivery(e),this.maybeEmitReadyForDrain(e)}return}switch(!e.inputTurnActive&&w4(r)&&this.admitPendingSeqForNewTurn(e,"queued_delivery_admitted_on_activity"),r.kind){case"thinking":this.recordActivitySnippet(e,"thinking",r.text);break;case"text":this.recordActivitySnippet(e,"text",r.text);break;case"tool_call":e.busy.outstandingToolUses+=1;let n=r.name===v4?e.runState?.toolCallCounts:C4(e.runState?.toolCallCounts,r.name);this.transitionRunState(e,{status:"tool_running",detail:r.name,...n?{toolCallCounts:n}:{}});break;case"tool_output":e.busy.outstandingToolUses=Math.max(0,e.busy.outstandingToolUses-1),e.busy.outstandingToolUses===0&&!e.busy.compacting&&this.transitionRunState(e,{status:"thinking",detail:null});break;case"compaction_started":e.busy.compacting=!0,this.startCompactionWatchdog(e),this.transitionRunState(e,{compacting:!0,compactingSince:this.now(),compactionStale:!1});break;case"compaction_finished":e.busy.compacting=!1,this.clearCompactionWatchdog(e),this.transitionRunState(e,{compacting:!1,compactingSince:null,compactionStale:!1,...e.busy.outstandingToolUses===0?{status:"thinking",detail:null}:{}});break;case"turn_end":e.busy.outstandingToolUses=0,e.busy.compacting=!1,this.resolveRun(e,"turn_ended");break;case"error":r.fatal!==!0&&this.transitionRunState(e,{status:"thinking",detail:null,activitySnippet:r.message});break;case"unknown":break}}transitionRunState(e,r){let n=this.now();if(!e.runState){let c=r.status??"thinking";e.runState={runId:a4(),agentId:e.agentId,conversationId:e.conversationId,status:c,startedAt:n,updatedAt:n,lastActivityAt:n,...r.detail&&r.detail!==null?{detail:r.detail}:{},...r.terminalReason?{terminalReason:r.terminalReason}:{},...r.activitySnippet?{activitySnippet:r.activitySnippet}:{},...r.toolCallCounts?{toolCallCounts:r.toolCallCounts}:{},...r.compacting!==void 0?{compacting:r.compacting}:{},...r.compactingSince!==void 0&&r.compactingSince!==null?{compactingSince:r.compactingSince}:{},...r.compactionStale===!0?{compactionStale:!0}:{}},this.emitState(e);return}let o=e.runState,i={...o,updatedAt:n,lastActivityAt:n};r.status!==void 0&&(i.status=r.status),r.detail===null?delete i.detail:r.detail!==void 0&&(i.detail=r.detail),r.terminalReason!==void 0&&(i.terminalReason=r.terminalReason),r.activitySnippet===null?delete i.activitySnippet:r.activitySnippet!==void 0&&(i.activitySnippet=r.activitySnippet),r.toolCallCounts===null?delete i.toolCallCounts:r.toolCallCounts!==void 0&&(i.toolCallCounts=r.toolCallCounts),r.compacting!==void 0&&(i.compacting=r.compacting),r.compactingSince===null?delete i.compactingSince:r.compactingSince!==void 0&&(i.compactingSince=r.compactingSince),r.compactionStale===!0?i.compactionStale=!0:r.compactionStale===!1&&delete i.compactionStale,e.runState=i,(o.status!==i.status||o.detail!==i.detail||o.terminalReason!==i.terminalReason||o.activitySnippet!==i.activitySnippet||JSON.stringify(o.toolCallCounts??{})!==JSON.stringify(i.toolCallCounts??{})||o.compacting!==i.compacting||o.compactionStale!==i.compactionStale)&&this.emitState(e)}recordActivitySnippet(e,r,n){e.runState||this.transitionRunState(e,{status:"thinking",detail:null});let o=e.runState?.runId;if(!o)return;let i=this.appendActivitySnippetBuffer(e,o,r,n);this.transitionRunState(e,i?{activitySnippet:i}:{status:"thinking"})}appendActivitySnippetBuffer(e,r,n,o){let i=e.activitySnippetBuffer,a=i?.runId===r&&i.kind===n?`${i.text}${o}`:o,c=a.length<=A0?a:a.slice(-A0);return e.activitySnippetBuffer={runId:r,kind:n,text:c},T4(c)}clearActivitySnippetBuffer(e,r){let n=e.activitySnippetBuffer;n&&(r&&n.runId!==r||(e.activitySnippetBuffer=null))}resolveRun(e,r){let n=r==="replied"||r==="turn_ended"||r==="replaced"?"idle":"failed",o=this.now(),i=e.runState?{...e.runState,status:n,updatedAt:o,lastActivityAt:o,terminalReason:r,compacting:!1}:{runId:`real-${e.pid}-${e.startedAt}`,agentId:e.agentId,conversationId:e.conversationId,status:n,startedAt:e.startedAt,updatedAt:o,lastActivityAt:o,terminalReason:r};this.emit({event:"runtime_state",conversation_id:e.conversationId,agent_id:e.agentId,state:i,ts:o}),this.clearActivitySnippetBuffer(e,i.runId),e.runState=null,e.busy.outstandingToolUses=0,e.busy.compacting=!1,e.inputTurnActive=!1,e.defaultReplyTarget=vl,e.pendingDefaultReplyTarget=void 0}writeStdinPayload(e,r){return new Promise((n,o)=>{let i=e.child.stdin;if(!i||i.destroyed){o(new Error("child stdin is not writable"));return}let a=typeof r=="string"?r:JSON.stringify(r);i.write(a+`
623
+ `,u=>u?o(u):n())||i.once("drain",()=>n())})}writeRuntimePidfile(e){!this.runtimePidRootDir||!this.daemonInstanceId||s0({rootDir:this.runtimePidRootDir,daemonInstanceId:this.daemonInstanceId,...e})}unlinkRuntimePidfileForHandle(e){if(!(!this.runtimePidRootDir||!this.daemonInstanceId))try{i0({rootDir:this.runtimePidRootDir,daemonInstanceId:this.daemonInstanceId,conversationId:e.conversationId,agentId:e.agentId})}catch(r){this.logger.warn({kind:"process",action:"runtime_pidfile_unlink_failed",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,err:r.message},"failed to unlink runtime pidfile during child finalization")}}onChildExit(e,r,n){if(e.phase==="exited")return;if(e.sigkillTimer&&(clearTimeout(e.sigkillTimer),e.sigkillTimer=null),this.clearInitWatchdog(e),this.clearCompactionWatchdog(e),e.stdoutLineBuffer.length>0){let u=e.stdoutLineBuffer;e.stdoutLineBuffer="",this.dispatchParsedLine(e,u)}e.phase="exited",e.exitCode=r,this.unlinkRuntimePidfileForHandle(e);let o=e.intentionalExit,i=this.now(),a=pt(e.conversationId,e.agentId);if(this.logger.info({kind:"process",action:"exit",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,exit_code:r,signal:n??null,intentional:o,init_timed_out:e.initTimedOut,init_retry_planned:e.initRetryPlanned},"child exited"),e.startupDelivery!==null&&(this.emitStartupDeliveryFailed(e,e.startupDelivery.deliveryIds,e.initTimedOut?"init_watchdog":"child_exit"),this.clearStartupGate(e)),e.initTimedOut&&e.initRetryPlanned&&!e.intentionalExit){let u=e.initAttempt+1;this.emit({event:"runtime_init_retrying",conversation_id:e.conversationId,agent_id:e.agentId,retry_attempt:u,max_retries:this.initMaxRetries,delay_ms:0,ts:this.now()}),this.handles.delete(a),this.resolveRun(e,"timeout"),this.emit({event:"runtime_exit",conversation_id:e.conversationId,agent_id:e.agentId,code:r,intentional:!1,ts:i}),this.internalRespawnForRetry(e.spawnParams,u);return}if(e.initTimedOut){let u=this.initRetryStates.get(a);u&&u.cooldownUntil>this.now()&&this.emit({event:"runtime_init_cooldown",conversation_id:e.conversationId,agent_id:e.agentId,cooldown_until:u.cooldownUntil,attempts_exhausted:u.failures,ts:this.now()})}let c=e.initTimedOut?"timeout":o?"stopped":r===0?"replied":"crashed";this.resolveRun(e,c),this.emit({event:"runtime_exit",conversation_id:e.conversationId,agent_id:e.agentId,code:r,intentional:o,ts:i})}emitState(e){let r=this.now(),n=e.runState?{...e.runState,updatedAt:r}:{runId:`real-${e.pid}-${e.startedAt}`,agentId:e.agentId,conversationId:e.conversationId,status:P4(e.phase),startedAt:e.startedAt,updatedAt:r,lastActivityAt:r};this.emit({event:"runtime_state",conversation_id:e.conversationId,agent_id:e.agentId,state:n,ts:r})}initTimeoutFor(e,r,n){if(this.initWatchdogMs!==null)return this.initWatchdogMs;let i={initLivenessSilenceMs:this.initLivenessSilenceMs,initPreProtocolCapMs:this.initPreProtocolCapMs,initPostProtocolMs:this.initPostProtocolMs}[r];return i!==void 0?i:e[r]??n}startInitWatchdog(e){this.clearInitWatchdog(e),e.initWatchdogArmed=!0,e.initStartedAt=this.now(),this.armInitLivenessSilenceWatchdog(e);let r=this.initTimeoutFor(e.driver,"initPreProtocolCapMs",m4);e.initPreProtocolCapTimer=Kn(()=>{e.initPreProtocolCapTimer=null,this.failInitWatchdog(e,"pre_protocol_cap",r)},r),e.initPreProtocolCapTimer.unref()}clearInitWatchdog(e){e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null),e.initPreProtocolCapTimer&&(clearTimeout(e.initPreProtocolCapTimer),e.initPreProtocolCapTimer=null),e.initPostProtocolTimer&&(clearTimeout(e.initPostProtocolTimer),e.initPostProtocolTimer=null)}armInitLivenessSilenceWatchdog(e){e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null);let r=this.initTimeoutFor(e.driver,"initLivenessSilenceMs",p4);e.initLivenessSilenceTimer=Kn(()=>{e.initLivenessSilenceTimer=null,this.failInitWatchdog(e,"silence",r)},r),e.initLivenessSilenceTimer.unref()}refreshInitLiveness(e){e.initWatchdogArmed&&(e.initObserved||e.initProtocolObserved||e.initTimedOut||this.armInitLivenessSilenceWatchdog(e))}observeInitProgress(e,r){if(!e.initWatchdogArmed||e.initObserved||e.initTimedOut)return;let n=e.driver.classifyInitProgress(r);n&&(this.markInitProtocolReady(e),n==="session_ready"&&this.clearInitWatchdog(e))}markInitProtocolReady(e){if(e.initProtocolObserved)return;e.initProtocolObserved=!0,e.initLivenessSilenceTimer&&(clearTimeout(e.initLivenessSilenceTimer),e.initLivenessSilenceTimer=null),e.initPreProtocolCapTimer&&(clearTimeout(e.initPreProtocolCapTimer),e.initPreProtocolCapTimer=null);let r=this.initTimeoutFor(e.driver,"initPostProtocolMs",f4);e.initPostProtocolTimer=Kn(()=>{e.initPostProtocolTimer=null,this.failInitWatchdog(e,"post_protocol",r)},r),e.initPostProtocolTimer.unref()}ensureInitWatchdogArmed(e){e.initWatchdogArmed||e.initObserved||e.initTimedOut||this.startInitWatchdog(e)}failInitWatchdog(e,r,n){let o=pt(e.conversationId,e.agentId);if(!this.handles.has(o)||e.initObserved||e.initTimedOut)return;this.clearInitWatchdog(e),e.initTimedOut=!0,e.initTimeoutReason=r,e.phase="draining",this.emitState(e);let{retry:i,cooldownUntilOnEvent:a}=this.recordInitTimeout(e);e.initRetryPlanned=i;let c=this.now()-e.initStartedAt;this.logger.warn({kind:"process",action:"init_watchdog_fired",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,timeout_reason:r,elapsed_ms:c,timeout_ms:n,retry_attempt:e.initAttempt,retrying:i},"init watchdog fired; killing child"),this.emit({event:"runtime_init_timeout",conversation_id:e.conversationId,agent_id:e.agentId,timeout_reason:r,elapsed_ms:c,timeout_ms:n,retrying:i,retry_attempt:e.initAttempt,max_retries:this.initMaxRetries,...a!==null?{cooldown_until:a}:{},ts:this.now()});try{e.child.kill("SIGTERM")}catch{}Kn(()=>{if(this.handles.has(o)&&e.phase!=="exited")try{e.child.kill("SIGKILL")}catch{}},this.sigtermToSigkillMs).unref()}recordInitTimeout(e){let r=pt(e.conversationId,e.agentId),n=this.now(),o=this.initRetryStates.get(r)??{failures:0,cooldownUntil:0};o.failures+=1,o.failures>=this.initFailureCooldownThreshold&&(o.cooldownUntil=n+this.initFailureCooldownMs),this.initRetryStates.set(r,o);let i=o.cooldownUntil>n;return{retry:!i&&e.initAttempt<this.initMaxRetries&&!e.intentionalExit,cooldownUntilOnEvent:i?o.cooldownUntil:null}}clearInitRetryState(e,r){this.initRetryStates.delete(pt(e,r))}isInitCoolingDown(e){let r=this.initRetryStates.get(e);return!!r&&r.cooldownUntil>this.now()}async internalRespawnForRetry(e,r){try{await this.startWithLock(e,r)}catch(n){this.logger.error({kind:"process",action:"init_retry_respawn_failed",conversationId:e.conversation_id,agent_id:e.agent_id,retry_attempt:r,error_message:n.message},"init watchdog retry respawn failed")}}async withLifecycleLock(e,r){let n=this.lifecycleTails.get(e),o,i=new Promise(a=>{o=a});this.lifecycleTails.set(e,i);try{if(n)try{await n}catch{}return await r()}finally{o(),this.lifecycleTails.get(e)===i&&this.lifecycleTails.delete(e)}}startCompactionWatchdog(e){this.clearCompactionWatchdog(e);let r=this.now();e.compactionWatchdog=Kn(()=>{e.compactionWatchdog=null,this.fireCompactionStale(e,r)},this.compactionStaleMs),e.compactionWatchdog.unref()}clearCompactionWatchdog(e){e.compactionWatchdog&&(clearTimeout(e.compactionWatchdog),e.compactionWatchdog=null)}fireCompactionStale(e,r){if(!e.busy.compacting||e.phase==="exited"||e.phase==="draining")return;let n=this.now()-r;this.logger.warn({kind:"process",action:"compaction_stale",pid:e.pid,conversationId:e.conversationId,agent_id:e.agentId,elapsed_ms:n},"compaction has been running past the stale window with no finish event"),this.emit({event:"runtime_compaction_stale",conversation_id:e.conversationId,agent_id:e.agentId,elapsed_ms:n,ts:this.now()}),this.transitionRunState(e,{compactionStale:!0})}};function P4(t){switch(t){case"spawning":case"startup_pending":return"starting";case"ready":case"draining":case"exited":return"idle"}}function Ji(t){return t.readyToEncode?.()??!0}async function E4(t){try{if((await c4(t.path)).isDirectory())return;throw new sr("workspace_path_missing",`runtime_start: resolved ${t.kind} workspace "${t.name}" (${t.id}) path is not a directory: ${t.path}`)}catch(e){if(e instanceof sr)throw e;let r=typeof e=="object"&&e!==null&&"code"in e?String(e.code):null;throw r==="ENOENT"||r==="ENOTDIR"?new sr("workspace_path_missing",`runtime_start: resolved ${t.kind} workspace "${t.name}" (${t.id}) path does not exist: ${t.path}`):new Error(`runtime_start: failed to access resolved ${t.kind} workspace "${t.name}" (${t.id}) path ${t.path}: `+(e instanceof Error?e.message:String(e)))}}function C4(t,e){return{...t??{},[e]:(t?.[e]??0)+1}}function T4(t){let e=t.replace(/\s+/g," ").trim();if(e)return e.length<=fg?e:e.slice(-fg)}async function O0(t=!1){let e=await iy({force:t}),r=new Map;for(let n of e)n.installed&&n.binary&&r.set(n.kind,n.binary);return r}async function A4(t,e){let n=(await O0(!1)).get(t);return n||((await O0(!0)).get(t)??null)}import{mkdirSync as I4}from"node:fs";import{hostname as $4}from"node:os";import{join as ms}from"node:path";function z4(t){let e=null,r=null,n=null,o=!0;for(let i=0;i<t.length;i++){let a=t[i];switch(a){case"-h":case"--help":return{ok:!1,exitCode:0,message:bl()};case"--server-url":e=t[++i]??null;break;case"--connect-token":r=t[++i]??null;break;case"--data-root":n=t[++i]??null;break;case"--quiet":o=!1;break;case"--stderr":o=!0;break;default:return{ok:!1,exitCode:1,message:`unknown connect argument: ${a}
623
624
 
624
- ${gl()}`}}}return e?r?n!==null&&!n.startsWith("/")?{ok:!1,exitCode:1,message:"--data-root must be absolute"}:{ok:!0,options:{serverUrl:e,connectToken:r,dataRoot:n,alsoStderr:o}}:{ok:!1,exitCode:1,message:`--connect-token is required
625
+ ${bl()}`}}}return e?r?n!==null&&!n.startsWith("/")?{ok:!1,exitCode:1,message:"--data-root must be absolute"}:{ok:!0,options:{serverUrl:e,connectToken:r,dataRoot:n,alsoStderr:o}}:{ok:!1,exitCode:1,message:`--connect-token is required
625
626
 
626
- ${gl()}`}:{ok:!1,exitCode:1,message:`--server-url is required
627
+ ${bl()}`}:{ok:!1,exitCode:1,message:`--server-url is required
627
628
 
628
- ${gl()}`}}async function R0(t,e=process.env){let r=s4(t);if(!r.ok)return(r.exitCode===0?process.stdout:process.stderr).write(`silverhand-daemon connect: ${r.message}
629
- `),r.exitCode;let n=b_(e);try{vo(r.options.serverUrl,{allowInsecureRemote:n})}catch(d){return process.stderr.write(`silverhand-daemon connect: invalid --server-url: ${d.message}
630
- `),1}let o;try{o=await i4({serverUrl:r.options.serverUrl,connectToken:r.options.connectToken})}catch(d){return process.stderr.write(`silverhand-daemon connect: ${d.message}
631
- `),1}let i=r.options.dataRoot??e0(o);n4(i,{recursive:!0});let a={server_url:r.options.serverUrl,host_id:o,host_token:r.options.connectToken,...n?{allow_insecure_remote:!0}:{}},c={daemon_id:o,host_descriptor:{name:o4()||"Computer",kind:"remote"}},u=ps(i,"logs"),l=await sl({socketPath:ps(i,"daemon.sock"),pidFilePath:ps(i,"daemon.pid"),logDir:u,runtimePidRootDir:ps(i,"runtime-pids"),agentHomeRootDir:ps(i,"agents"),proxyConfigPath:ps(i,"proxy-config.json"),hostConfig:a,daemonIdentity:c,daemonIdentityPath:null,installSignals:!0,writeStdoutHandshake:!1,alsoStderr:r.options.alsoStderr,supervisorFactory:d=>new ds(d)});return Ar(l.logger,{action:"connect_ready",pid:process.pid,host_id:o,data_root:i,log_dir:u}),null}async function i4(t){let e=new URL(va.hostConnectTokenResolve,t.serverUrl),r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t.connectToken}`,Accept:"application/json"}});if(!r.ok)throw new Error(`server rejected connection command (${r.status} ${r.statusText})`);let n=await r.json();if(!n||typeof n!="object"||typeof n.host_id!="string"||!n.host_id)throw new Error("server returned an invalid connect-token resolve response");return n.host_id}function gl(){return["Usage:"," silverhand-daemon connect --server-url <url> --connect-token <token> [--data-root <abs>]","","Options:"," --server-url Silverhand server URL."," --connect-token Connection credential shown once by the app."," --data-root Optional absolute root for daemon runtime files."," --quiet Do not mirror daemon logs to stderr."].join(`
632
- `)}function a4(t){let e=null,r=null,n=null,o=null,i=null,a=null,c=null,u=null,l=null,d=null,p=!1;for(let m=0;m<t.length;m++){let f=t[m];switch(f){case"--socket-path":e=t[++m]??null;break;case"--pid-file":r=t[++m]??null;break;case"--log-dir":n=t[++m]??null;break;case"--host-config":o=t[++m]??null;break;case"--local-outbound-socket-path":i=t[++m]??null;break;case"--runtime-pid-root-dir":a=t[++m]??null;break;case"--agent-home-root-dir":c=t[++m]??null;break;case"--proxy-config-path":u=t[++m]??null;break;case"--legacy-proxy-config-path":l=t[++m]??null;break;case"--control-plane-server-url-path":d=t[++m]??null;break;case"--stderr":p=!0;break;default:return{error:`unknown argument: ${f}`}}}return e?r?n?e.startsWith("/")?r.startsWith("/")?n.startsWith("/")?o!==null&&!o.startsWith("/")?{error:"--host-config must be absolute"}:i!==null&&!i.startsWith("/")?{error:"--local-outbound-socket-path must be absolute"}:a!==null&&!a.startsWith("/")?{error:"--runtime-pid-root-dir must be absolute"}:c!==null&&!c.startsWith("/")?{error:"--agent-home-root-dir must be absolute"}:u!==null&&!u.startsWith("/")?{error:"--proxy-config-path must be absolute"}:l!==null&&!l.startsWith("/")?{error:"--legacy-proxy-config-path must be absolute"}:d!==null&&!d.startsWith("/")?{error:"--control-plane-server-url-path must be absolute"}:{socketPath:e,pidFilePath:r,logDir:n,hostConfigPath:o,localOutboundSocketPath:i,runtimePidRootDir:a,agentHomeRootDir:c,proxyConfigPath:u,legacyProxyConfigPath:l,controlPlaneServerUrlPath:d,alsoStderr:p}:{error:"--log-dir must be absolute"}:{error:"--pid-file must be absolute"}:{error:"--socket-path must be absolute"}:{error:"--log-dir is required"}:{error:"--pid-file is required"}:{error:"--socket-path is required"}}async function c4(){let t=process.argv.slice(2);if(t[0]==="connect"){let r=await R0(t.slice(1));r!==null&&process.exit(r);return}let e=a4(t);"error"in e&&(process.stderr.write(`silverhand-daemon: ${e.error}
633
- `),process.exit(1));try{await sl({socketPath:e.socketPath,pidFilePath:e.pidFilePath,logDir:e.logDir,hostConfigPath:e.hostConfigPath,localOutboundSocketPath:e.localOutboundSocketPath,runtimePidRootDir:e.runtimePidRootDir??void 0,agentHomeRootDir:e.agentHomeRootDir??void 0,proxyConfigPath:e.proxyConfigPath??void 0,legacyProxyConfigPath:e.legacyProxyConfigPath??void 0,controlPlaneServerUrlPath:e.controlPlaneServerUrlPath??void 0,installSignals:!0,writeStdoutHandshake:!0,alsoStderr:e.alsoStderr,supervisorFactory:r=>new ds(r)})}catch(r){let n=r;process.stderr.write(`silverhand-daemon: ${n.message}
634
- `),process.exit(n.code==="EALREADY"?2:1)}}c4();
629
+ ${bl()}`}}async function D0(t,e=process.env){let r=z4(t);if(!r.ok)return(r.exitCode===0?process.stdout:process.stderr).write(`silverhand-daemon connect: ${r.message}
630
+ `),r.exitCode;let n=E_(e);try{bo(r.options.serverUrl,{allowInsecureRemote:n})}catch(d){return process.stderr.write(`silverhand-daemon connect: invalid --server-url: ${d.message}
631
+ `),1}let o;try{o=await O4({serverUrl:r.options.serverUrl,connectToken:r.options.connectToken})}catch(d){return process.stderr.write(`silverhand-daemon connect: ${d.message}
632
+ `),1}let i=r.options.dataRoot??p0(o);I4(i,{recursive:!0});let a={server_url:r.options.serverUrl,host_id:o,host_token:r.options.connectToken,...n?{allow_insecure_remote:!0}:{}},c={daemon_id:o,host_descriptor:{name:$4()||"Computer",kind:"remote"}},u=ms(i,"logs"),l=await ul({socketPath:ms(i,"daemon.sock"),pidFilePath:ms(i,"daemon.pid"),logDir:u,runtimePidRootDir:ms(i,"runtime-pids"),agentHomeRootDir:ms(i,"agents"),proxyConfigPath:ms(i,"proxy-config.json"),hostConfig:a,daemonIdentity:c,daemonIdentityPath:null,installSignals:!0,writeStdoutHandshake:!1,alsoStderr:r.options.alsoStderr,supervisorFactory:d=>new ps(d)});return Ir(l.logger,{action:"connect_ready",pid:process.pid,host_id:o,data_root:i,log_dir:u}),null}async function O4(t){let e=new URL(ba.hostConnectTokenResolve,t.serverUrl),r=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t.connectToken}`,Accept:"application/json"}});if(!r.ok)throw new Error(`server rejected connection command (${r.status} ${r.statusText})`);let n=await r.json();if(!n||typeof n!="object"||typeof n.host_id!="string"||!n.host_id)throw new Error("server returned an invalid connect-token resolve response");return n.host_id}function bl(){return["Usage:"," silverhand-daemon connect --server-url <url> --connect-token <token> [--data-root <abs>]","","Options:"," --server-url Silverhand server URL."," --connect-token Connection credential shown once by the app."," --data-root Optional absolute root for daemon runtime files."," --quiet Do not mirror daemon logs to stderr."].join(`
633
+ `)}function D4(t){let e=null,r=null,n=null,o=null,i=null,a=null,c=null,u=null,l=null,d=null,p=!1;for(let m=0;m<t.length;m++){let f=t[m];switch(f){case"--socket-path":e=t[++m]??null;break;case"--pid-file":r=t[++m]??null;break;case"--log-dir":n=t[++m]??null;break;case"--host-config":o=t[++m]??null;break;case"--local-outbound-socket-path":i=t[++m]??null;break;case"--runtime-pid-root-dir":a=t[++m]??null;break;case"--agent-home-root-dir":c=t[++m]??null;break;case"--proxy-config-path":u=t[++m]??null;break;case"--legacy-proxy-config-path":l=t[++m]??null;break;case"--control-plane-server-url-path":d=t[++m]??null;break;case"--stderr":p=!0;break;default:return{error:`unknown argument: ${f}`}}}return e?r?n?e.startsWith("/")?r.startsWith("/")?n.startsWith("/")?o!==null&&!o.startsWith("/")?{error:"--host-config must be absolute"}:i!==null&&!i.startsWith("/")?{error:"--local-outbound-socket-path must be absolute"}:a!==null&&!a.startsWith("/")?{error:"--runtime-pid-root-dir must be absolute"}:c!==null&&!c.startsWith("/")?{error:"--agent-home-root-dir must be absolute"}:u!==null&&!u.startsWith("/")?{error:"--proxy-config-path must be absolute"}:l!==null&&!l.startsWith("/")?{error:"--legacy-proxy-config-path must be absolute"}:d!==null&&!d.startsWith("/")?{error:"--control-plane-server-url-path must be absolute"}:{socketPath:e,pidFilePath:r,logDir:n,hostConfigPath:o,localOutboundSocketPath:i,runtimePidRootDir:a,agentHomeRootDir:c,proxyConfigPath:u,legacyProxyConfigPath:l,controlPlaneServerUrlPath:d,alsoStderr:p}:{error:"--log-dir must be absolute"}:{error:"--pid-file must be absolute"}:{error:"--socket-path must be absolute"}:{error:"--log-dir is required"}:{error:"--pid-file is required"}:{error:"--socket-path is required"}}async function M4(){let t=process.argv.slice(2);if(t[0]==="connect"){let r=await D0(t.slice(1));r!==null&&process.exit(r);return}let e=D4(t);"error"in e&&(process.stderr.write(`silverhand-daemon: ${e.error}
634
+ `),process.exit(1));try{await ul({socketPath:e.socketPath,pidFilePath:e.pidFilePath,logDir:e.logDir,hostConfigPath:e.hostConfigPath,localOutboundSocketPath:e.localOutboundSocketPath,runtimePidRootDir:e.runtimePidRootDir??void 0,agentHomeRootDir:e.agentHomeRootDir??void 0,proxyConfigPath:e.proxyConfigPath??void 0,legacyProxyConfigPath:e.legacyProxyConfigPath??void 0,controlPlaneServerUrlPath:e.controlPlaneServerUrlPath??void 0,installSignals:!0,writeStdoutHandshake:!0,alsoStderr:e.alsoStderr,supervisorFactory:r=>new ps(r)})}catch(r){let n=r;process.stderr.write(`silverhand-daemon: ${n.message}
635
+ `),process.exit(n.code==="EALREADY"?2:1)}}M4();