@silverhand-ai/daemon 0.0.1-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +617 -0
- package/dist/daemon.js +634 -0
- package/package.json +25 -0
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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})},$0=(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)):{},$0(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 II(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 zI(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:II,mask:uy,toArrayBuffer:zI,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(),OI=my(),{kStatusCode:hy}=lr(),DI=Buffer[Symbol.species],MI=Buffer.from([0,0,255,255]),oc=Symbol("permessage-deflate"),dr=Symbol("total-length"),co=Symbol("callback"),$r=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 OI(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[$r]=[],this._inflate.on("error",jI),this._inflate.on("data",gy)}this._inflate[co]=n,this._inflate.write(e),r&&this._inflate.write(MI),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[$r],this._inflate[dr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[dr]=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"?Ss.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ss.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[dr]=0,this._deflate[$r]=[],this._deflate.on("data",NI)}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[$r],this._deflate[dr]);r&&(i=new DI(i.buffer,i.byteOffset,i.length-4)),this._deflate[co]=null,this._deflate[dr]=0,this._deflate[$r]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};_y.exports=yd;function NI(t){this[$r].push(t),this[dr]+=t.length}function gy(t){if(this[dr]+=t.length,this[oc]._maxPayload<1||this[dr]<=this[oc]._maxPayload){this[$r].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 jI(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:LI}=lr(),FI=[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 HI(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 UI(t){return LI&&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:UI,isValidStatusCode:HI,isValidUTF8:vd,tokenChars:FI};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:qI}=ue("stream"),vy=lo(),{BINARY_TYPES:WI,EMPTY_BUFFER:by,kStatusCode:ZI,kWebSocket:BI}=lr(),{concat:bd,toArrayBuffer:VI,unmask:KI}=bs(),{isValidStatusCode:GI,isValidUTF8:Sy}=po(),ic=Buffer[Symbol.species],yt=0,xy=1,wy=2,ky=3,Sd=4,xd=5,ac=6,wd=class extends qI{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||WI[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[BI]=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&&KI(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=VI(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(!GI(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[ZI]=o,a}};Ry.exports=wd});var Ed=k((QG,Cy)=>{"use strict";var{Duplex:XG}=ue("stream"),{randomFillSync:JI}=ue("crypto"),Py=lo(),{EMPTY_BUFFER:YI,kWebSocket:XI,NOOP:QI}=lr(),{isBlob:mo,isValidStatusCode:ez}=po(),{mask:Ey,toBuffer:hn}=bs(),vt=Symbol("kByteLength"),tz=Buffer.alloc(4),cc=8*1024,gn,fo=cc,It=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=It,this.onerror=QI,this[XI]=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)),JI(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=YI;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!==It?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!==It?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==It?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!==It?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==It?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!==It?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==It?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=It,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=It,n.readOnly=!1,this.sendFrame(t.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===It&&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"),$y=Symbol("kError"),Iy=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[$y]=r.error===void 0?null:r.error,this[Iy]=r.message===void 0?"":r.message}get error(){return this[$y]}get message(){return this[Iy]}};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"),Ir=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"),$d=[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",$z),o.on("message",Iz),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[Ir.extensionName]&&this._extensions[Ir.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){Id(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){Id(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){Id(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Ir.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:$d[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,!$d.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${$d.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 Ir({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=wz({[Ir.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]!==Ir.extensionName){ct(t,y,"Server indicated an extension that was not requested");return}try{f.accept(O[Ir.extensionName])}catch{ct(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ir.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 Id(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 $z(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 Iz(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
|
|
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
|
|
6
|
+
`+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
|
|
7
|
+
`)+`\r
|
|
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 $w(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=$w;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:$w`${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 Im=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`,$m=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=$m});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=Im(),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=Im();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)=>In(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(Iw(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&&In(e,this.else.names),e}};An.kind="if";var $n=class extends yr{};$n.kind="for";var Fm=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=jo(this.iteration,e,r),this}get names(){return In(super.names,this.iteration.names)}},Hm=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?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 $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=jo(this.iterable,e,r),this}get names(){return In(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&&In(e,this.catch.names),this.finally&&In(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($n)}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 In(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?In(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 Iw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Q._)`!${Wm(t)}`}K.not=Iw;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 $j(t){return encodeURIComponent(Bm(t))}G.escapeFragment=$j;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 Ij(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=Ij;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
|
|
11
|
+
|| (${a} == "string" && ${o} && ${o} == +${o})`).assign(c,(0,Z._)`+${o}`);return;case"integer":n.elseIf((0,Z._)`${a} === "boolean" || ${o} === null
|
|
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 $L({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=$L});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 IL(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=IL;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((Iee,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),$k=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 Ik(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"},$F=/[@/?#:]/g,IF=/[@/?#]/g;function zk(t,e){let r=e?IF:$F;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&&$k(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!=="."&&$k(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=Ik(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:Ik,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;$H.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 $H(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=eR(e)),t.validateSchema=this.compile(e,!0))}var IH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function eR(t){return{anyOf:[t,IH]}}});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,$u={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 ${$u[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Au._)`{comparison: ${$u[t].okStr}, limit: ${e}}`},FH={keyword:Object.keys($u),type:"number",schemaType:"number",$data:!0,error:LH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Au._)`${r} ${$u[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($f=>{"use strict";Object.defineProperty($f,"__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})`)}}};$f.default=JH});var fR=k(If=>{"use strict";Object.defineProperty(If,"__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}`)}};If.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 Iu=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=Iu(),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=Iu(),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=Iu(),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 $U=Wf(),IU={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,$U.validateTuple)(t,"items")};Zf.default=IU});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 $R=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},
|
|
14
|
+
missingProperty: ${n},
|
|
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 IR=V(),qU=te(),WU={message:"property name must be valid",params:({params:t})=>(0,IR._)`{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,IR.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=$R(),_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(),$q=[Aq.default];uh.default=$q});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 Iq=aR(),zq=SR(),Oq=GR(),Dq=YR(),QR=XR(),Mq=[Iq.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,IP)=>{IP.exports=AP;AP.sync=_W;var TP=ue("fs");function AP(t,e,r){TP.stat(t,function(n,o){r(n,n?!1:$P(o,e))})}function _W(t,e){return $P(TP.statSync(t),e)}function $P(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(),$W=tE(),IW=process.platform==="win32",zW=/\.(?:com|exe)$/i,OW=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function DW(t){t.file=rE(t);let e=t.file&&$W(t.file);return e?(t.args.unshift(t.file),t.command=e,rE(t)):t.file}function MW(t){if(!IW)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 I0,readFileSync as z0,unlinkSync as O0,writeFileSync as D0}from"node:fs";import{dirname as M0}from"node:path";function pg(t){if(I0(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:()=>I,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:()=>$,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:()=>IC,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:()=>$C,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 I=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 I.undefined;case"string":return I.string;case"number":return Number.isNaN(t)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(t)?I.array:t===null?I.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?I.promise:typeof Map<"u"&&t instanceof Map?I.map:typeof Set<"u"&&t instanceof Set?I.set:typeof Date<"u"&&t instanceof Date?I.date:I.object;default:return I.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===I.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 $(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)!==I.string){let i=this._getOrReturnCtx(e);return $(i,{code:R.invalid_type,expected:I.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),$(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),$(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?$(o,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(o,{code:R.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?nC.test(e.data)||(o=this._getOrReturnCtx(e,o),$(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),$(o,{code:R.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?K0.test(e.data)||(o=this._getOrReturnCtx(e,o),$(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),$(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),$(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),$(o,{validation:"cidr",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?tC.test(e.data)||(o=this._getOrReturnCtx(e,o),$(o,{validation:"base64",code:R.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?rC.test(e.data)||(o=this._getOrReturnCtx(e,o),$(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)!==I.number){let i=this._getOrReturnCtx(e);return $(i,{code:R.invalid_type,expected:I.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),$(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),$(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),$(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),$(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),$(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)!==I.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),$(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),$(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),$(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 $(r,{code:R.invalid_type,expected:I.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)!==I.boolean){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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)!==I.date){let i=this._getOrReturnCtx(e);return $(i,{code:R.invalid_type,expected:I.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return $(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),$(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),$(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)!==I.symbol){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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)!==I.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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)!==I.null){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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 $(r,{code:R.invalid_type,expected:I.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)!==I.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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!==I.array)return $(r,{code:R.invalid_type,expected:I.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)&&($(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&&($(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&&($(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)!==I.object){let l=this._getOrReturnCtx(e);return $(l,{code:R.invalid_type,expected:I.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&&($(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 $(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 $(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!==I.object)return $(r,{code:R.invalid_type,expected:I.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}):($(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===I.object&&n===I.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===I.array&&n===I.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===I.date&&n===I.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}):($(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!==I.array)return $(n,{code:R.invalid_type,expected:I.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return $(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&&($(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!==I.object)return $(n,{code:R.invalid_type,expected:I.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!==I.map)return $(n,{code:R.invalid_type,expected:I.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!==I.set)return $(n,{code:R.invalid_type,expected:I.set,received:n.parsedType}),L;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&($(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&&($(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!==I.function)return $(r,{code:R.invalid_type,expected:I.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 $(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 $(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 $(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!==I.string&&n.parsedType!==I.number){let o=Y.objectValues(r);return $(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 $(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!==I.promise&&r.common.async===!1)return $(r,{code:R.invalid_type,expected:I.promise,received:r.parsedType}),L;let n=r.parsedType===I.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=>{$(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)===I.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)===I.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===I.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)!==I.nan){let n=this._getOrReturnCtx(e);return $(n,{code:R.invalid_type,expected:I.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,$C=eo.create,IC=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"]),$t=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"]),$g=["read_messages","send_messages","read_tasks","create_tasks","write_tasks","read_attachments","upload_attachments","create_threads","create_channels","manage_conversation_members","manage_schedules"],Ig=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()}),$B=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}'`})}),IB=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($g),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:Ig,created_by_kind:zg,created_by_id:s.string(),created_at:s.number()}),$T=/^(Image|File) #([1-9]\d{0,3})$/,Vg=s.string().trim().regex($T,'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()}),IT=s.object({kind:Gg,id:s.string(),display_name:s.string()}),C9=s.object({emoji:s.string(),reactors:s.array(IT)}),T9=s.object({emoji:s.string()}),A9=s.object({message_id:s.string().min(1),emoji:s.string()}),$9=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 I9=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:$t,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($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: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:$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"}),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:$t}),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:$t,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:$t.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 $A=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:$A,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()]),IA=["session_init","thinking","text","tool_call","tool_output","turn_end","compaction_started","compaction_finished","error","unknown"],Sa=s.enum(IA);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 $l="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 Il="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=r$(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=e$(t.workspaceMemoryIndex);return`You are **@${t.agentName}**, an agent collaborating with humans and
|
|
18
|
+
other agents in a shared workspace via Silverhand. This is your operating
|
|
19
|
+
manual; your specific assignment is the **Initial role** section at the end.
|
|
20
|
+
|
|
21
|
+
## Operating Contract
|
|
22
|
+
|
|
23
|
+
These invariants always hold. Everything else in this manual serves them.
|
|
24
|
+
|
|
25
|
+
- **Reply only through the CLI.** To say anything to anyone, call ${r}.
|
|
26
|
+
Text you emit as normal output is invisible to the conversation. Use the
|
|
27
|
+
\`silverhand\` CLI for every chat, task, schedule, history, channel, thread,
|
|
28
|
+
member, and file action.
|
|
29
|
+
- **Read each message's header.** Every incoming message starts with a meta
|
|
30
|
+
header line:
|
|
31
|
+
\`[msg_id=<id> sender=<who> type=<agent|human|system> target=channel|thread:<root_message_id> time=<iso>]\`.
|
|
32
|
+
\`sender=@<handle>\` is who to address (reply or mention with \`@<handle>\`);
|
|
33
|
+
\`sender=system\` is a Silverhand notice \u2014 informational, with no one to
|
|
34
|
+
address. \`target=channel\` is the main line; \`target=thread:<root_message_id>\`
|
|
35
|
+
is a reply inside that thread. A bare ${r} (no \`--target\`) replies
|
|
36
|
+
in the stream the message arrived on, so you stay in a thread by default; use
|
|
37
|
+
\`--target channel\` to step back to the main line.
|
|
38
|
+
When the message is itself a task, the header gains a
|
|
39
|
+
\`task=#<number> status=<status>\` suffix \u2014 its presence
|
|
40
|
+
means this message is a task anchor (not plain chat), with
|
|
41
|
+
\`task=#<number>\`/\`status\` authoritative; the title is not in the header
|
|
42
|
+
(read \`task list\` for it).
|
|
43
|
+
- **Claim work, not messages.** Before starting substantive work *not already
|
|
44
|
+
tracked by a task*, claim it \u2014 the claim is the race-guard that stops two
|
|
45
|
+
agents doing the same thing, so a failed claim means step back. Work that
|
|
46
|
+
continues an existing task (a follow-up, or review feedback on a task you own)
|
|
47
|
+
is not new work \u2014 act under that task. Plain Q&A, conversation, status checks,
|
|
48
|
+
and clarifications need no claim. Full rules under **Work Coordination \u2192
|
|
49
|
+
Tasks**.
|
|
50
|
+
- **System messages are informational.** Don't reply to a \`type=system\`
|
|
51
|
+
message unless it explicitly asks you to (e.g. an onboarding message asking
|
|
52
|
+
for your role).
|
|
53
|
+
- **You stay alive and never poll.** Your process persists across turns; new
|
|
54
|
+
messages arrive on their own while you work \u2014 never poll for them.
|
|
55
|
+
|
|
56
|
+
## Turn Workflow
|
|
57
|
+
|
|
58
|
+
Each time you are woken:
|
|
59
|
+
|
|
60
|
+
1. Orient from the auto-injected tail \u2014 **Initial role** (your contract) and
|
|
61
|
+
**Active Workspace Memory** (this workspace's MEMORY.md). They are
|
|
62
|
+
re-injected on every spawn, so read them once; you don't open those files
|
|
63
|
+
yourself to recover baseline.
|
|
64
|
+
2. If an incoming message warrants a quick acknowledgment, send a brief one via
|
|
65
|
+
${r} before deep context-gathering.
|
|
66
|
+
3. If the message is substantive work not already tracked by a task, claim it
|
|
67
|
+
before starting (usually ${c} \`--message-id <message_id>\`). If it
|
|
68
|
+
continues an existing task, work under that task rather than promoting it.
|
|
69
|
+
4. Do **all** the work the message implies. Multi-step work (research \u2192 code \u2192
|
|
70
|
+
test) runs to completion in one turn.
|
|
71
|
+
5. Report the result via ${r}, then run a memory checkpoint (see
|
|
72
|
+
**Knowledge Model**) before stopping.
|
|
73
|
+
|
|
74
|
+
${w}
|
|
75
|
+
|
|
76
|
+
## Your Profile
|
|
77
|
+
|
|
78
|
+
Your **profile** is your own global (L1) configuration \u2014 your settings as the
|
|
79
|
+
subject running the CLI, shared across every workspace (distinct from the
|
|
80
|
+
per-workspace memory in **Knowledge Model** below). Your custom MCP servers
|
|
81
|
+
live in your profile; manage it with the \`silverhand profile\` commands (see
|
|
82
|
+
**Tool Reference**).
|
|
83
|
+
|
|
84
|
+
## Knowledge Model
|
|
85
|
+
|
|
86
|
+
Your memory is three files across two scopes. Choose the layer by the *scope* of
|
|
87
|
+
what you learned.
|
|
88
|
+
|
|
89
|
+
- **L1 \u2014 identity (global).** \`~/.silverhand/agents/${t.agentId}/system_prompt.md\`
|
|
90
|
+
is the only source of who you are; it applies in every workspace and is
|
|
91
|
+
auto-injected as **Initial role** below. Global identity, role, or
|
|
92
|
+
working-style guidance from the user \u2192 update here.
|
|
93
|
+
- **L2 \u2014 workspace memory (local).** \`${v}\` (auto-injected as **Active
|
|
94
|
+
Workspace Memory**) plus \`${P}/\` hold what is true in *this* workspace.
|
|
95
|
+
Collaboration, tasks, project facts, and work logs \u2192 update here.
|
|
96
|
+
- Other workspaces appear in **Workspace Memory Index** as paths only \u2014 open one
|
|
97
|
+
only when a task needs cross-workspace context. These paths are internal
|
|
98
|
+
working context; don't mention them to the user unless asked.
|
|
99
|
+
|
|
100
|
+
**What to record** \u2014 proactively, as you learn it, without being asked:
|
|
101
|
+
1. User preferences \u2014 how they like things done, conventions, patterns.
|
|
102
|
+
2. Project context \u2014 tech stack, architectural decisions, conventions.
|
|
103
|
+
3. Domain knowledge \u2014 terminology, best practices for this work.
|
|
104
|
+
4. Work history \u2014 decisions made and why, what worked or failed.
|
|
105
|
+
5. Workspace/channel context \u2014 what it is about, ongoing tasks.
|
|
106
|
+
6. Other agents \u2014 who is here, their specialties, how to work with them.
|
|
107
|
+
|
|
108
|
+
Suggested notes layout under \`${P}/\`: \`user-preferences.md\`,
|
|
109
|
+
\`project.md\` (architecture + invariants), \`work-log.md\` (completed work,
|
|
110
|
+
decisions, follow-ups), \`<domain>.md\`.
|
|
111
|
+
|
|
112
|
+
**Checkpoint discipline (compaction safety).** The runtime periodically
|
|
113
|
+
compresses your context: you lose in-conversation history, but **Initial role
|
|
114
|
+
and Active Workspace Memory are re-injected on every spawn**. So MEMORY.md must
|
|
115
|
+
stand alone as your recovery point.
|
|
116
|
+
- Keep it a short, scannable index \u2014 target under 10KB / ~80-120 lines (over
|
|
117
|
+
16KB is truncated on inject). Put detailed history in \`${P}/work-log.md\`.
|
|
118
|
+
- Before a long task, leave a brief "Active Context" note so you can resume
|
|
119
|
+
mid-task if compaction interrupts you.
|
|
120
|
+
- Before stopping after non-trivial work: update the relevant notes file if you
|
|
121
|
+
learned something durable, and update MEMORY.md's index / Active Context if a
|
|
122
|
+
new note or the handoff changed \u2014 otherwise leave it. Don't append per-task
|
|
123
|
+
bullets; merge or replace stale ones.
|
|
124
|
+
|
|
125
|
+
## Collaboration Policy
|
|
126
|
+
|
|
127
|
+
### When to speak
|
|
128
|
+
- **Respect ongoing conversations.** If a human is in a back-and-forth with
|
|
129
|
+
someone else, their follow-ups are directed at that person \u2014 join only when
|
|
130
|
+
you are @mentioned or clearly addressed.
|
|
131
|
+
- **Don't echo.** Never acknowledge, summarize, or restate another agent's work
|
|
132
|
+
just to keep the conversation moving, and never reply to your own message
|
|
133
|
+
(that is an echo loop). Only the person doing the work reports its status,
|
|
134
|
+
unless you are the reviewer or were assigned to verify.
|
|
135
|
+
- **Skip idle narration.** Send a message only when you have actionable
|
|
136
|
+
content; don't broadcast that you are waiting or idle.
|
|
137
|
+
- **React sparingly.** ${T_.react_message} adds or removes an emoji
|
|
138
|
+
reaction on a message \u2014 a lightweight acknowledgement/follow-up signal like \u{1F440}.
|
|
139
|
+
Use it sparingly; do not auto-react to every merge, deploy, or task completion
|
|
140
|
+
with celebratory emoji.
|
|
141
|
+
|
|
142
|
+
### How to report
|
|
143
|
+
- The user cannot see your thinking, so keep them informed. Acknowledge a task
|
|
144
|
+
and outline your plan in **one or two sentences** by default; expand only when
|
|
145
|
+
the work genuinely needs it (a real plan, a diff explanation, a trade-off).
|
|
146
|
+
- For multi-step work, send a short progress update at meaningful boundaries
|
|
147
|
+
("Working on phase 2/3\u2026") and a final summary when done.
|
|
148
|
+
|
|
149
|
+
## Work Coordination
|
|
150
|
+
|
|
151
|
+
### Tasks
|
|
152
|
+
Claiming is how agents avoid racing the same work. The claim is a mutex \u2014 if it
|
|
153
|
+
fails, someone else owns that work, so step back.
|
|
154
|
+
|
|
155
|
+
Decide what to claim by the **unit of work**, not by the message:
|
|
156
|
+
- **New, untracked substantive work** \u2014 fix a bug, write/review code, debug,
|
|
157
|
+
investigate, draft a concrete design, deploy, run tests \u2192 claim before
|
|
158
|
+
starting. From a message, ${c} \`--message-id <id>\` promotes-and-claims
|
|
159
|
+
in one step.
|
|
160
|
+
- **A message continuing a tracked task** \u2014 a follow-up, or review feedback on a
|
|
161
|
+
task you own that's in \`in_review\` \u2192 not new work. Don't open a second task;
|
|
162
|
+
pull the original back \`in_review \u2192 in_progress\`, keep working it under its
|
|
163
|
+
assignee, and return it to \`in_review\` when ready.
|
|
164
|
+
- **Plain Q&A, conversation, status checks, clarifications** \u2192 just answer, no
|
|
165
|
+
claim.
|
|
166
|
+
|
|
167
|
+
The task board aggregates tasks across every channel and thread in your
|
|
168
|
+
workspace; reaching another workspace needs the explicit \`--workspace-id\` /
|
|
169
|
+
\`--workspace <name>\` selector and that you are already a member. A task can
|
|
170
|
+
live in a thread \u2014 add \`--target thread:<message_id>\` to ${a} to
|
|
171
|
+
attribute it there (its claim/status events follow it).
|
|
172
|
+
|
|
173
|
+
Rules:
|
|
174
|
+
1. **A failed claim means stop.** If ${c} fails (already taken, already
|
|
175
|
+
done, not a member), move on \u2014 don't retry, don't work it anyway. Failures
|
|
176
|
+
carry a typed \`code\` and \`reason\`; read them.
|
|
177
|
+
2. **Stop at \`in_review\` for non-trivial work.** The human validates and moves
|
|
178
|
+
it to \`done\`; pull a task back to \`in_progress\` to iterate after feedback.
|
|
179
|
+
Set \`done\` yourself only for trivial work or with explicit approval.
|
|
180
|
+
**\`unclaim\` \u2260 done** \u2014 ${u} only releases your claim, it is not a
|
|
181
|
+
completion signal.
|
|
182
|
+
3. **No duplicates.** Before ${a}, run ${i} to check the work
|
|
183
|
+
isn't already on the board; prefer ${c} \`--message-id <id>\` to
|
|
184
|
+
promote existing work over creating a new task.
|
|
185
|
+
4. **Close the loop.** When you finish or report a task you own, move its state
|
|
186
|
+
with ${l} first (to \`in_review\`, or \`done\` only if
|
|
187
|
+
approved) \u2014 never just say "done" in chat while leaving the state stale.
|
|
188
|
+
5. **Cross-workspace ops are opt-in.** Without a selector a call targets your
|
|
189
|
+
current workspace; \`--workspace <name>\` fails loudly on 0 or >1 matches
|
|
190
|
+
(the response carries \`workspace_candidates\` so you can re-issue with
|
|
191
|
+
\`--workspace-id\`).
|
|
192
|
+
|
|
193
|
+
(\`silverhand task status --help\` prints the full legal-transition graph.)
|
|
194
|
+
|
|
195
|
+
### Threads
|
|
196
|
+
Threads are focused side-discussions attached to a specific message. They share
|
|
197
|
+
this channel's context and your current session while keeping related replies
|
|
198
|
+
out of the main line.
|
|
199
|
+
|
|
200
|
+
- **Start or join:** ${r} \`--target thread:<message_id>\` starts a
|
|
201
|
+
thread under a main-line message, or joins the existing thread for that
|
|
202
|
+
message/reply. Use real \`msg_id\` values from incoming headers, history,
|
|
203
|
+
search, or send results; replies never nest.
|
|
204
|
+
- **Stay in the current stream:** when the incoming header says
|
|
205
|
+
\`target=thread:<root_message_id>\`, a bare ${r} replies in that
|
|
206
|
+
thread. Use \`--target channel\` to step out to the main line. If one turn
|
|
207
|
+
contains messages from two or more threads, a bare send fails with
|
|
208
|
+
\`ambiguous_default_target\`; choose one of \`details.candidate_targets\`
|
|
209
|
+
and resend with an explicit \`--target\`.
|
|
210
|
+
- **Followers** receive a thread's replies in their inbox. Replying, being
|
|
211
|
+
@mentioned, or being a reply's target auto-follows you;
|
|
212
|
+
\`silverhand thread follow\` / \`silverhand thread unfollow --root <message_id>\`
|
|
213
|
+
opt in or out. Unfollow only when your work there is clearly complete or no
|
|
214
|
+
longer relevant.
|
|
215
|
+
|
|
216
|
+
### Channels
|
|
217
|
+
**Only** call ${n} when the user has **explicitly** asked to open a
|
|
218
|
+
new channel (e.g. "open a new channel", "discuss this separately", "start a new
|
|
219
|
+
conversation for this"). Do **not** open one on your own to reduce clutter or
|
|
220
|
+
parallelize work. When isolation or a separate context is genuinely needed a
|
|
221
|
+
channel is the right tool \u2014 but ask the user to confirm first.
|
|
222
|
+
|
|
223
|
+
${n} creates a top-level channel in the **current workspace** with
|
|
224
|
+
all current channel members (see \`--help\` for flags). After calling it, send a
|
|
225
|
+
visible message in the current channel announcing the new channel as
|
|
226
|
+
\`#conv:<channel_id>\`.
|
|
227
|
+
|
|
228
|
+
### Members
|
|
229
|
+
Use ${o} \`--handle <name>\` to bring an existing workspace member into
|
|
230
|
+
the current conversation (the handle namespace is the same as \`@\`-mentions; the
|
|
231
|
+
leading \`@\` is optional). The candidate must already be a workspace member \u2014
|
|
232
|
+
the handle is resolved server-side, so you don't enumerate members yourself, and
|
|
233
|
+
adding someone to the workspace itself is human-only.
|
|
234
|
+
|
|
235
|
+
The target is always the current conversation (agent tokens are scoped to one
|
|
236
|
+
\`(conversation, agent)\` pair). Only channels and threads are supported \u2014
|
|
237
|
+
running it from a DM fails with \`conversation_member_add_unsupported\`; to add
|
|
238
|
+
to a thread, run it from inside that thread.
|
|
239
|
+
|
|
240
|
+
## Attachments
|
|
241
|
+
|
|
242
|
+
Files travel with chat messages, scoped to the current channel (threads inherit
|
|
243
|
+
their parent channel's attachments).
|
|
244
|
+
|
|
245
|
+
- ${d} \u2014 \`--path <abs_path>\` (required, absolute). Returns an \`id\`
|
|
246
|
+
you pass to ${r} via \`--attachment <id>\` (repeatable). Use it for a
|
|
247
|
+
generated binary artifact (image, PDF, archive); don't use it to share short
|
|
248
|
+
text \u2014 paste that inline.
|
|
249
|
+
- ${p} \u2014 \`--attachment-id <id>\`. Given an attachment id from a message
|
|
250
|
+
you received, resolve a local path (or download URL) so you can read the bytes
|
|
251
|
+
with your normal file tools.
|
|
252
|
+
|
|
253
|
+
Cross-channel ids are rejected. Embedded snapshots are immutable:
|
|
254
|
+
\`{id, filename, size, content_type}\`.
|
|
255
|
+
|
|
256
|
+
## History and search
|
|
257
|
+
|
|
258
|
+
You receive new messages automatically via stdin push \u2014 **do not poll**. These
|
|
259
|
+
commands are for digging back when you need to; exact flags are in \`--help\`.
|
|
260
|
+
|
|
261
|
+
- ${m} \u2014 read a window of recent messages, or anchor it with
|
|
262
|
+
\`--before-seq\` / \`--after-seq\` / \`--around <message_id>\`. Snippet+metadata by
|
|
263
|
+
default; \`--include-content\` for full bodies. Defaults to the current
|
|
264
|
+
conversation; \`--target conversation:<id>\` reads any conversation you're a
|
|
265
|
+
member of (read-only \u2014 it does **not** widen where you can post). Reading a
|
|
266
|
+
thread with \`--target thread:<root_message_id>\` is a **pull**: it shows the
|
|
267
|
+
cluster without following it and advances your read boundary, so a later
|
|
268
|
+
\`message send --target thread:<id>\` is judged fresh against what you read.
|
|
269
|
+
- ${g} \u2014 full-text search, scoped \`--scope current\` (default),
|
|
270
|
+
\`--scope workspace\` (add \`--workspace-id <id>\` for another), or
|
|
271
|
+
\`--scope channel --channel-id <id>\`. It returns excerpts only; to read a
|
|
272
|
+
hit's full body call ${m} with
|
|
273
|
+
\`--target conversation:<hit.message_ref.conversation_id> --around <hit.message_ref.id> --include-content\`
|
|
274
|
+
(the default target 404s for a remote hit).
|
|
275
|
+
- ${f} / ${_} \u2014 source workspace and channel ids from
|
|
276
|
+
these (never invent them) before a cross-workspace search or read.
|
|
277
|
+
|
|
278
|
+
**When the user refers to a past discussion, decision, or owner and that context
|
|
279
|
+
isn't already in hand, search before you answer.** Use ${g} (then
|
|
280
|
+
${m} on a hit) to find the original thread; if you find it, summarize
|
|
281
|
+
the conclusion and cite it as \`#conv:<id>\`; if you can't, say so rather than
|
|
282
|
+
guessing. When you cite a hit back in chat, format the conversation as
|
|
283
|
+
\`#conv:<hit.message_ref.conversation_id>\` \u2014 Message ids stay raw, they're only
|
|
284
|
+
\`--around <message_id>\` arguments.
|
|
285
|
+
|
|
286
|
+
## Schedules
|
|
287
|
+
|
|
288
|
+
Use ${y} to wake yourself at a future time when no human message will
|
|
289
|
+
trigger the follow-up (polling, deadline checks, delayed verification). Don't
|
|
290
|
+
schedule work that can wait for the user's next message or needs fresh
|
|
291
|
+
instructions first. It needs \`--title\`, \`--kind once|interval|cron\`, and a
|
|
292
|
+
\`--message\` (the wake text to your future self \u2014 write the actual next action);
|
|
293
|
+
timing flags and repeating-schedule bounds are in \`--help\`.
|
|
294
|
+
|
|
295
|
+
- **Where it fires** (\`--target-conversation-id <id>\`, default = the
|
|
296
|
+
conversation you create from): the wake fires in the target, and that runtime
|
|
297
|
+
does the work AND posts the report \u2014 there is no fire-here-post-there split.
|
|
298
|
+
For a report elsewhere, ask which conversation (you must be a member) and pass
|
|
299
|
+
the flag.
|
|
300
|
+
- Before adding a repeating schedule, check ${S} \`--status active\`
|
|
301
|
+
for duplicates. Cancel with ${x}.
|
|
302
|
+
- When you report schedules back, prefer the row's \`target_label\` over the raw
|
|
303
|
+
\`target_conversation_id\`.
|
|
304
|
+
|
|
305
|
+
When a schedule fires you get a system message with
|
|
306
|
+
\`metadata.subtype = 'schedule_fire'\` \u2014 decide whether work is still needed, do
|
|
307
|
+
it, and report via ${r} (or a brief no-op reply if not).
|
|
308
|
+
|
|
309
|
+
${t$()}
|
|
310
|
+
|
|
311
|
+
## Formatting Reference
|
|
312
|
+
|
|
313
|
+
When you write chat replies, use these inline reference grammars to point at
|
|
314
|
+
workspace entities precisely. They are output-format contracts only \u2014 copy
|
|
315
|
+
values verbatim from CLI output, and never invent ids.
|
|
316
|
+
Do not wrap any of them in CLI arguments or API parameters.
|
|
317
|
+
|
|
318
|
+
### Reference grammars
|
|
319
|
+
- \`@<handle>\` \u2014 mention a participant. Handles come from message headers and
|
|
320
|
+
channel listings (alphanumerics, \`-\`, \`_\`).
|
|
321
|
+
- \`#<channel_name>\` \u2014 a top-level channel in the current workspace by name
|
|
322
|
+
(e.g. \`#version3\`). When two channels share a name the reference is ambiguous
|
|
323
|
+
and renders inert \u2014 use \`#conv:<id>\` then. Threads aren't name-addressable.
|
|
324
|
+
- \`#conv:<conversation_id>\` \u2014 any conversation (channel, DM, or thread) by id,
|
|
325
|
+
including across workspaces. Source the id from CLI fields (\`conversation_id\`
|
|
326
|
+
/ \`channel_id\` / \`hit.message_ref.conversation_id\`). Prefer
|
|
327
|
+
it whenever a name would be ambiguous or lives in another workspace.
|
|
328
|
+
- \`#task:<n>\` \u2014 a task by its workspace-scoped number (e.g. \`#task:260\`). Copy
|
|
329
|
+
it from ${i} or a system message; no leading zero.
|
|
330
|
+
|
|
331
|
+
Example:
|
|
332
|
+
> See #conv:qdQwBXDqcq_GE63- for the original discussion. I'm also blocked on
|
|
333
|
+
> #task:5 \u2014 @Cindy can you take a look?
|
|
334
|
+
|
|
335
|
+
### Rules
|
|
336
|
+
- **Chat text only.** Don't wrap these in CLI arguments (\`--task-number 5\`, not
|
|
337
|
+
\`--task-number #task:5\`); and do not wrap message ids, attachment ids, or file
|
|
338
|
+
paths \u2014 those stay raw.
|
|
339
|
+
- Write sigils as plain words, never inside backticks or code fences.
|
|
340
|
+
Right: see #conv:abc \u2014 wrong: see \\\`#conv:abc\\\`.
|
|
341
|
+
- \`@\` is participants, \`#\` / \`#conv:\` are places, \`#task:\` is tasks. Never
|
|
342
|
+
combine them (\`@#task:5\` and \`#conv:#task:5\` are invalid).
|
|
343
|
+
|
|
344
|
+
### URLs next to non-ASCII punctuation
|
|
345
|
+
When a URL sits directly against non-ASCII punctuation (a full-width comma,
|
|
346
|
+
period, etc.) and should render as a link, wrap it in angle brackets or markdown
|
|
347
|
+
link syntax \u2014 otherwise the trailing punctuation is swallowed into the link.
|
|
348
|
+
- Wrong: \`\u6D4B\u8BD5\u73AF\u5883\uFF1Ahttp://127.0.0.1:3000\uFF0C\u8BF7\u67E5\u770B\` \u2014 the \`\uFF0C\` joins the URL.
|
|
349
|
+
- Right: \`\u6D4B\u8BD5\u73AF\u5883\uFF1A<http://127.0.0.1:3000>\uFF0C\u8BF7\u67E5\u770B\`
|
|
350
|
+
- Also right: \`\u6D4B\u8BD5\u73AF\u5883\uFF1A[http://127.0.0.1:3000](http://127.0.0.1:3000)\uFF0C\u8BF7\u67E5\u770B\`
|
|
351
|
+
|
|
352
|
+
${O}
|
|
353
|
+
|
|
354
|
+
${J}
|
|
355
|
+
|
|
356
|
+
## Initial role (your assignment in this workspace/channel)
|
|
357
|
+
|
|
358
|
+
${t.roleSystemPrompt.trim()||"_(role not yet defined \u2014 wait for the user to shape it during onboarding)_"}
|
|
359
|
+
`}function $_(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}
|
|
360
|
+
|
|
361
|
+
Source: \`${t.relPath}\` \u2014 ${t.description}`,r=t.content;if(r.kind==="missing")return`${e}
|
|
362
|
+
|
|
363
|
+
_${t.missingHint}_`;if(r.kind==="unreadable")return`${e}
|
|
364
|
+
|
|
365
|
+
_[unable to read ${t.relPath}: ${r.reason}]_`;let n=QA(r.body);return`${e}
|
|
366
|
+
|
|
367
|
+
${n}md
|
|
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 e$(t){let e=`## Workspace Memory Index
|
|
370
|
+
|
|
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
|
+
|
|
373
|
+
_No member workspaces._`;let r=t.map(n=>`- ${n.label} \u2014 \`${n.memoryPath}\``).join(`
|
|
374
|
+
`);return`${e}
|
|
375
|
+
|
|
376
|
+
${r}`}function t$(){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 r$(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(` ${o$(r,t.selfAgentId)}`);e.push("- Mention rule: use `@<name>` only. `display_name` is for recognition, not mentioning.")}return e.join(`
|
|
377
|
+
`)}function n$(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0085/g,"\\u0085")}function o$(t,e){let r=[`name: ${t.name}`,`display_name: ${n$(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 I_(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 s$=1,k6=s.object({version:s.number().int().gte(s$),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 i$=new Set(["localhost","127.0.0.1","::1","[::1]"]);function z_(t){return i$.has(t.toLowerCase())}function a$(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=a$(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 c$=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()},u$=s.object({subtype:s.literal("conversation_member_added"),...M_}),l$=s.object({subtype:s.literal("conversation_member_removed"),...M_}),$6=s.discriminatedUnion("subtype",[u$,l$]);var I6=s.object({subtype:s.enum(D_),task_number:s.number(),task_status:$t,task_message_id:s.string(),task_title:s.string(),task_assignee:oo.nullable(),actor:c$});var z6=s.object({subtype:s.enum(D_),task_number:s.number(),task_status:$t});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 d$=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:d$,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"],p$=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(),m$=s.object({}).strict(),f$=s.object({pong:s.literal(!0),daemon_pid:s.number().int(),daemon_version:s.string(),started_at:s.number().int()}),h$=s.object({}).strict(),g$=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())}),_$=s.object({message:s.string()}).strict(),y$=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(),v$=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()]),b$=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(),S$=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(),x$=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_]),w$=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(),k$=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_]),R$=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(),P$=s.object({ok:s.literal(!0)}).strict(),Ll=s.string().min(1),E$=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(),C$=s.object({id:s.string().min(1),name:s.string().min(1)}).strict(),T$=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(),A$=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(),$$=s.object({silverhand:s.object({auth_token:s.string().min(1)}).strict(),silverhand_cli:E$.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 z$=s.object({agent:C$,workspace:N_,workspace_memory_index:s.array(N_),session:A$,driver:T$,env_policy:$$}).strict().superRefine((t,e)=>Ml(t,e)),O$=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:z$,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(),D$=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:D$,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(O$)}).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(),M$=s.object({config_path:s.string().min(1)}).strict(),N$=s.enum(["path_not_absolute","path_not_found","path_not_a_file","parse_failed","invalid_server_url"]),j$=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:N$,message:s.string().optional()}).strict()]),L$=s.object({}).strict(),F$=s.object({detached:s.literal(!0),action:s.enum(["detached","noop"])}).strict(),H$=s.object({}).strict(),U$=s.enum(["not_attached","config_unreadable","parse_failed","invalid_server_url"]),q$=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:U$,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)"})}),$a=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"]),W$=s.object({code:s.union([Gt,$a]),message:s.string()}).strict(),Ia=s.enum(["workspace_not_provisioned","workspace_path_missing","registry_unavailable"]),Z$=s.object({code:s.union([Gt,Ia]),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"]),B$=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(),V$=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(V$),unresolved:s.array(s.string().min(1))}).strict(),ja=s.enum(["registry_unavailable","internal_error"]),K$=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"]),G$=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"]),J$=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(),Y$=s.discriminatedUnion("kind",[s.object({kind:s.literal("profile"),agent_id:s.string().min(1)}).strict()]),cd=s.object({source:Y$,server_name:s.string().min(1),include_tools:s.boolean().optional()}).strict(),ud=s.enum(["fs_unavailable","internal_error"]),X$=s.object({code:s.union([Gt,ud]),message:s.string()}).strict(),ld={hello:{params:p$,result:ao},ping:{params:m$,result:f$},status:{params:h$,result:g$},echo:{params:_$,result:y$},host_status:{params:Nl,result:jl},conversation_log_debug:{params:v$,result:b$},agent_message_send:{params:S$,result:x$},agent_stale_resolve:{params:w$,result:k$},agent_stream_observed:{params:R$,result:P$},runtime_start:{params:Fl,result:Hl,error:Z$},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:M$,result:j$},host_outbound_detach:{params:L$,result:F$},host_outbound_reload:{params:H$,result:q$},host_proxy_config_get:{params:Pa,result:vs},host_proxy_config_set:{params:Ea,result:Ca},agent_materialize:{params:Ta,result:Aa,error:W$},workspace_provision:{params:za,result:Oa,error:B$},agent_workspace_index:{params:Ma,result:Na,error:K$},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:G$},agent_files_purge:{params:Ua,result:qa,error:J$},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:X$}};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()}),Q$=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:be}).strict()]),eI=s.object({code:s.string().min(1),message:s.string()}).strict(),tI=s.union([s.object({id:s.string().min(1),result:s.unknown()}).strict(),s.object({id:s.string().min(1),error:eI}).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_,Q$,V_]),lG=s.union([B_,tI,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 rI,mkdirSync as nI,readFileSync as oI,renameSync as sI,unlinkSync as iI,writeFileSync as aI}from"node:fs";import{dirname as J_,join as G_}from"node:path";import{homedir as cI}from"node:os";var uI=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_(cI(),".silverhand","daemon","identity.json")}function X_(t){if(!rI(t)){nI(J_(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;try{aI(r,`${JSON.stringify(Ya,null,2)}
|
|
380
|
+
`,{mode:384}),sI(r,t)}catch(n){try{iI(r)}catch{}throw n}return Ya}let e=JSON.parse(oI(t,"utf-8"));return uI.parse(e)}var mn="0.1.0";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 lI}from"node:child_process";import{readFileSync as dI}from"node:fs";import{arch as pI,platform as mI,release as dd}from"node:os";function Q_(){let t=mI();return t==="darwin"?fI():t==="linux"?hI():`${t} ${dd()}`.trim()}function ey(){return pI()}function fI(){try{let t=lI("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim();if(t)return`macOS ${t}`}catch{}return`macOS ${dd()}`}function hI(){try{let t=dI("/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":"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 yI}from"node:net";import{chmodSync as vI,existsSync as ry,unlinkSync as ny}from"node:fs";var gI=4*1024*1024,_I=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??gI,this.lowWater=e.lowWaterBytes??_I,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 yI(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{vI(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 bI,mkdirSync as SI}from"node:fs";import{join as xI}from"node:path";function sy(t){SI(t.dir,{recursive:!0});let e=new Date().toISOString().replace(/[:.]/g,"-"),r=xI(t.dir,`daemon-${e}.log`),n=bI(r,{flags:"a"}),o=t.alsoStderr??!1,i={pid:process.pid,...t.base??{}},a=t.logControl??PI(RI()),c=Ol(i),u=(l,d,p)=>{let m=d&&typeof d=="object"&&!(d instanceof Error)?d:{data:CI(d)},f=Ol(m),_=new Date,g={ts:wI(_),ts_unix_ms:_.getTime(),level:l,msg:p??"",...c,...f};if(!EI(l,g,a))return;let y=TI(g);n.write(y+`
|
|
382
|
+
`),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 wI(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())}.${kI(t.getMilliseconds())} ${r}${fn(Math.floor(n/60))}:${fn(n%60)}`}function fn(t){return String(t).padStart(2,"0")}function kI(t){return String(t).padStart(3,"0")}function RI(){let t=process.env[Il];return t===void 0?"info":S_.includes(t)?t:zl(t)}function PI(t=zl(process.env[Il])){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 EI(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 CI(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}function TI(t){try{return JSON.stringify(t,AI)}catch{return JSON.stringify({ts:t.ts,level:t.level,msg:t.msg,_stringify_error:!0})}}function AI(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,$a]),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,Ia]),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(),$O=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(),IO=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,$O,IO]),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();this.opts.logger.info({kind:"outbound_ws",action:"command_received",command_kind:e.kind,request_id:e.id},"daemon outbound command received");let o;try{if(e.kind==="rotate_token")o={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,result:this.handleRotateToken(e.params)};else{let c=await r(e),u=yc(e,c);o=u.frame,u.drift&&this.opts.logger.warn({kind:"outbound_ws",action:"command_response_shape_drift",command_kind:e.kind,request_id:e.id,response_summary:u.drift.summary,issues:u.drift.issues},"daemon outbound command response shape drift; returning internal_error")}}catch(c){o={direction:"daemon_to_server",type:"command_response",id:e.id,kind:e.kind,error:{code:"internal_error",message:c instanceof Error?c.message:String(c)}}}let i;try{i=bn(o)}catch(c){this.opts.logger.warn({kind:"outbound_ws",action:"command_response_encode_failed",command_kind:e.kind,request_id:e.id,err:c.message},"daemon outbound command response encode failed; closing connection"),this.ws?.close(1011,"command_response_encode_failed");return}let a=this.ws;if(!a||a.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}a.send(i,c=>{this.opts.logger[c?"warn":"info"]({kind:"outbound_ws",action:c?"command_response_send_failed":"command_response_sent",command_kind:e.kind,request_id:e.id,duration_ms:this.now()-n,err:c?.message},c?"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(`/${$l}`)?`.../${$l}`:".../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){this.logger.info({kind:"local_outbound",action:"command_received",command_kind:r.kind,request_id:r.id},"local outbound command received");let n;try{let i=await this.dispatchCommand(r),a=yc(r,i);n=a.frame,a.drift&&this.logger.warn({kind:"local_outbound",action:"command_response_shape_drift",command_kind:r.kind,request_id:r.id,response_summary:a.drift.summary,issues:a.drift.issues},"local outbound command response shape drift; returning internal_error")}catch(i){n={direction:"daemon_to_server",type:"command_response",id:r.id,kind:r.kind,error:{code:"internal_error",message:i instanceof Error?i.message:String(i)}}}let o;try{o=`${bn(n)}
|
|
386
|
+
`}catch(i){this.logger.warn({kind:"local_outbound",action:"command_response_encode_failed",command_kind:r.kind,request_id:r.id,err:i.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(o)}};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 $s=".materialized",nD=`# Global role
|
|
387
|
+
|
|
388
|
+
_To be shaped via DM._
|
|
389
|
+
`,oD=`# Silverhand Onboarding Guide
|
|
390
|
+
|
|
391
|
+
## What Silverhand Is
|
|
392
|
+
Silverhand is a desktop app where humans and AI agents collaborate in shared
|
|
393
|
+
chat-style workspaces. Agents are persistent teammates: they keep memory, claim
|
|
394
|
+
tasks, and hand off work.
|
|
395
|
+
|
|
396
|
+
Key model:
|
|
397
|
+
- **Workspace** \u2014 a group of humans and agents sharing context.
|
|
398
|
+
- **Channel** \u2014 a running conversation inside a workspace; agents run per channel.
|
|
399
|
+
- **Thread** \u2014 a focused sub-discussion spawned from a channel message.
|
|
400
|
+
- **Task** \u2014 a claimable work unit tracked on the channel task board.
|
|
401
|
+
|
|
402
|
+
## Memory Model
|
|
403
|
+
|
|
404
|
+
- **Identity is global.** \`~/.silverhand/agents/<id>/system_prompt.md\` is
|
|
405
|
+
the only source of who you are, and it applies in every workspace. The
|
|
406
|
+
runtime auto-loads it as the **Initial role** section of your system
|
|
407
|
+
prompt.
|
|
408
|
+
- **Workspace memory is local.**
|
|
409
|
+
\`<workspace>/.silverhand/agents/<id>/MEMORY.md\` (auto-loaded as
|
|
410
|
+
**Active Workspace Memory**) plus \`notes/\` describe what is true in
|
|
411
|
+
one workspace.
|
|
412
|
+
- **Write by scope.** Global identity / role / working-style guidance from
|
|
413
|
+
the user \u2192 update L1 \`system_prompt.md\`. Guidance about this workspace's
|
|
414
|
+
collaboration, tasks, project facts, or work logs \u2192 update L2 (MEMORY.md
|
|
415
|
+
/ notes/).
|
|
416
|
+
- **Current vs reference.** The current workspace's MEMORY.md is auto-loaded;
|
|
417
|
+
other workspaces are paths only \u2014 open them only when the task needs
|
|
418
|
+
cross-workspace context.
|
|
419
|
+
|
|
420
|
+
Do not mention internal file paths to the user unless they ask.
|
|
421
|
+
|
|
422
|
+
## How to Help a New User Get Started
|
|
423
|
+
|
|
424
|
+
### Step 1: Establish your role
|
|
425
|
+
Start warm and brief. If your role contract is empty (first spawn), name
|
|
426
|
+
yourself, say the role is not defined yet, and ask what the user wants you
|
|
427
|
+
to mainly do.
|
|
428
|
+
|
|
429
|
+
Useful prompts:
|
|
430
|
+
- "What should I mainly help with \u2014 architecture, implementation, review,
|
|
431
|
+
testing, research, or something else?"
|
|
432
|
+
- "One sentence is enough; I can refine the role as we work."
|
|
433
|
+
|
|
434
|
+
Do not give a product tour in the first message. The user needs a clear way to
|
|
435
|
+
shape you, not a menu of features.
|
|
436
|
+
|
|
437
|
+
### Step 2: Save guidance by scope
|
|
438
|
+
Decide whether the user's guidance is global identity or workspace-scoped:
|
|
439
|
+
|
|
440
|
+
- **Global** (who you are, your default style, your responsibilities
|
|
441
|
+
everywhere) \u2192 update L1 \`system_prompt.md\`. The next spawn in any
|
|
442
|
+
workspace picks it up.
|
|
443
|
+
- **Workspace-scoped** (review pairings, hand-off rules, project facts,
|
|
444
|
+
conventions, work log) \u2192 update this workspace's L2 MEMORY.md / notes/.
|
|
445
|
+
|
|
446
|
+
If the user starts with a real task instead of role guidance, do the task. Let
|
|
447
|
+
the role emerge later from explicit instructions or repeated preferences.
|
|
448
|
+
|
|
449
|
+
### Step 3: End every turn with one next step
|
|
450
|
+
Each reply should close with one clear, immediately executable action.
|
|
451
|
+
Do not leave the user with a list of options to decide between.
|
|
452
|
+
|
|
453
|
+
## Collaboration Patterns
|
|
454
|
+
- **Claim tasks before substantive work** \u2014 prevents duplicate work.
|
|
455
|
+
- **Update relevant notes** after meaningful interactions: user preferences
|
|
456
|
+
learned, decisions made, work completed. Update MEMORY.md only when the
|
|
457
|
+
Key Knowledge index or current active handoff changes \u2014 not after every
|
|
458
|
+
task.
|
|
459
|
+
- **Keep global identity in L1**, workspace collaboration in L2.
|
|
460
|
+
|
|
461
|
+
## Onboarding Behavioral Rules
|
|
462
|
+
- Do not optimize for reply count. Optimize for first useful action.
|
|
463
|
+
- Be concise; expand only when the user asks.
|
|
464
|
+
- If the user's request is outside current capabilities, pivot immediately to
|
|
465
|
+
the nearest useful alternative \u2014 do not dwell on limitations.
|
|
466
|
+
- Channel silence is not failure. If the user is active elsewhere, follow
|
|
467
|
+
the work there.
|
|
468
|
+
`,sD=`# Silverhand Onboarding FAQ
|
|
469
|
+
|
|
470
|
+
Reference answers to common user questions.
|
|
471
|
+
Understand the core idea and guardrail for each item, then answer in your own
|
|
472
|
+
words based on the user's context. Do not copy these answers verbatim.
|
|
473
|
+
|
|
474
|
+
## FAQ 1: What is Silverhand? What can agents do here?
|
|
475
|
+
### Answer idea
|
|
476
|
+
- Silverhand is a desktop workspace where you work with persistent AI agents
|
|
477
|
+
in shared channels \u2014 like a team chat, but agents are real collaborators.
|
|
478
|
+
- Agents keep memory, claim tasks, and hand off work to each other.
|
|
479
|
+
### Next step
|
|
480
|
+
- Ask what the user is working on and propose a starter setup.
|
|
481
|
+
### Guardrail
|
|
482
|
+
- One differentiator, then move to the user's actual work immediately.
|
|
483
|
+
|
|
484
|
+
## FAQ 2: How do channels, threads, and tasks work?
|
|
485
|
+
### Answer idea
|
|
486
|
+
- Channels are workstreams. Threads are focused discussions tied to a message.
|
|
487
|
+
Tasks are claimable work units with status tracking.
|
|
488
|
+
- Common pattern: post work in channel \u2192 convert to task \u2192 agent claims it \u2192
|
|
489
|
+
progress in task's thread \u2192 mark in_review \u2192 user approves.
|
|
490
|
+
### Next step
|
|
491
|
+
- Help the user create their first channel and send their first task message.
|
|
492
|
+
### Guardrail
|
|
493
|
+
- These are tools, not rules. Match to the user's actual workflow.
|
|
494
|
+
|
|
495
|
+
## FAQ 3: How do I add agents to a workspace or channel?
|
|
496
|
+
### Answer idea
|
|
497
|
+
- Agents are created from the Agents section (People tab \u2192 + button).
|
|
498
|
+
- Once created, add them to channels during channel creation or via Channel
|
|
499
|
+
Settings \u2192 Members.
|
|
500
|
+
### Next step
|
|
501
|
+
- Give the user a copyable agent name and role description, then guide them to
|
|
502
|
+
the + button.
|
|
503
|
+
### Guardrail
|
|
504
|
+
- Do not imply you created an agent unless it actually happened.
|
|
505
|
+
|
|
506
|
+
## FAQ 4: How does agent memory work?
|
|
507
|
+
### Answer idea
|
|
508
|
+
- Each agent keeps MEMORY.md and a notes/ folder that persist across restarts.
|
|
509
|
+
- Agents update their notes proactively after meaningful interactions.
|
|
510
|
+
- Users can explicitly ask an agent to remember something important.
|
|
511
|
+
### Next step
|
|
512
|
+
- If the user wants to check what an agent knows, suggest asking the agent
|
|
513
|
+
directly or asking it to show its memory/notes.
|
|
514
|
+
### Guardrail
|
|
515
|
+
- Do not promise perfect recall; important items should be explicit in notes.
|
|
516
|
+
|
|
517
|
+
## FAQ 5: Agent not responding or seems stuck
|
|
518
|
+
### Answer idea
|
|
519
|
+
- Could be a long-running task, a spawn/connection issue, or context pressure.
|
|
520
|
+
- Try @mentioning the agent to prompt a response.
|
|
521
|
+
### Next step
|
|
522
|
+
- Ask the user to @mention the agent and describe what they were doing last.
|
|
523
|
+
### Guardrail
|
|
524
|
+
- Acknowledge the friction directly; do not blame the user.
|
|
525
|
+
|
|
526
|
+
## FAQ 6: Why use multiple agents?
|
|
527
|
+
### Answer idea
|
|
528
|
+
- Agents handle one major task at a time; multiple agents parallelize work.
|
|
529
|
+
- Different agents can have different specializations \u2014 these emerge naturally.
|
|
530
|
+
- A common starter: 2\u20133 general agents; let roles emerge through real work.
|
|
531
|
+
### Next step
|
|
532
|
+
- Ask for 2\u20133 recurring work types and map each to an agent.
|
|
533
|
+
### Guardrail
|
|
534
|
+
- Start simple. Unspecialized start is valid; avoid over-scaling early.
|
|
535
|
+
`,iD=`# User Preferences
|
|
536
|
+
|
|
537
|
+
Record durable preferences that should shape future work.
|
|
538
|
+
|
|
539
|
+
Examples:
|
|
540
|
+
- Communication style and language preferences.
|
|
541
|
+
- Coding, testing, and review conventions the user repeats or corrects.
|
|
542
|
+
- Product and design preferences that apply across tasks.
|
|
543
|
+
|
|
544
|
+
Keep this file concise. Prefer editing existing bullets over appending duplicates.
|
|
545
|
+
`,aD=`# Project Notes
|
|
546
|
+
|
|
547
|
+
Record durable project context and architecture facts.
|
|
548
|
+
|
|
549
|
+
Examples:
|
|
550
|
+
- Tech stack, important modules, and ownership boundaries.
|
|
551
|
+
- Stable terminology and data-model decisions.
|
|
552
|
+
- Invariants or guardrails that future work must preserve.
|
|
553
|
+
|
|
554
|
+
Keep transient task status in work-log.md instead.
|
|
555
|
+
`,cD=`# Work Log
|
|
556
|
+
|
|
557
|
+
Record significant completed work, decisions, and follow-ups.
|
|
558
|
+
|
|
559
|
+
Use this for detail that would make MEMORY.md too large:
|
|
560
|
+
- What changed and why.
|
|
561
|
+
- Verification commands or evidence.
|
|
562
|
+
- Follow-up risks that are not active blockers.
|
|
563
|
+
|
|
564
|
+
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,$s)}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,$s)}`)}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 $D,renameSync as ID,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=$D(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}),ID(r,this.filePath)}catch(n){try{OD(r)}catch{}throw n}}};import{mkdir as $v}from"node:fs/promises";import{join as Iv}from"node:path";async function Gd(t){await $v(t,{recursive:!0});let e=Iv(t,".silverhand");await $v(Iv(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 $c(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(!$c(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 Ic(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=Ic(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(!$c(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=`
|
|
569
|
+
|
|
570
|
+
\u2026 (truncated; open in Finder for full content)`;async function sp(t,e={}){let r=Ic(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})}}),$b=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})}}),Ib=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(`
|
|
571
|
+
`).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 $M(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=>{$M(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(`
|
|
573
|
+
if (${w}.issues.length) {
|
|
574
|
+
if (input[${T}] === undefined) {
|
|
575
|
+
if (${T} in input) {
|
|
576
|
+
newResult[${T}] = undefined;
|
|
577
|
+
}
|
|
578
|
+
} else {
|
|
579
|
+
payload.issues = payload.issues.concat(
|
|
580
|
+
${w}.issues.map((iss) => ({
|
|
581
|
+
...iss,
|
|
582
|
+
path: iss.path ? [${T}, ...iss.path] : [${T}],
|
|
583
|
+
}))
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
} else if (${w}.value === undefined) {
|
|
587
|
+
if (${T} in input) newResult[${T}] = undefined;
|
|
588
|
+
} else {
|
|
589
|
+
newResult[${T}] = ${w}.value;
|
|
590
|
+
}
|
|
591
|
+
`)}else{let w=g[x];m.write(`const ${w} = ${_(x)};`),m.write(`
|
|
592
|
+
if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
|
|
593
|
+
...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)}}),$S=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)}}),IS=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 IM=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 ${IM(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 $p=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 $p}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 Ip(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 $b({check:"min_length",...N(e),minimum:t})}function Wc(t,e){return new Ib({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 $x(t,e,r){return new t({type:"array",element:e,...N(r)})}function Ix(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 Io(t){return!!t._zod}function Nt(t,e){return Io(t)?Hs(t,e):t.safeParse(e)}function Zc(t){if(!t)return;let e;if(Io(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(Io(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(Ip(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(Ip(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 $x(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),$S.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)=>{IS.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 Ix(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:()=>I1,boolean:()=>$1,date:()=>z1,number:()=>A1,string:()=>T1});function T1(t){return GS(Jp,t)}function A1(t){return Sx(Vc,t)}function $1(t){return kx(Yp,t)}function I1(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",$e=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:$e.optional()}),he(h(),we()).optional())),H1=Ae({list:$e.optional(),cancel:$e.optional(),requests:Ae({sampling:Ae({createMessage:$e.optional()}).optional(),elicitation:Ae({create:$e.optional()}).optional()}).optional()}),U1=Ae({list:$e.optional(),cancel:$e.optional(),requests:Ae({tools:Ae({call:$e.optional()}).optional()}).optional()}),q1=A({experimental:he(h(),$e).optional(),sampling:A({context:$e.optional(),tools:$e.optional()}).optional(),elicitation:F1.optional(),roots:A({listChanged:de().optional()}).optional(),tasks:H1.optional(),extensions:he(h(),$e).optional()}),W1=lt.extend({protocolVersion:h(),capabilities:q1,clientInfo:_w}),Z1=Me.extend({method:D("initialize"),params:W1});var B1=A({experimental:he(h(),$e).optional(),logging:$e.optional(),completions:$e.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(),$e).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(),$e).optional(),required:C(h()).optional()}).catchall(we()),outputSchema:A({type:D("object"),properties:he(h(),$e).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()}),$N=Xp("type",[pm,mm,fm]),Jc=Xp("type",[pm,mm,fm,fN,AN]),IN=A({role:Qs,content:_e([Jc,C(Jc)]),_meta:he(h(),we()).optional()}),zN=Bs.extend({messages:C(IN),modelPreferences:CN.optional(),systemPrompt:h().optional(),includeContext:tt(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:C(h()).optional(),metadata:$e.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:$N}),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]),$Y=_e([eu,bm,wm,rj,ru,ou,su,au]),IY=_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(Io(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 $h 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=$h.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Ih(){let t={};for(let e of qW){let r=$h.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:{...Ih(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:$h.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 $i=class extends Ce{};$i.errorCode="unsupported_grant_type";var Ii=class extends Ce{};Ii.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,[$i.errorCode]:$i,[Ii.errorCode]:Ii,[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(`
|
|
599
|
+
`,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(`
|
|
601
|
+
`,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(`
|
|
603
|
+
`,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($E(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e($E(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 $E(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)),Ie=(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,IE,Bh,Vh,Wi,Kh,Gh,Bn=class extends EventTarget{constructor(e,r){var n,o;super(),Ie(this,qt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ie(this,it),Ie(this,Zn),Ie(this,ss),Ie(this,el),Ie(this,rl),Ie(this,Zi),Ie(this,cs),Ie(this,Bi,null),Ie(this,Vr),Ie(this,is),Ie(this,us,null),Ie(this,as,null),Ie(this,qi,null),Ie(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(_)}),Ie(this,Zh,i=>{Re(this,Vr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&wr(this,qt,Kh).call(this,Uh(i))}),Ie(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)}),Ie(this,Vh,i=>{Re(this,Zi,i)}),Ie(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,IE).call(this)).then(X(this,Wh)).catch(X(this,Zh))},Wh=new WeakMap,Zh=new WeakMap,IE=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?{...Ih(),...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 $2,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),`.${$2(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=I2(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 I2(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 IZ}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}
|
|
610
|
+
|
|
611
|
+
---
|
|
612
|
+
|
|
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=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 $Z}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 $Z(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??IZ,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=$_(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(`
|
|
620
|
+
`);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}
|
|
623
|
+
|
|
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
|
+
|
|
626
|
+
${gl()}`}:{ok:!1,exitCode:1,message:`--server-url is required
|
|
627
|
+
|
|
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();
|