@silverhand-ai/daemon 0.0.1-alpha.6 → 0.0.1-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +50 -50
- package/dist/daemon.js +65 -64
- package/package.json +4 -3
package/dist/cli.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire}from"node:module";const require=createRequire(import.meta.url);
|
|
3
|
-
var tc=Object.create;var lr=Object.defineProperty;var nc=Object.getOwnPropertyDescriptor;var rc=Object.getOwnPropertyNames;var sc=Object.getPrototypeOf,oc=Object.prototype.hasOwnProperty;var I=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var H=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),ac=(n,t)=>{for(var r in t)lr(n,r,{get:t[r],enumerable:!0})},ic=(n,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rc(t))!oc.call(n,o)&&o!==r&&lr(n,o,{get:()=>t[o],enumerable:!(s=nc(t,o))||s.enumerable});return n};var fe=(n,t,r)=>(r=n!=null?tc(sc(n)):{},ic(t||!n||!n.__esModule?lr(r,"default",{value:n,enumerable:!0}):r,n));var ue=H((Zx,Sa)=>{"use strict";var va=["nodebuffer","arraybuffer","fragments"],ba=typeof Blob<"u";ba&&va.push("blob");Sa.exports={BINARY_TYPES:va,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ba,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ht=H((Yx,Vn)=>{"use strict";var{EMPTY_BUFFER:Jm}=ue(),us=Buffer[Symbol.species];function Xm(n,t){if(n.length===0)return Jm;if(n.length===1)return n[0];let r=Buffer.allocUnsafe(t),s=0;for(let o=0;o<n.length;o++){let a=n[o];r.set(a,s),s+=a.length}return s<t?new us(r.buffer,r.byteOffset,s):r}function xa(n,t,r,s,o){for(let a=0;a<o;a++)r[s+a]=n[a]^t[a&3]}function ka(n,t){for(let r=0;r<n.length;r++)n[r]^=t[r&3]}function Qm(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function ms(n){if(ms.readOnly=!0,Buffer.isBuffer(n))return n;let t;return n instanceof ArrayBuffer?t=new us(n):ArrayBuffer.isView(n)?t=new us(n.buffer,n.byteOffset,n.byteLength):(t=Buffer.from(n),ms.readOnly=!1),t}Vn.exports={concat:Xm,mask:xa,toArrayBuffer:Qm,toBuffer:ms,unmask:ka};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=I("bufferutil");Vn.exports.mask=function(t,r,s,o,a){a<48?xa(t,r,s,o,a):n.mask(t,r,s,o,a)},Vn.exports.unmask=function(t,r){t.length<32?ka(t,r):n.unmask(t,r)}}catch{}});var Ea=H((Jx,Ra)=>{"use strict";var wa=Symbol("kDone"),ps=Symbol("kRun"),hs=class{constructor(t){this[wa]=()=>{this.pending--,this[ps]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[ps]()}[ps](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[wa])}}};Ra.exports=hs});var yt=H((Xx,Pa)=>{"use strict";var Ut=I("zlib"),Ca=Ht(),ep=Ea(),{kStatusCode:Aa}=ue(),tp=Buffer[Symbol.species],np=Buffer.from([0,0,255,255]),Kn=Symbol("permessage-deflate"),me=Symbol("total-length"),gt=Symbol("callback"),xe=Symbol("buffers"),_t=Symbol("error"),Gn,fs=class{constructor(t){if(this._options=t||{},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,!Gn){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Gn=new ep(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[gt];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,s=t.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(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(t){let r=t[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(t){return t.forEach(r=>{Object.keys(r).forEach(s=>{let o=r[s];if(o.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(o=o[0],s==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${s}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${o}`)}else if(s==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${s}": ${o}`);o=a}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${o}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=o})}),t}decompress(t,r,s){Gn.add(o=>{this._decompress(t,r,(a,i)=>{o(),s(a,i)})})}compress(t,r,s){Gn.add(o=>{this._compress(t,r,(a,i)=>{o(),s(a,i)})})}_decompress(t,r,s){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,i=typeof this.params[a]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=Ut.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Kn]=this,this._inflate[me]=0,this._inflate[xe]=[],this._inflate.on("error",sp),this._inflate.on("data",Ta)}this._inflate[gt]=s,this._inflate.write(t),r&&this._inflate.write(np),this._inflate.flush(()=>{let a=this._inflate[_t];if(a){this._inflate.close(),this._inflate=null,s(a);return}let i=Ca.concat(this._inflate[xe],this._inflate[me]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[me]=0,this._inflate[xe]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(t,r,s){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,i=typeof this.params[a]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=Ut.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[me]=0,this._deflate[xe]=[],this._deflate.on("data",rp)}this._deflate[gt]=s,this._deflate.write(t),this._deflate.flush(Ut.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=Ca.concat(this._deflate[xe],this._deflate[me]);r&&(a=new tp(a.buffer,a.byteOffset,a.length-4)),this._deflate[gt]=null,this._deflate[me]=0,this._deflate[xe]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),s(null,a)})}};Pa.exports=fs;function rp(n){this[xe].push(n),this[me]+=n.length}function Ta(n){if(this[me]+=n.length,this[Kn]._maxPayload<1||this[me]<=this[Kn]._maxPayload){this[xe].push(n);return}this[_t]=new RangeError("Max payload size exceeded"),this[_t].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[_t][Aa]=1009,this.removeListener("data",Ta),this.reset()}function sp(n){if(this[Kn]._inflate=null,this[_t]){this[gt](this[_t]);return}n[Aa]=1007,this[gt](n)}});var vt=H((Qx,Zn)=>{"use strict";var{isUtf8:Oa}=I("buffer"),{hasBlob:op}=ue(),ap=[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 ip(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function gs(n){let t=n.length,r=0;for(;r<t;)if((n[r]&128)===0)r++;else if((n[r]&224)===192){if(r+1===t||(n[r+1]&192)!==128||(n[r]&254)===192)return!1;r+=2}else if((n[r]&240)===224){if(r+2>=t||(n[r+1]&192)!==128||(n[r+2]&192)!==128||n[r]===224&&(n[r+1]&224)===128||n[r]===237&&(n[r+1]&224)===160)return!1;r+=3}else if((n[r]&248)===240){if(r+3>=t||(n[r+1]&192)!==128||(n[r+2]&192)!==128||(n[r+3]&192)!==128||n[r]===240&&(n[r+1]&240)===128||n[r]===244&&n[r+1]>143||n[r]>244)return!1;r+=4}else return!1;return!0}function cp(n){return op&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Zn.exports={isBlob:cp,isValidStatusCode:ip,isValidUTF8:gs,tokenChars:ap};if(Oa)Zn.exports.isValidUTF8=function(n){return n.length<24?gs(n):Oa(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=I("utf-8-validate");Zn.exports.isValidUTF8=function(t){return t.length<32?gs(t):n(t)}}catch{}});var Ss=H((ek,Fa)=>{"use strict";var{Writable:lp}=I("stream"),Ia=yt(),{BINARY_TYPES:dp,EMPTY_BUFFER:Ma,kStatusCode:up,kWebSocket:mp}=ue(),{concat:_s,toArrayBuffer:pp,unmask:hp}=Ht(),{isValidStatusCode:fp,isValidUTF8:Da}=vt(),Yn=Buffer[Symbol.species],G=0,La=1,ja=2,Na=3,ys=4,vs=5,Jn=6,bs=class extends lp{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||dp[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[mp]=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=G}_write(t,r,s){if(this._opcode===8&&this._state==G)return s();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(s)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Yn(s.buffer,s.byteOffset+t,s.length-t),new Yn(s.buffer,s.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let s=this._buffers[0],o=r.length-t;t>=s.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(s.buffer,s.byteOffset,t),o),this._buffers[0]=new Yn(s.buffer,s.byteOffset+t,s.length-t)),t-=s.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case G:this.getInfo(t);break;case La:this.getPayloadLength16(t);break;case ja:this.getPayloadLength64(t);break;case Na:this.getMask();break;case ys:this.getData(t);break;case vs:case Jn:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){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");t(o);return}let s=(r[0]&64)===64;if(s&&!this._extensions[Ia.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(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");t(o);return}this._compressed=s}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");t(o);return}if(s){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(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");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(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");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=La:this._payloadLength===127?this._state=ja:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>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");t(o);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){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");t(r);return}this._masked?this._state=Na:this._state=ys}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ys}getData(t){let r=Ma;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&&hp(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=vs,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[Ia.extensionName].decompress(t,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(a)}this.dataMessage(r),this._state===G&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=G;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=_s(s,r):this._binaryType==="arraybuffer"?o=pp(_s(s,r)):this._binaryType==="blob"?o=new Blob(s):o=s,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=G):(this._state=Jn,setImmediate(()=>{this.emit("message",o,!0),this._state=G,this.startLoop(t)}))}else{let o=_s(s,r);if(!this._skipUTF8Validation&&!Da(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===vs||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=G):(this._state=Jn,setImmediate(()=>{this.emit("message",o,!1),this._state=G,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Ma),this.end();else{let s=t.readUInt16BE(0);if(!fp(s)){let a=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new Yn(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Da(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);return}this._loop=!1,this.emit("conclude",s,o),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=G):(this._state=Jn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=G,this.startLoop(r)}))}createError(t,r,s,o,a){this._loop=!1,this._errored=!0;let i=new t(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=a,i[up]=o,i}};Fa.exports=bs});var ws=H((nk,Ha)=>{"use strict";var{Duplex:tk}=I("stream"),{randomFillSync:gp}=I("crypto"),za=yt(),{EMPTY_BUFFER:_p,kWebSocket:yp,NOOP:vp}=ue(),{isBlob:bt,isValidStatusCode:bp}=vt(),{mask:$a,toBuffer:Ge}=Ht(),K=Symbol("kByteLength"),Sp=Buffer.alloc(4),Xn=8*1024,Ke,St=Xn,X=0,xp=1,kp=2,xs=class n{constructor(t,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=X,this.onerror=vp,this[yp]=void 0}static frame(t,r){let s,o=!1,a=2,i=!1;r.mask&&(s=r.maskBuffer||Sp,r.generateMask?r.generateMask(s):(St===Xn&&(Ke===void 0&&(Ke=Buffer.alloc(Xn)),gp(Ke,0,Xn),St=0),s[0]=Ke[St++],s[1]=Ke[St++],s[2]=Ke[St++],s[3]=Ke[St++]),i=(s[0]|s[1]|s[2]|s[3])===0,a=6);let c;typeof t=="string"?(!r.mask||i)&&r[K]!==void 0?c=r[K]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!i);let d=c;c>=65536?(a+=8,d=127):c>125&&(a+=2,d=126);let l=Buffer.allocUnsafe(o?c+a:a);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[a-4]=s[0],l[a-3]=s[1],l[a-2]=s[2],l[a-1]=s[3],i?[l,t]:o?($a(t,s,l,a,c),[l]):($a(t,s,t,0,c),[l,t])):[l,t]}close(t,r,s,o){let a;if(t===void 0)a=_p;else{if(typeof t!="number"||!bp(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");a=Buffer.allocUnsafe(2+c),a.writeUInt16BE(t,0),typeof r=="string"?a.write(r,2):a.set(r,2)}}let i={[K]:a.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==X?this.enqueue([this.dispatch,a,!1,i,o]):this.sendFrame(n.frame(a,i),o)}ping(t,r,s){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):bt(t)?(o=t.size,a=!1):(t=Ge(t),o=t.length,a=Ge.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,s]):this.getBlobData(t,!1,i,s):this._state!==X?this.enqueue([this.dispatch,t,!1,i,s]):this.sendFrame(n.frame(t,i),s)}pong(t,r,s){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):bt(t)?(o=t.size,a=!1):(t=Ge(t),o=t.length,a=Ge.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,s]):this.getBlobData(t,!1,i,s):this._state!==X?this.enqueue([this.dispatch,t,!1,i,s]):this.sendFrame(n.frame(t,i),s)}send(t,r,s){let o=this._extensions[za.extensionName],a=r.binary?2:1,i=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):bt(t)?(c=t.size,d=!1):(t=Ge(t),c=t.length,d=Ge.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=o._threshold),this._compress=i):(i=!1,a=0),r.fin&&(this._firstFragment=!0);let l={[K]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:d,rsv1:i};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,this._compress,l,s]):this.getBlobData(t,this._compress,l,s):this._state!==X?this.enqueue([this.dispatch,t,this._compress,l,s]):this.dispatch(t,this._compress,l,s)}getBlobData(t,r,s,o){this._bufferedBytes+=s[K],this._state=kp,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ks,this,c,o);return}this._bufferedBytes-=s[K];let i=Ge(a);r?this.dispatch(i,r,s,o):(this._state=X,this.sendFrame(n.frame(i,s),o),this.dequeue())}).catch(a=>{process.nextTick(wp,this,a,o)})}dispatch(t,r,s,o){if(!r){this.sendFrame(n.frame(t,s),o);return}let a=this._extensions[za.extensionName];this._bufferedBytes+=s[K],this._state=xp,a.compress(t,s.fin,(i,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");ks(this,d,o);return}this._bufferedBytes-=s[K],this._state=X,s.readOnly=!1,this.sendFrame(n.frame(c,s),o),this.dequeue()})}dequeue(){for(;this._state===X&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][K],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][K],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};Ha.exports=xs;function ks(n,t,r){typeof r=="function"&&r(t);for(let s=0;s<n._queue.length;s++){let o=n._queue[s],a=o[o.length-1];typeof a=="function"&&a(t)}}function wp(n,t,r){ks(n,t,r),n.onerror(t)}});var Ya=H((rk,Za)=>{"use strict";var{kForOnEventAttribute:Wt,kListener:Rs}=ue(),Ua=Symbol("kCode"),Wa=Symbol("kData"),qa=Symbol("kError"),Ba=Symbol("kMessage"),Va=Symbol("kReason"),xt=Symbol("kTarget"),Ga=Symbol("kType"),Ka=Symbol("kWasClean"),pe=class{constructor(t){this[xt]=null,this[Ga]=t}get target(){return this[xt]}get type(){return this[Ga]}};Object.defineProperty(pe.prototype,"target",{enumerable:!0});Object.defineProperty(pe.prototype,"type",{enumerable:!0});var Ze=class extends pe{constructor(t,r={}){super(t),this[Ua]=r.code===void 0?0:r.code,this[Va]=r.reason===void 0?"":r.reason,this[Ka]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ua]}get reason(){return this[Va]}get wasClean(){return this[Ka]}};Object.defineProperty(Ze.prototype,"code",{enumerable:!0});Object.defineProperty(Ze.prototype,"reason",{enumerable:!0});Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});var kt=class extends pe{constructor(t,r={}){super(t),this[qa]=r.error===void 0?null:r.error,this[Ba]=r.message===void 0?"":r.message}get error(){return this[qa]}get message(){return this[Ba]}};Object.defineProperty(kt.prototype,"error",{enumerable:!0});Object.defineProperty(kt.prototype,"message",{enumerable:!0});var qt=class extends pe{constructor(t,r={}){super(t),this[Wa]=r.data===void 0?null:r.data}get data(){return this[Wa]}};Object.defineProperty(qt.prototype,"data",{enumerable:!0});var Rp={addEventListener(n,t,r={}){for(let o of this.listeners(n))if(!r[Wt]&&o[Rs]===t&&!o[Wt])return;let s;if(n==="message")s=function(a,i){let c=new qt("message",{data:i?a:a.toString()});c[xt]=this,Qn(t,this,c)};else if(n==="close")s=function(a,i){let c=new Ze("close",{code:a,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[xt]=this,Qn(t,this,c)};else if(n==="error")s=function(a){let i=new kt("error",{error:a,message:a.message});i[xt]=this,Qn(t,this,i)};else if(n==="open")s=function(){let a=new pe("open");a[xt]=this,Qn(t,this,a)};else return;s[Wt]=!!r[Wt],s[Rs]=t,r.once?this.once(n,s):this.on(n,s)},removeEventListener(n,t){for(let r of this.listeners(n))if(r[Rs]===t&&!r[Wt]){this.removeListener(n,r);break}}};Za.exports={CloseEvent:Ze,ErrorEvent:kt,Event:pe,EventTarget:Rp,MessageEvent:qt};function Qn(n,t,r){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,r):n.call(t,r)}});var er=H((sk,Ja)=>{"use strict";var{tokenChars:Bt}=vt();function oe(n,t,r){n[t]===void 0?n[t]=[r]:n[t].push(r)}function Ep(n){let t=Object.create(null),r=Object.create(null),s=!1,o=!1,a=!1,i,c,d=-1,l=-1,m=-1,h=0;for(;h<n.length;h++)if(l=n.charCodeAt(h),i===void 0)if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(h!==0&&(l===32||l===9))m===-1&&d!==-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h);let R=n.slice(d,m);l===44?(oe(t,R,r),r=Object.create(null)):i=R,d=m=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(l===32||l===9)m===-1&&d!==-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h),oe(r,n.slice(d,m),!0),l===44&&(oe(t,i,r),r=Object.create(null),i=void 0),d=m=-1}else if(l===61&&d!==-1&&m===-1)c=n.slice(d,h),d=m=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(o){if(Bt[l]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);d===-1?d=h:s||(s=!0),o=!1}else if(a)if(Bt[l]===1)d===-1&&(d=h);else if(l===34&&d!==-1)a=!1,m=h;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(l===34&&n.charCodeAt(h-1)===61)a=!0;else if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(d!==-1&&(l===32||l===9))m===-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h);let R=n.slice(d,m);s&&(R=R.replace(/\\/g,""),s=!1),oe(r,c,R),l===44&&(oe(t,i,r),r=Object.create(null),i=void 0),c=void 0,d=m=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(d===-1||a||l===32||l===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=h);let v=n.slice(d,m);return i===void 0?oe(t,v,r):(c===void 0?oe(r,v,!0):s?oe(r,c,v.replace(/\\/g,"")):oe(r,c,v),oe(t,i,r)),t}function Cp(n){return Object.keys(n).map(t=>{let r=n[t];return Array.isArray(r)||(r=[r]),r.map(s=>[t].concat(Object.keys(s).map(o=>{let a=s[o];return Array.isArray(a)||(a=[a]),a.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ja.exports={format:Cp,parse:Ep}});var sr=H((ik,li)=>{"use strict";var Ap=I("events"),Tp=I("https"),Pp=I("http"),ei=I("net"),Op=I("tls"),{randomBytes:Ip,createHash:Mp}=I("crypto"),{Duplex:ok,Readable:ak}=I("stream"),{URL:Es}=I("url"),ke=yt(),Dp=Ss(),Lp=ws(),{isBlob:jp}=vt(),{BINARY_TYPES:Xa,CLOSE_TIMEOUT:Np,EMPTY_BUFFER:tr,GUID:Fp,kForOnEventAttribute:Cs,kListener:zp,kStatusCode:$p,kWebSocket:D,NOOP:ti}=ue(),{EventTarget:{addEventListener:Hp,removeEventListener:Up}}=Ya(),{format:Wp,parse:qp}=er(),{toBuffer:Bp}=Ht(),ni=Symbol("kAborted"),As=[8,13],he=["CONNECTING","OPEN","CLOSING","CLOSED"],Vp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class n extends Ap{constructor(t,r,s){super(),this._binaryType=Xa[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=tr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),ri(this,t,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Xa.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}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(t,r,s){let o=new Dp({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),a=new Lp(t,this._extensions,s.generateMask);this._receiver=o,this._sender=a,this._socket=t,o[D]=this,a[D]=this,t[D]=this,o.on("conclude",Zp),o.on("drain",Yp),o.on("error",Jp),o.on("message",Xp),o.on("ping",Qp),o.on("pong",eh),a.onerror=th,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",ai),t.on("data",rr),t.on("end",ii),t.on("error",ci),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ke.extensionName]&&this._extensions[ke.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){U(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(t,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),oi(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(s=t,t=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Ts(this,t,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||tr,r,s)}pong(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(s=t,t=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Ts(this,t,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||tr,r,s)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Ts(this,t,s);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ke.extensionName]||(o.compress=!1),this._sender.send(t||tr,o,s)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){U(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(P.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(P.prototype,`on${n}`,{enumerable:!0,get(){for(let t of this.listeners(n))if(t[Cs])return t[zp];return null},set(t){for(let r of this.listeners(n))if(r[Cs]){this.removeListener(n,r);break}typeof t=="function"&&this.addEventListener(n,t,{[Cs]:!0})}})});P.prototype.addEventListener=Hp;P.prototype.removeEventListener=Up;li.exports=P;function ri(n,t,r,s){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Np,protocolVersion:As[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=o.autoPong,n._closeTimeout=o.closeTimeout,!As.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${As.join(", ")})`);let a;if(t instanceof Es)a=t;else try{a=new Es(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),n._url=a.href;let i=a.protocol==="wss:",c=a.protocol==="ws+unix:",d;if(a.protocol!=="ws:"&&!i&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?d="The URL's pathname is empty":a.hash&&(d="The URL contains a fragment identifier"),d){let E=new SyntaxError(d);if(n._redirects===0)throw E;nr(n,E);return}let l=i?443:80,m=Ip(16).toString("base64"),h=i?Tp.request:Pp.request,v=new Set,R;if(o.createConnection=o.createConnection||(i?Kp:Gp),o.defaultPort=o.defaultPort||l,o.port=a.port||l,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(R=new ke({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Wp({[ke.extensionName]:R.offer()})),r.length){for(let E of r){if(typeof E!="string"||!Vp.test(E)||v.has(E))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(E)}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),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),c){let E=o.path.split(":");o.socketPath=E[0],o.path=E[1]}let O;if(o.followRedirects){if(n._redirects===0){n._originalIpc=c,n._originalSecure=i,n._originalHostOrSocketPath=c?o.socketPath:a.host;let E=s&&s.headers;if(s={...s,headers:{}},E)for(let[A,Qe]of Object.entries(E))s.headers[A.toLowerCase()]=Qe}else if(n.listenerCount("redirect")===0){let E=c?n._originalIpc?o.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:a.host===n._originalHostOrSocketPath;(!E||n._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,E||delete o.headers.host,o.auth=void 0)}o.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),O=n._req=h(o),n._redirects&&n.emit("redirect",n.url,O)}else O=n._req=h(o);o.timeout&&O.on("timeout",()=>{U(n,O,"Opening handshake has timed out")}),O.on("error",E=>{O===null||O[ni]||(O=n._req=null,nr(n,E))}),O.on("response",E=>{let A=E.headers.location,Qe=E.statusCode;if(A&&o.followRedirects&&Qe>=300&&Qe<400){if(++n._redirects>o.maxRedirects){U(n,O,"Maximum redirects exceeded");return}O.abort();let wt;try{wt=new Es(A,t)}catch{let et=new SyntaxError(`Invalid URL: ${A}`);nr(n,et);return}ri(n,wt,r,s)}else n.emit("unexpected-response",O,E)||U(n,O,`Unexpected server response: ${E.statusCode}`)}),O.on("upgrade",(E,A,Qe)=>{if(n.emit("upgrade",E),n.readyState!==P.CONNECTING)return;O=n._req=null;let wt=E.headers.upgrade;if(wt===void 0||wt.toLowerCase()!=="websocket"){U(n,A,"Invalid Upgrade header");return}let zs=Mp("sha1").update(m+Fp).digest("base64");if(E.headers["sec-websocket-accept"]!==zs){U(n,A,"Invalid Sec-WebSocket-Accept header");return}let et=E.headers["sec-websocket-protocol"],Rt;if(et!==void 0?v.size?v.has(et)||(Rt="Server sent an invalid subprotocol"):Rt="Server sent a subprotocol but none was requested":v.size&&(Rt="Server sent no subprotocol"),Rt){U(n,A,Rt);return}et&&(n._protocol=et);let $s=E.headers["sec-websocket-extensions"];if($s!==void 0){if(!R){U(n,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ir;try{ir=qp($s)}catch{U(n,A,"Invalid Sec-WebSocket-Extensions header");return}let Hs=Object.keys(ir);if(Hs.length!==1||Hs[0]!==ke.extensionName){U(n,A,"Server indicated an extension that was not requested");return}try{R.accept(ir[ke.extensionName])}catch{U(n,A,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ke.extensionName]=R}n.setSocket(A,Qe,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(O,n):O.end()}function nr(n,t){n._readyState=P.CLOSING,n._errorEmitted=!0,n.emit("error",t),n.emitClose()}function Gp(n){return n.path=n.socketPath,ei.connect(n)}function Kp(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=ei.isIP(n.host)?"":n.host),Op.connect(n)}function U(n,t,r){n._readyState=P.CLOSING;let s=new Error(r);Error.captureStackTrace(s,U),t.setHeader?(t[ni]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(nr,n,s)):(t.destroy(s),t.once("error",n.emit.bind(n,"error")),t.once("close",n.emitClose.bind(n)))}function Ts(n,t,r){if(t){let s=jp(t)?t.size:Bp(t).length;n._socket?n._sender._bufferedBytes+=s:n._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${n.readyState} (${he[n.readyState]})`);process.nextTick(r,s)}}function Zp(n,t){let r=this[D];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=n,r._socket[D]!==void 0&&(r._socket.removeListener("data",rr),process.nextTick(si,r._socket),n===1005?r.close():r.close(n,t))}function Yp(){let n=this[D];n.isPaused||n._socket.resume()}function Jp(n){let t=this[D];t._socket[D]!==void 0&&(t._socket.removeListener("data",rr),process.nextTick(si,t._socket),t.close(n[$p])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n))}function Qa(){this[D].emitClose()}function Xp(n,t){this[D].emit("message",n,t)}function Qp(n){let t=this[D];t._autoPong&&t.pong(n,!this._isServer,ti),t.emit("ping",n)}function eh(n){this[D].emit("pong",n)}function si(n){n.resume()}function th(n){let t=this[D];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,oi(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n)))}function oi(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function ai(){let n=this[D];if(this.removeListener("close",ai),this.removeListener("data",rr),this.removeListener("end",ii),n._readyState=P.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);n._receiver.write(t)}n._receiver.end(),this[D]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Qa),n._receiver.on("finish",Qa))}function rr(n){this[D]._receiver.write(n)||this.pause()}function ii(){let n=this[D];n._readyState=P.CLOSING,n._receiver.end(),this.end()}function ci(){let n=this[D];this.removeListener("error",ci),this.on("error",ti),n&&(n._readyState=P.CLOSING,this.destroy())}});var pi=H((lk,mi)=>{"use strict";var ck=sr(),{Duplex:nh}=I("stream");function di(n){n.emit("close")}function rh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ui(n){this.removeListener("error",ui),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function sh(n,t){let r=!0,s=new nh({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(a,i){let c=!i&&s._readableState.objectMode?a.toString():a;s.push(c)||n.pause()}),n.once("error",function(a){s.destroyed||(r=!1,s.destroy(a))}),n.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(o,a){if(n.readyState===n.CLOSED){a(o),process.nextTick(di,s);return}let i=!1;n.once("error",function(d){i=!0,a(d)}),n.once("close",function(){i||a(o),process.nextTick(di,s)}),r&&n.terminate()},s._final=function(o){if(n.readyState===n.CONNECTING){n.once("open",function(){s._final(o)});return}n._socket!==null&&(n._socket._writableState.finished?(o(),s._readableState.endEmitted&&s.destroy()):(n._socket.once("finish",function(){o()}),n.close()))},s._read=function(){n.isPaused&&n.resume()},s._write=function(o,a,i){if(n.readyState===n.CONNECTING){n.once("open",function(){s._write(o,a,i)});return}n.send(o,i)},s.on("end",rh),s.on("error",ui),s}mi.exports=sh});var Ps=H((dk,hi)=>{"use strict";var{tokenChars:oh}=vt();function ah(n){let t=new Set,r=-1,s=-1,o=0;for(o;o<n.length;o++){let i=n.charCodeAt(o);if(s===-1&&oh[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))s===-1&&r!==-1&&(s=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);s===-1&&(s=o);let c=n.slice(r,s);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let a=n.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return t.add(a),t}hi.exports={parse:ah}});var Si=H((mk,bi)=>{"use strict";var ih=I("events"),or=I("http"),{Duplex:uk}=I("stream"),{createHash:ch}=I("crypto"),fi=er(),Ye=yt(),lh=Ps(),dh=sr(),{CLOSE_TIMEOUT:uh,GUID:mh,kWebSocket:ph}=ue(),hh=/^[+/0-9A-Za-z]{22}==$/,gi=0,_i=1,vi=2,Os=class extends ih{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:uh,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dh,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=or.createServer((s,o)=>{let a=or.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=fh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,a,i)=>{this.handleUpgrade(o,a,i,s)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=gi}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===vi){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Vt,this);return}if(t&&this.once("close",t),this._state!==_i)if(this._state=_i,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(Vt,this):process.nextTick(Vt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Vt(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,s,o){r.on("error",yi);let a=t.headers["sec-websocket-key"],i=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Je(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Je(this,t,r,400,"Invalid Upgrade header");return}if(a===void 0||!hh.test(a)){Je(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Je(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Gt(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=lh.parse(d)}catch{Je(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=t.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&m!==void 0){let v=new Ye({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let R=fi.parse(m);R[Ye.extensionName]&&(v.accept(R[Ye.extensionName]),h[Ye.extensionName]=v)}catch{Je(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(R,O,E,A)=>{if(!R)return Gt(r,O||401,E,A);this.completeUpgrade(h,a,l,t,r,s,o)});return}if(!this.options.verifyClient(v))return Gt(r,401)}this.completeUpgrade(h,a,l,t,r,s,o)}completeUpgrade(t,r,s,o,a,i,c){if(!a.readable||!a.writable)return a.destroy();if(a[ph])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>gi)return Gt(a,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ch("sha1").update(r+mh).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(s.size){let h=this.options.handleProtocols?this.options.handleProtocols(s,o):s.values().next().value;h&&(l.push(`Sec-WebSocket-Protocol: ${h}`),m._protocol=h)}if(t[Ye.extensionName]){let h=t[Ye.extensionName].params,v=fi.format({[Ye.extensionName]:[h]});l.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=t}this.emit("headers",l,o),a.write(l.concat(`\r
|
|
3
|
+
var sc=Object.create;var ur=Object.defineProperty;var ac=Object.getOwnPropertyDescriptor;var oc=Object.getOwnPropertyNames;var ic=Object.getPrototypeOf,cc=Object.prototype.hasOwnProperty;var I=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var H=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),lc=(n,t)=>{for(var r in t)ur(n,r,{get:t[r],enumerable:!0})},dc=(n,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of oc(t))!cc.call(n,a)&&a!==r&&ur(n,a,{get:()=>t[a],enumerable:!(s=ac(t,a))||s.enumerable});return n};var fe=(n,t,r)=>(r=n!=null?sc(ic(n)):{},dc(t||!n||!n.__esModule?ur(r,"default",{value:n,enumerable:!0}):r,n));var ue=H((ek,wo)=>{"use strict";var xo=["nodebuffer","arraybuffer","fragments"],ko=typeof Blob<"u";ko&&xo.push("blob");wo.exports={BINARY_TYPES:xo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ko,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ht=H((tk,Kn)=>{"use strict";var{EMPTY_BUFFER:rp}=ue(),ps=Buffer[Symbol.species];function sp(n,t){if(n.length===0)return rp;if(n.length===1)return n[0];let r=Buffer.allocUnsafe(t),s=0;for(let a=0;a<n.length;a++){let o=n[a];r.set(o,s),s+=o.length}return s<t?new ps(r.buffer,r.byteOffset,s):r}function Ro(n,t,r,s,a){for(let o=0;o<a;o++)r[s+o]=n[o]^t[o&3]}function Eo(n,t){for(let r=0;r<n.length;r++)n[r]^=t[r&3]}function ap(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function hs(n){if(hs.readOnly=!0,Buffer.isBuffer(n))return n;let t;return n instanceof ArrayBuffer?t=new ps(n):ArrayBuffer.isView(n)?t=new ps(n.buffer,n.byteOffset,n.byteLength):(t=Buffer.from(n),hs.readOnly=!1),t}Kn.exports={concat:sp,mask:Ro,toArrayBuffer:ap,toBuffer:hs,unmask:Eo};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=I("bufferutil");Kn.exports.mask=function(t,r,s,a,o){o<48?Ro(t,r,s,a,o):n.mask(t,r,s,a,o)},Kn.exports.unmask=function(t,r){t.length<32?Eo(t,r):n.unmask(t,r)}}catch{}});var To=H((nk,Ao)=>{"use strict";var Co=Symbol("kDone"),fs=Symbol("kRun"),gs=class{constructor(t){this[Co]=()=>{this.pending--,this[fs]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[fs]()}[fs](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[Co])}}};Ao.exports=gs});var yt=H((rk,Mo)=>{"use strict";var Ut=I("zlib"),Po=Ht(),op=To(),{kStatusCode:Oo}=ue(),ip=Buffer[Symbol.species],cp=Buffer.from([0,0,255,255]),Yn=Symbol("permessage-deflate"),me=Symbol("total-length"),gt=Symbol("callback"),xe=Symbol("buffers"),_t=Symbol("error"),Zn,_s=class{constructor(t){if(this._options=t||{},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,!Zn){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zn=new op(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[gt];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,s=t.find(a=>!(r.serverNoContextTakeover===!1&&a.server_no_context_takeover||a.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>a.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!a.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(t){let r=t[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(t){return t.forEach(r=>{Object.keys(r).forEach(s=>{let a=r[s];if(a.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(a=a[0],s==="client_max_window_bits"){if(a!==!0){let o=+a;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${a}`);a=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${a}`)}else if(s==="server_max_window_bits"){let o=+a;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${a}`);a=o}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(a!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${a}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=a})}),t}decompress(t,r,s){Zn.add(a=>{this._decompress(t,r,(o,i)=>{a(),s(o,i)})})}compress(t,r,s){Zn.add(a=>{this._compress(t,r,(o,i)=>{a(),s(o,i)})})}_decompress(t,r,s){let a=this._isServer?"client":"server";if(!this._inflate){let o=`${a}_max_window_bits`,i=typeof this.params[o]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Ut.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Yn]=this,this._inflate[me]=0,this._inflate[xe]=[],this._inflate.on("error",dp),this._inflate.on("data",Io)}this._inflate[gt]=s,this._inflate.write(t),r&&this._inflate.write(cp),this._inflate.flush(()=>{let o=this._inflate[_t];if(o){this._inflate.close(),this._inflate=null,s(o);return}let i=Po.concat(this._inflate[xe],this._inflate[me]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[me]=0,this._inflate[xe]=[],r&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),s(null,i)})}_compress(t,r,s){let a=this._isServer?"server":"client";if(!this._deflate){let o=`${a}_max_window_bits`,i=typeof this.params[o]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Ut.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[me]=0,this._deflate[xe]=[],this._deflate.on("data",lp)}this._deflate[gt]=s,this._deflate.write(t),this._deflate.flush(Ut.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Po.concat(this._deflate[xe],this._deflate[me]);r&&(o=new ip(o.buffer,o.byteOffset,o.length-4)),this._deflate[gt]=null,this._deflate[me]=0,this._deflate[xe]=[],r&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};Mo.exports=_s;function lp(n){this[xe].push(n),this[me]+=n.length}function Io(n){if(this[me]+=n.length,this[Yn]._maxPayload<1||this[me]<=this[Yn]._maxPayload){this[xe].push(n);return}this[_t]=new RangeError("Max payload size exceeded"),this[_t].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[_t][Oo]=1009,this.removeListener("data",Io),this.reset()}function dp(n){if(this[Yn]._inflate=null,this[_t]){this[gt](this[_t]);return}n[Oo]=1007,this[gt](n)}});var vt=H((sk,Jn)=>{"use strict";var{isUtf8:Do}=I("buffer"),{hasBlob:up}=ue(),mp=[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 pp(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function ys(n){let t=n.length,r=0;for(;r<t;)if((n[r]&128)===0)r++;else if((n[r]&224)===192){if(r+1===t||(n[r+1]&192)!==128||(n[r]&254)===192)return!1;r+=2}else if((n[r]&240)===224){if(r+2>=t||(n[r+1]&192)!==128||(n[r+2]&192)!==128||n[r]===224&&(n[r+1]&224)===128||n[r]===237&&(n[r+1]&224)===160)return!1;r+=3}else if((n[r]&248)===240){if(r+3>=t||(n[r+1]&192)!==128||(n[r+2]&192)!==128||(n[r+3]&192)!==128||n[r]===240&&(n[r+1]&240)===128||n[r]===244&&n[r+1]>143||n[r]>244)return!1;r+=4}else return!1;return!0}function hp(n){return up&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Jn.exports={isBlob:hp,isValidStatusCode:pp,isValidUTF8:ys,tokenChars:mp};if(Do)Jn.exports.isValidUTF8=function(n){return n.length<24?ys(n):Do(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=I("utf-8-validate");Jn.exports.isValidUTF8=function(t){return t.length<32?ys(t):n(t)}}catch{}});var ks=H((ak,Ho)=>{"use strict";var{Writable:fp}=I("stream"),Lo=yt(),{BINARY_TYPES:gp,EMPTY_BUFFER:jo,kStatusCode:_p,kWebSocket:yp}=ue(),{concat:vs,toArrayBuffer:vp,unmask:bp}=Ht(),{isValidStatusCode:Sp,isValidUTF8:No}=vt(),Xn=Buffer[Symbol.species],G=0,Fo=1,zo=2,$o=3,bs=4,Ss=5,Qn=6,xs=class extends fp{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||gp[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[yp]=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=G}_write(t,r,s){if(this._opcode===8&&this._state==G)return s();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(s)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Xn(s.buffer,s.byteOffset+t,s.length-t),new Xn(s.buffer,s.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let s=this._buffers[0],a=r.length-t;t>=s.length?r.set(this._buffers.shift(),a):(r.set(new Uint8Array(s.buffer,s.byteOffset,t),a),this._buffers[0]=new Xn(s.buffer,s.byteOffset+t,s.length-t)),t-=s.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case G:this.getInfo(t);break;case Fo:this.getPayloadLength16(t);break;case zo:this.getPayloadLength64(t);break;case $o:this.getMask();break;case bs:this.getData(t);break;case Ss:case Qn:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let a=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(a);return}let s=(r[0]&64)===64;if(s&&!this._extensions[Lo.extensionName]){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(a);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(a);return}if(!this._fragmented){let a=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(a);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(a);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let a=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(a);return}if(s){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(a);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let a=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(a);return}}else{let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(a);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let a=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(a);return}}else if(this._masked){let a=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(a);return}this._payloadLength===126?this._state=Fo:this._payloadLength===127?this._state=zo:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let a=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(a);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){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");t(r);return}this._masked?this._state=$o:this._state=bs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=bs}getData(t){let r=jo;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&&bp(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=Ss,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[Lo.extensionName].decompress(t,this._fin,(a,o)=>{if(a)return r(a);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(o)}this.dataMessage(r),this._state===G&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=G;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let a;this._binaryType==="nodebuffer"?a=vs(s,r):this._binaryType==="arraybuffer"?a=vp(vs(s,r)):this._binaryType==="blob"?a=new Blob(s):a=s,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=G):(this._state=Qn,setImmediate(()=>{this.emit("message",a,!0),this._state=G,this.startLoop(t)}))}else{let a=vs(s,r);if(!this._skipUTF8Validation&&!No(a)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._state===Ss||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=G):(this._state=Qn,setImmediate(()=>{this.emit("message",a,!1),this._state=G,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,jo),this.end();else{let s=t.readUInt16BE(0);if(!Sp(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let a=new Xn(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!No(a)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,a),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=G):(this._state=Qn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=G,this.startLoop(r)}))}createError(t,r,s,a,o){this._loop=!1,this._errored=!0;let i=new t(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=o,i[_p]=a,i}};Ho.exports=xs});var Es=H((ik,qo)=>{"use strict";var{Duplex:ok}=I("stream"),{randomFillSync:xp}=I("crypto"),Uo=yt(),{EMPTY_BUFFER:kp,kWebSocket:wp,NOOP:Rp}=ue(),{isBlob:bt,isValidStatusCode:Ep}=vt(),{mask:Wo,toBuffer:Ge}=Ht(),K=Symbol("kByteLength"),Cp=Buffer.alloc(4),er=8*1024,Ke,St=er,X=0,Ap=1,Tp=2,ws=class n{constructor(t,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=X,this.onerror=Rp,this[wp]=void 0}static frame(t,r){let s,a=!1,o=2,i=!1;r.mask&&(s=r.maskBuffer||Cp,r.generateMask?r.generateMask(s):(St===er&&(Ke===void 0&&(Ke=Buffer.alloc(er)),xp(Ke,0,er),St=0),s[0]=Ke[St++],s[1]=Ke[St++],s[2]=Ke[St++],s[3]=Ke[St++]),i=(s[0]|s[1]|s[2]|s[3])===0,o=6);let c;typeof t=="string"?(!r.mask||i)&&r[K]!==void 0?c=r[K]:(t=Buffer.from(t),c=t.length):(c=t.length,a=r.mask&&r.readOnly&&!i);let d=c;c>=65536?(o+=8,d=127):c>125&&(o+=2,d=126);let l=Buffer.allocUnsafe(a?c+o:o);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[o-4]=s[0],l[o-3]=s[1],l[o-2]=s[2],l[o-1]=s[3],i?[l,t]:a?(Wo(t,s,l,o,c),[l]):(Wo(t,s,t,0,c),[l,t])):[l,t]}close(t,r,s,a){let o;if(t===void 0)o=kp;else{if(typeof t!="number"||!Ep(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+c),o.writeUInt16BE(t,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let i={[K]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==X?this.enqueue([this.dispatch,o,!1,i,a]):this.sendFrame(n.frame(o,i),a)}ping(t,r,s){let a,o;if(typeof t=="string"?(a=Buffer.byteLength(t),o=!1):bt(t)?(a=t.size,o=!1):(t=Ge(t),a=t.length,o=Ge.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:a,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,s]):this.getBlobData(t,!1,i,s):this._state!==X?this.enqueue([this.dispatch,t,!1,i,s]):this.sendFrame(n.frame(t,i),s)}pong(t,r,s){let a,o;if(typeof t=="string"?(a=Buffer.byteLength(t),o=!1):bt(t)?(a=t.size,o=!1):(t=Ge(t),a=t.length,o=Ge.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:a,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,s]):this.getBlobData(t,!1,i,s):this._state!==X?this.enqueue([this.dispatch,t,!1,i,s]):this.sendFrame(n.frame(t,i),s)}send(t,r,s){let a=this._extensions[Uo.extensionName],o=r.binary?2:1,i=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):bt(t)?(c=t.size,d=!1):(t=Ge(t),c=t.length,d=Ge.readOnly),this._firstFragment?(this._firstFragment=!1,i&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=a._threshold),this._compress=i):(i=!1,o=0),r.fin&&(this._firstFragment=!0);let l={[K]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:d,rsv1:i};bt(t)?this._state!==X?this.enqueue([this.getBlobData,t,this._compress,l,s]):this.getBlobData(t,this._compress,l,s):this._state!==X?this.enqueue([this.dispatch,t,this._compress,l,s]):this.dispatch(t,this._compress,l,s)}getBlobData(t,r,s,a){this._bufferedBytes+=s[K],this._state=Tp,t.arrayBuffer().then(o=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Rs,this,c,a);return}this._bufferedBytes-=s[K];let i=Ge(o);r?this.dispatch(i,r,s,a):(this._state=X,this.sendFrame(n.frame(i,s),a),this.dequeue())}).catch(o=>{process.nextTick(Pp,this,o,a)})}dispatch(t,r,s,a){if(!r){this.sendFrame(n.frame(t,s),a);return}let o=this._extensions[Uo.extensionName];this._bufferedBytes+=s[K],this._state=Ap,o.compress(t,s.fin,(i,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");Rs(this,d,a);return}this._bufferedBytes-=s[K],this._state=X,s.readOnly=!1,this.sendFrame(n.frame(c,s),a),this.dequeue()})}dequeue(){for(;this._state===X&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][K],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][K],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};qo.exports=ws;function Rs(n,t,r){typeof r=="function"&&r(t);for(let s=0;s<n._queue.length;s++){let a=n._queue[s],o=a[a.length-1];typeof o=="function"&&o(t)}}function Pp(n,t,r){Rs(n,t,r),n.onerror(t)}});var Qo=H((ck,Xo)=>{"use strict";var{kForOnEventAttribute:Wt,kListener:Cs}=ue(),Bo=Symbol("kCode"),Vo=Symbol("kData"),Go=Symbol("kError"),Ko=Symbol("kMessage"),Zo=Symbol("kReason"),xt=Symbol("kTarget"),Yo=Symbol("kType"),Jo=Symbol("kWasClean"),pe=class{constructor(t){this[xt]=null,this[Yo]=t}get target(){return this[xt]}get type(){return this[Yo]}};Object.defineProperty(pe.prototype,"target",{enumerable:!0});Object.defineProperty(pe.prototype,"type",{enumerable:!0});var Ze=class extends pe{constructor(t,r={}){super(t),this[Bo]=r.code===void 0?0:r.code,this[Zo]=r.reason===void 0?"":r.reason,this[Jo]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Bo]}get reason(){return this[Zo]}get wasClean(){return this[Jo]}};Object.defineProperty(Ze.prototype,"code",{enumerable:!0});Object.defineProperty(Ze.prototype,"reason",{enumerable:!0});Object.defineProperty(Ze.prototype,"wasClean",{enumerable:!0});var kt=class extends pe{constructor(t,r={}){super(t),this[Go]=r.error===void 0?null:r.error,this[Ko]=r.message===void 0?"":r.message}get error(){return this[Go]}get message(){return this[Ko]}};Object.defineProperty(kt.prototype,"error",{enumerable:!0});Object.defineProperty(kt.prototype,"message",{enumerable:!0});var qt=class extends pe{constructor(t,r={}){super(t),this[Vo]=r.data===void 0?null:r.data}get data(){return this[Vo]}};Object.defineProperty(qt.prototype,"data",{enumerable:!0});var Op={addEventListener(n,t,r={}){for(let a of this.listeners(n))if(!r[Wt]&&a[Cs]===t&&!a[Wt])return;let s;if(n==="message")s=function(o,i){let c=new qt("message",{data:i?o:o.toString()});c[xt]=this,tr(t,this,c)};else if(n==="close")s=function(o,i){let c=new Ze("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[xt]=this,tr(t,this,c)};else if(n==="error")s=function(o){let i=new kt("error",{error:o,message:o.message});i[xt]=this,tr(t,this,i)};else if(n==="open")s=function(){let o=new pe("open");o[xt]=this,tr(t,this,o)};else return;s[Wt]=!!r[Wt],s[Cs]=t,r.once?this.once(n,s):this.on(n,s)},removeEventListener(n,t){for(let r of this.listeners(n))if(r[Cs]===t&&!r[Wt]){this.removeListener(n,r);break}}};Xo.exports={CloseEvent:Ze,ErrorEvent:kt,Event:pe,EventTarget:Op,MessageEvent:qt};function tr(n,t,r){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,r):n.call(t,r)}});var nr=H((lk,ei)=>{"use strict";var{tokenChars:Bt}=vt();function ae(n,t,r){n[t]===void 0?n[t]=[r]:n[t].push(r)}function Ip(n){let t=Object.create(null),r=Object.create(null),s=!1,a=!1,o=!1,i,c,d=-1,l=-1,m=-1,h=0;for(;h<n.length;h++)if(l=n.charCodeAt(h),i===void 0)if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(h!==0&&(l===32||l===9))m===-1&&d!==-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h);let R=n.slice(d,m);l===44?(ae(t,R,r),r=Object.create(null)):i=R,d=m=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(l===32||l===9)m===-1&&d!==-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h),ae(r,n.slice(d,m),!0),l===44&&(ae(t,i,r),r=Object.create(null),i=void 0),d=m=-1}else if(l===61&&d!==-1&&m===-1)c=n.slice(d,h),d=m=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(a){if(Bt[l]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);d===-1?d=h:s||(s=!0),a=!1}else if(o)if(Bt[l]===1)d===-1&&(d=h);else if(l===34&&d!==-1)o=!1,m=h;else if(l===92)a=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(l===34&&n.charCodeAt(h-1)===61)o=!0;else if(m===-1&&Bt[l]===1)d===-1&&(d=h);else if(d!==-1&&(l===32||l===9))m===-1&&(m=h);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${h}`);m===-1&&(m=h);let R=n.slice(d,m);s&&(R=R.replace(/\\/g,""),s=!1),ae(r,c,R),l===44&&(ae(t,i,r),r=Object.create(null),i=void 0),c=void 0,d=m=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(d===-1||o||l===32||l===9)throw new SyntaxError("Unexpected end of input");m===-1&&(m=h);let v=n.slice(d,m);return i===void 0?ae(t,v,r):(c===void 0?ae(r,v,!0):s?ae(r,c,v.replace(/\\/g,"")):ae(r,c,v),ae(t,i,r)),t}function Mp(n){return Object.keys(n).map(t=>{let r=n[t];return Array.isArray(r)||(r=[r]),r.map(s=>[t].concat(Object.keys(s).map(a=>{let o=s[a];return Array.isArray(o)||(o=[o]),o.map(i=>i===!0?a:`${a}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ei.exports={format:Mp,parse:Ip}});var or=H((mk,mi)=>{"use strict";var Dp=I("events"),Lp=I("https"),jp=I("http"),ri=I("net"),Np=I("tls"),{randomBytes:Fp,createHash:zp}=I("crypto"),{Duplex:dk,Readable:uk}=I("stream"),{URL:As}=I("url"),ke=yt(),$p=ks(),Hp=Es(),{isBlob:Up}=vt(),{BINARY_TYPES:ti,CLOSE_TIMEOUT:Wp,EMPTY_BUFFER:rr,GUID:qp,kForOnEventAttribute:Ts,kListener:Bp,kStatusCode:Vp,kWebSocket:D,NOOP:si}=ue(),{EventTarget:{addEventListener:Gp,removeEventListener:Kp}}=Qo(),{format:Zp,parse:Yp}=nr(),{toBuffer:Jp}=Ht(),ai=Symbol("kAborted"),Ps=[8,13],he=["CONNECTING","OPEN","CLOSING","CLOSED"],Xp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class n extends Dp{constructor(t,r,s){super(),this._binaryType=ti[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=rr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),oi(this,t,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){ti.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}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(t,r,s){let a=new $p({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new Hp(t,this._extensions,s.generateMask);this._receiver=a,this._sender=o,this._socket=t,a[D]=this,o[D]=this,t[D]=this,a.on("conclude",th),a.on("drain",nh),a.on("error",rh),a.on("message",sh),a.on("ping",ah),a.on("pong",oh),o.onerror=ih,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",li),t.on("data",ar),t.on("end",di),t.on("error",ui),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ke.extensionName]&&this._extensions[ke.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){U(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(t,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ci(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(s=t,t=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Os(this,t,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||rr,r,s)}pong(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(s=t,t=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Os(this,t,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||rr,r,s)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==n.OPEN){Os(this,t,s);return}let a={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ke.extensionName]||(a.compress=!1),this._sender.send(t||rr,a,s)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){U(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(P.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(P.prototype,`on${n}`,{enumerable:!0,get(){for(let t of this.listeners(n))if(t[Ts])return t[Bp];return null},set(t){for(let r of this.listeners(n))if(r[Ts]){this.removeListener(n,r);break}typeof t=="function"&&this.addEventListener(n,t,{[Ts]:!0})}})});P.prototype.addEventListener=Gp;P.prototype.removeEventListener=Kp;mi.exports=P;function oi(n,t,r,s){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Wp,protocolVersion:Ps[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=a.autoPong,n._closeTimeout=a.closeTimeout,!Ps.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${Ps.join(", ")})`);let o;if(t instanceof As)o=t;else try{o=new As(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),n._url=o.href;let i=o.protocol==="wss:",c=o.protocol==="ws+unix:",d;if(o.protocol!=="ws:"&&!i&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!o.pathname?d="The URL's pathname is empty":o.hash&&(d="The URL contains a fragment identifier"),d){let E=new SyntaxError(d);if(n._redirects===0)throw E;sr(n,E);return}let l=i?443:80,m=Fp(16).toString("base64"),h=i?Lp.request:jp.request,v=new Set,R;if(a.createConnection=a.createConnection||(i?eh:Qp),a.defaultPort=a.defaultPort||l,a.port=o.port||l,a.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},a.path=o.pathname+o.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(R=new ke({...a.perMessageDeflate,isServer:!1,maxPayload:a.maxPayload}),a.headers["Sec-WebSocket-Extensions"]=Zp({[ke.extensionName]:R.offer()})),r.length){for(let E of r){if(typeof E!="string"||!Xp.test(E)||v.has(E))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(E)}a.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(o.username||o.password)&&(a.auth=`${o.username}:${o.password}`),c){let E=a.path.split(":");a.socketPath=E[0],a.path=E[1]}let O;if(a.followRedirects){if(n._redirects===0){n._originalIpc=c,n._originalSecure=i,n._originalHostOrSocketPath=c?a.socketPath:o.host;let E=s&&s.headers;if(s={...s,headers:{}},E)for(let[T,Qe]of Object.entries(E))s.headers[T.toLowerCase()]=Qe}else if(n.listenerCount("redirect")===0){let E=c?n._originalIpc?a.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:o.host===n._originalHostOrSocketPath;(!E||n._originalSecure&&!i)&&(delete a.headers.authorization,delete a.headers.cookie,E||delete a.headers.host,a.auth=void 0)}a.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),O=n._req=h(a),n._redirects&&n.emit("redirect",n.url,O)}else O=n._req=h(a);a.timeout&&O.on("timeout",()=>{U(n,O,"Opening handshake has timed out")}),O.on("error",E=>{O===null||O[ai]||(O=n._req=null,sr(n,E))}),O.on("response",E=>{let T=E.headers.location,Qe=E.statusCode;if(T&&a.followRedirects&&Qe>=300&&Qe<400){if(++n._redirects>a.maxRedirects){U(n,O,"Maximum redirects exceeded");return}O.abort();let wt;try{wt=new As(T,t)}catch{let et=new SyntaxError(`Invalid URL: ${T}`);sr(n,et);return}oi(n,wt,r,s)}else n.emit("unexpected-response",O,E)||U(n,O,`Unexpected server response: ${E.statusCode}`)}),O.on("upgrade",(E,T,Qe)=>{if(n.emit("upgrade",E),n.readyState!==P.CONNECTING)return;O=n._req=null;let wt=E.headers.upgrade;if(wt===void 0||wt.toLowerCase()!=="websocket"){U(n,T,"Invalid Upgrade header");return}let Hs=zp("sha1").update(m+qp).digest("base64");if(E.headers["sec-websocket-accept"]!==Hs){U(n,T,"Invalid Sec-WebSocket-Accept header");return}let et=E.headers["sec-websocket-protocol"],Rt;if(et!==void 0?v.size?v.has(et)||(Rt="Server sent an invalid subprotocol"):Rt="Server sent a subprotocol but none was requested":v.size&&(Rt="Server sent no subprotocol"),Rt){U(n,T,Rt);return}et&&(n._protocol=et);let Us=E.headers["sec-websocket-extensions"];if(Us!==void 0){if(!R){U(n,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let lr;try{lr=Yp(Us)}catch{U(n,T,"Invalid Sec-WebSocket-Extensions header");return}let Ws=Object.keys(lr);if(Ws.length!==1||Ws[0]!==ke.extensionName){U(n,T,"Server indicated an extension that was not requested");return}try{R.accept(lr[ke.extensionName])}catch{U(n,T,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ke.extensionName]=R}n.setSocket(T,Qe,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(O,n):O.end()}function sr(n,t){n._readyState=P.CLOSING,n._errorEmitted=!0,n.emit("error",t),n.emitClose()}function Qp(n){return n.path=n.socketPath,ri.connect(n)}function eh(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=ri.isIP(n.host)?"":n.host),Np.connect(n)}function U(n,t,r){n._readyState=P.CLOSING;let s=new Error(r);Error.captureStackTrace(s,U),t.setHeader?(t[ai]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(sr,n,s)):(t.destroy(s),t.once("error",n.emit.bind(n,"error")),t.once("close",n.emitClose.bind(n)))}function Os(n,t,r){if(t){let s=Up(t)?t.size:Jp(t).length;n._socket?n._sender._bufferedBytes+=s:n._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${n.readyState} (${he[n.readyState]})`);process.nextTick(r,s)}}function th(n,t){let r=this[D];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=n,r._socket[D]!==void 0&&(r._socket.removeListener("data",ar),process.nextTick(ii,r._socket),n===1005?r.close():r.close(n,t))}function nh(){let n=this[D];n.isPaused||n._socket.resume()}function rh(n){let t=this[D];t._socket[D]!==void 0&&(t._socket.removeListener("data",ar),process.nextTick(ii,t._socket),t.close(n[Vp])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n))}function ni(){this[D].emitClose()}function sh(n,t){this[D].emit("message",n,t)}function ah(n){let t=this[D];t._autoPong&&t.pong(n,!this._isServer,si),t.emit("ping",n)}function oh(n){this[D].emit("pong",n)}function ii(n){n.resume()}function ih(n){let t=this[D];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,ci(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",n)))}function ci(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function li(){let n=this[D];if(this.removeListener("close",li),this.removeListener("data",ar),this.removeListener("end",di),n._readyState=P.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);n._receiver.write(t)}n._receiver.end(),this[D]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",ni),n._receiver.on("finish",ni))}function ar(n){this[D]._receiver.write(n)||this.pause()}function di(){let n=this[D];n._readyState=P.CLOSING,n._receiver.end(),this.end()}function ui(){let n=this[D];this.removeListener("error",ui),this.on("error",si),n&&(n._readyState=P.CLOSING,this.destroy())}});var gi=H((hk,fi)=>{"use strict";var pk=or(),{Duplex:ch}=I("stream");function pi(n){n.emit("close")}function lh(){!this.destroyed&&this._writableState.finished&&this.destroy()}function hi(n){this.removeListener("error",hi),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function dh(n,t){let r=!0,s=new ch({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(o,i){let c=!i&&s._readableState.objectMode?o.toString():o;s.push(c)||n.pause()}),n.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),n.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(a,o){if(n.readyState===n.CLOSED){o(a),process.nextTick(pi,s);return}let i=!1;n.once("error",function(d){i=!0,o(d)}),n.once("close",function(){i||o(a),process.nextTick(pi,s)}),r&&n.terminate()},s._final=function(a){if(n.readyState===n.CONNECTING){n.once("open",function(){s._final(a)});return}n._socket!==null&&(n._socket._writableState.finished?(a(),s._readableState.endEmitted&&s.destroy()):(n._socket.once("finish",function(){a()}),n.close()))},s._read=function(){n.isPaused&&n.resume()},s._write=function(a,o,i){if(n.readyState===n.CONNECTING){n.once("open",function(){s._write(a,o,i)});return}n.send(a,i)},s.on("end",lh),s.on("error",hi),s}fi.exports=dh});var Is=H((fk,_i)=>{"use strict";var{tokenChars:uh}=vt();function mh(n){let t=new Set,r=-1,s=-1,a=0;for(a;a<n.length;a++){let i=n.charCodeAt(a);if(s===-1&&uh[i]===1)r===-1&&(r=a);else if(a!==0&&(i===32||i===9))s===-1&&r!==-1&&(s=a);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${a}`);s===-1&&(s=a);let c=n.slice(r,s);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=n.slice(r,a);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}_i.exports={parse:mh}});var wi=H((_k,ki)=>{"use strict";var ph=I("events"),ir=I("http"),{Duplex:gk}=I("stream"),{createHash:hh}=I("crypto"),yi=nr(),Ye=yt(),fh=Is(),gh=or(),{CLOSE_TIMEOUT:_h,GUID:yh,kWebSocket:vh}=ue(),bh=/^[+/0-9A-Za-z]{22}==$/,vi=0,bi=1,xi=2,Ms=class extends ph{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:_h,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:gh,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=ir.createServer((s,a)=>{let o=ir.STATUS_CODES[426];a.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),a.end(o)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=Sh(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,o,i)=>{this.handleUpgrade(a,o,i,s)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=vi}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===xi){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Vt,this);return}if(t&&this.once("close",t),this._state!==bi)if(this._state=bi,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(Vt,this):process.nextTick(Vt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Vt(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,s,a){r.on("error",Si);let o=t.headers["sec-websocket-key"],i=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Je(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Je(this,t,r,400,"Invalid Upgrade header");return}if(o===void 0||!bh.test(o)){Je(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Je(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Gt(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=fh.parse(d)}catch{Je(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let m=t.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&m!==void 0){let v=new Ye({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let R=yi.parse(m);R[Ye.extensionName]&&(v.accept(R[Ye.extensionName]),h[Ye.extensionName]=v)}catch{Je(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(R,O,E,T)=>{if(!R)return Gt(r,O||401,E,T);this.completeUpgrade(h,o,l,t,r,s,a)});return}if(!this.options.verifyClient(v))return Gt(r,401)}this.completeUpgrade(h,o,l,t,r,s,a)}completeUpgrade(t,r,s,a,o,i,c){if(!o.readable||!o.writable)return o.destroy();if(o[vh])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>vi)return Gt(o,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hh("sha1").update(r+yh).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(s.size){let h=this.options.handleProtocols?this.options.handleProtocols(s,a):s.values().next().value;h&&(l.push(`Sec-WebSocket-Protocol: ${h}`),m._protocol=h)}if(t[Ye.extensionName]){let h=t[Ye.extensionName].params,v=yi.format({[Ye.extensionName]:[h]});l.push(`Sec-WebSocket-Extensions: ${v}`),m._extensions=t}this.emit("headers",l,a),o.write(l.concat(`\r
|
|
4
4
|
`).join(`\r
|
|
5
|
-
`)),
|
|
6
|
-
`+Object.keys(s).map(
|
|
5
|
+
`)),o.removeListener("error",Si),m.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Vt,this)})),c(m,a)}};ki.exports=Ms;function Sh(n,t){for(let r of Object.keys(t))n.on(r,t[r]);return function(){for(let s of Object.keys(t))n.removeListener(s,t[s])}}function Vt(n){n._state=xi,n.emit("close")}function Si(){this.destroy()}function Gt(n,t,r,s){r=r||ir.STATUS_CODES[t],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${t} ${ir.STATUS_CODES[t]}\r
|
|
6
|
+
`+Object.keys(s).map(a=>`${a}: ${s[a]}`).join(`\r
|
|
7
7
|
`)+`\r
|
|
8
8
|
\r
|
|
9
|
-
`+r)}function Je(n,t,r,s,o,a){if(n.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,Je),n.emit("wsClientError",i,r,t)}else Gt(r,s,o,a)}});import{performance as Qi}from"node:perf_hooks";var Et="5 MB";var e={};ac(e,{BRAND:()=>Mc,DIRTY:()=>Ee,EMPTY_PATH:()=>uc,INVALID:()=>b,NEVER:()=>_l,OK:()=>N,ParseStatus:()=>L,Schema:()=>k,ZodAny:()=>ye,ZodArray:()=>le,ZodBigInt:()=>Ae,ZodBoolean:()=>Te,ZodBranded:()=>At,ZodCatch:()=>$e,ZodDate:()=>Pe,ZodDefault:()=>ze,ZodDiscriminatedUnion:()=>Qt,ZodEffects:()=>B,ZodEnum:()=>Ne,ZodError:()=>z,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>tn,ZodIntersection:()=>De,ZodIssueCode:()=>p,ZodLazy:()=>Le,ZodLiteral:()=>je,ZodMap:()=>at,ZodNaN:()=>ct,ZodNativeEnum:()=>Fe,ZodNever:()=>Y,ZodNull:()=>Ie,ZodNullable:()=>te,ZodNumber:()=>Ce,ZodObject:()=>$,ZodOptional:()=>W,ZodParsedType:()=>g,ZodPipeline:()=>Tt,ZodPromise:()=>ve,ZodReadonly:()=>He,ZodRecord:()=>en,ZodSchema:()=>k,ZodSet:()=>it,ZodString:()=>_e,ZodSymbol:()=>st,ZodTransformer:()=>B,ZodTuple:()=>ee,ZodType:()=>k,ZodUndefined:()=>Oe,ZodUnion:()=>Me,ZodUnknown:()=>ce,ZodVoid:()=>ot,addIssueToContext:()=>f,any:()=>Uc,array:()=>Vc,bigint:()=>Nc,boolean:()=>Xs,coerce:()=>gl,custom:()=>Zs,date:()=>Fc,datetimeRegex:()=>Gs,defaultErrorMap:()=>ae,discriminatedUnion:()=>Yc,effect:()=>cl,enum:()=>ol,function:()=>nl,getErrorMap:()=>tt,getParsedType:()=>Q,instanceof:()=>Lc,intersection:()=>Jc,isAborted:()=>Jt,isAsync:()=>nt,isDirty:()=>Xt,isValid:()=>ge,late:()=>Dc,lazy:()=>rl,literal:()=>sl,makeIssue:()=>Ct,map:()=>el,nan:()=>jc,nativeEnum:()=>al,never:()=>qc,null:()=>Hc,nullable:()=>dl,number:()=>Js,object:()=>Gc,objectUtil:()=>dr,oboolean:()=>fl,onumber:()=>hl,optional:()=>ll,ostring:()=>pl,pipeline:()=>ml,preprocess:()=>ul,promise:()=>il,quotelessJson:()=>cc,record:()=>Qc,set:()=>tl,setErrorMap:()=>dc,strictObject:()=>Kc,string:()=>Ys,symbol:()=>zc,transformer:()=>cl,tuple:()=>Xc,undefined:()=>$c,union:()=>Zc,unknown:()=>Wc,util:()=>w,void:()=>Bc});var w;(function(n){n.assertEqual=o=>{};function t(o){}n.assertIs=t;function r(o){throw new Error}n.assertNever=r,n.arrayToEnum=o=>{let a={};for(let i of o)a[i]=i;return a},n.getValidEnumValues=o=>{let a=n.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),i={};for(let c of a)i[c]=o[c];return n.objectValues(i)},n.objectValues=o=>n.objectKeys(o).map(function(a){return o[a]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let a=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&a.push(i);return a},n.find=(o,a)=>{for(let i of o)if(a(i))return i},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function s(o,a=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}n.joinValues=s,n.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a})(w||(w={}));var dr;(function(n){n.mergeShapes=(t,r)=>({...t,...r})})(dr||(dr={}));var g=w.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Q=n=>{switch(typeof n){case"undefined":return g.undefined;case"string":return g.string;case"number":return Number.isNaN(n)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":return Array.isArray(n)?g.array:n===null?g.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?g.promise:typeof Map<"u"&&n instanceof Map?g.map:typeof Set<"u"&&n instanceof Set?g.set:typeof Date<"u"&&n instanceof Date?g.date:g.object;default:return g.unknown}};var p=w.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"]),cc=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),z=class n extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(a){return a.message},s={_errors:[]},o=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)s._errors.push(r(i));else{let c=s,d=0;for(;d<i.path.length;){let l=i.path[d];d===i.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(i))):c[l]=c[l]||{_errors:[]},c=c[l],d++}}};return o(this),s}static assert(t){if(!(t instanceof n))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,w.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},s=[];for(let o of this.issues)if(o.path.length>0){let a=o.path[0];r[a]=r[a]||[],r[a].push(t(o))}else s.push(t(o));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};z.create=n=>new z(n);var lc=(n,t)=>{let r;switch(n.code){case p.invalid_type:n.received===g.undefined?r="Required":r=`Expected ${n.expected}, received ${n.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(n.expected,w.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${w.joinValues(n.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${w.joinValues(n.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${w.joinValues(n.options)}, received '${n.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(r=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?r=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?r=`Invalid input: must end with "${n.validation.endsWith}"`:w.assertNever(n.validation):n.validation!=="regex"?r=`Invalid ${n.validation}`:r="Invalid";break;case p.too_small:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:r="Invalid input";break;case p.too_big:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?r=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:r="Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${n.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,w.assertNever(n)}return{message:r}},ae=lc;var Us=ae;function dc(n){Us=n}function tt(){return Us}var Ct=n=>{let{data:t,path:r,errorMaps:s,issueData:o}=n,a=[...r,...o.path||[]],i={...o,path:a};if(o.message!==void 0)return{...o,path:a,message:o.message};let c="",d=s.filter(l=>!!l).slice().reverse();for(let l of d)c=l(i,{data:t,defaultError:c}).message;return{...o,path:a,message:c}},uc=[];function f(n,t){let r=tt(),s=Ct({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,r,r===ae?void 0:ae].filter(o=>!!o)});n.common.issues.push(s)}var L=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let s=[];for(let o of r){if(o.status==="aborted")return b;o.status==="dirty"&&t.dirty(),s.push(o.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,r){let s=[];for(let o of r){let a=await o.key,i=await o.value;s.push({key:a,value:i})}return n.mergeObjectSync(t,s)}static mergeObjectSync(t,r){let s={};for(let o of r){let{key:a,value:i}=o;if(a.status==="aborted"||i.status==="aborted")return b;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(s[a.value]=i.value)}return{status:t.value,value:s}}},b=Object.freeze({status:"aborted"}),Ee=n=>({status:"dirty",value:n}),N=n=>({status:"valid",value:n}),Jt=n=>n.status==="aborted",Xt=n=>n.status==="dirty",ge=n=>n.status==="valid",nt=n=>typeof Promise<"u"&&n instanceof Promise;var _;(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(_||(_={}));var q=class{constructor(t,r,s,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=s,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}},Ws=(n,t)=>{if(ge(t))return{success:!0,data:t.value};if(!n.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 z(n.common.issues);return this._error=r,this._error}}};function x(n){if(!n)return{};let{errorMap:t,invalid_type_error:r,required_error:s,description:o}=n;if(t&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,c)=>{let{message:d}=n;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:d??s??c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:d??r??c.defaultError}},description:o}}var k=class{get description(){return this._def.description}_getType(t){return Q(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Q(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:Q(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(nt(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let s=this.safeParse(t,r);if(s.success)return s.data;throw s.error}safeParse(t,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)},o=this._parseSync({data:t,path:s.path,parent:s});return Ws(s,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:r});return ge(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(s=>ge(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(t,r){let s=await this.safeParseAsync(t,r);if(s.success)return s.data;throw s.error}async safeParseAsync(t,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)},o=this._parse({data:t,path:s.path,parent:s}),a=await(nt(o)?o:Promise.resolve(o));return Ws(s,a)}refine(t,r){let s=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,a)=>{let i=t(o),c=()=>a.addIssue({code:p.custom,...s(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(t,r){return this._refinement((s,o)=>t(s)?!0:(o.addIssue(typeof r=="function"?r(s,o):r),!1))}_refinement(t){return new B({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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 W.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return ve.create(this,this._def)}or(t){return Me.create([this,t],this._def)}and(t){return De.create(this,t,this._def)}transform(t){return new B({...x(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new ze({...x(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new At({typeName:S.ZodBranded,type:this,...x(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new $e({...x(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Tt.create(this,t)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mc=/^c[^\s-]{8,}$/i,pc=/^[0-9a-z]+$/,hc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fc=/^[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,gc=/^[a-z0-9_-]{21}$/i,_c=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yc=/^[-+]?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)?)??$/,vc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ur,Sc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xc=/^(?:(?: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])$/,kc=/^(([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]))$/,wc=/^(([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])$/,Rc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ec=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bs="((\\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])))",Cc=new RegExp(`^${Bs}$`);function Vs(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);let r=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Ac(n){return new RegExp(`^${Vs(n)}$`)}function Gs(n){let t=`${Bs}T${Vs(n)}`,r=[];return r.push(n.local?"Z?":"Z"),n.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Tc(n,t){return!!((t==="v4"||!t)&&Sc.test(n)||(t==="v6"||!t)&&kc.test(n))}function Pc(n,t){if(!_c.test(n))return!1;try{let[r]=n.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(s));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Oc(n,t){return!!((t==="v4"||!t)&&xc.test(n)||(t==="v6"||!t)&&wc.test(n))}var _e=class n extends k{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==g.string){let a=this._getOrReturnCtx(t);return f(a,{code:p.invalid_type,expected:g.string,received:a.parsedType}),b}let s=new L,o;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),f(o,{code:p.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")t.data.length>a.value&&(o=this._getOrReturnCtx(t,o),f(o,{code:p.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){let i=t.data.length>a.value,c=t.data.length<a.value;(i||c)&&(o=this._getOrReturnCtx(t,o),i?f(o,{code:p.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):c&&f(o,{code:p.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")vc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"email",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")ur||(ur=new RegExp(bc,"u")),ur.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"emoji",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")fc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"uuid",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")gc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"nanoid",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")mc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"cuid",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")pc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"cuid2",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")hc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"ulid",code:p.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),f(o,{validation:"url",code:p.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"regex",code:p.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Gs(a).test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Cc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?Ac(a).test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{code:p.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?yc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"duration",code:p.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Tc(t.data,a.version)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"ip",code:p.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Pc(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"jwt",code:p.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Oc(t.data,a.version)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"cidr",code:p.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?Rc.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"base64",code:p.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?Ec.test(t.data)||(o=this._getOrReturnCtx(t,o),f(o,{validation:"base64url",code:p.invalid_string,message:a.message}),s.dirty()):w.assertNever(a);return{status:s.value,value:t.data}}_regex(t,r,s){return this.refinement(o=>t.test(o),{validation:r,code:p.invalid_string,..._.errToObj(s)})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",..._.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",..._.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",..._.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,..._.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,..._.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",..._.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,..._.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,..._.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,..._.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,..._.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,..._.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,..._.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,..._.errToObj(r)})}nonempty(t){return this.min(1,_.errToObj(t))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_e.create=n=>new _e({checks:[],typeName:S.ZodString,coerce:n?.coerce??!1,...x(n)});function Ic(n,t){let r=(n.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,o=r>s?r:s,a=Number.parseInt(n.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}var Ce=class n extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==g.number){let a=this._getOrReturnCtx(t);return f(a,{code:p.invalid_type,expected:g.number,received:a.parsedType}),b}let s,o=new L;for(let a of this._def.checks)a.kind==="int"?w.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),f(s,{code:p.invalid_type,expected:"integer",received:"float",message:a.message}),o.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="multipleOf"?Ic(t.data,a.value)!==0&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_finite,message:a.message}),o.dirty()):w.assertNever(a);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,_.toString(r))}gt(t,r){return this.setLimit("min",t,!1,_.toString(r))}lte(t,r){return this.setLimit("max",t,!0,_.toString(r))}lt(t,r){return this.setLimit("max",t,!1,_.toString(r))}setLimit(t,r,s,o){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:s,message:_.toString(o)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:_.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&w.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Ce.create=n=>new Ce({checks:[],typeName:S.ZodNumber,coerce:n?.coerce||!1,...x(n)});var Ae=class n extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==g.bigint)return this._getInvalidInput(t);let s,o=new L;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):w.assertNever(a);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return f(r,{code:p.invalid_type,expected:g.bigint,received:r.parsedType}),b}gte(t,r){return this.setLimit("min",t,!0,_.toString(r))}gt(t,r){return this.setLimit("min",t,!1,_.toString(r))}lte(t,r){return this.setLimit("max",t,!0,_.toString(r))}lt(t,r){return this.setLimit("max",t,!1,_.toString(r))}setLimit(t,r,s,o){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:s,message:_.toString(o)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Ae.create=n=>new Ae({checks:[],typeName:S.ZodBigInt,coerce:n?.coerce??!1,...x(n)});var Te=class extends k{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==g.boolean){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.boolean,received:s.parsedType}),b}return N(t.data)}};Te.create=n=>new Te({typeName:S.ZodBoolean,coerce:n?.coerce||!1,...x(n)});var Pe=class n extends k{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==g.date){let a=this._getOrReturnCtx(t);return f(a,{code:p.invalid_type,expected:g.date,received:a.parsedType}),b}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return f(a,{code:p.invalid_date}),b}let s=new L,o;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),f(o,{code:p.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(o=this._getOrReturnCtx(t,o),f(o,{code:p.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):w.assertNever(a);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:_.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:_.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Pe.create=n=>new Pe({checks:[],coerce:n?.coerce||!1,typeName:S.ZodDate,...x(n)});var st=class extends k{_parse(t){if(this._getType(t)!==g.symbol){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.symbol,received:s.parsedType}),b}return N(t.data)}};st.create=n=>new st({typeName:S.ZodSymbol,...x(n)});var Oe=class extends k{_parse(t){if(this._getType(t)!==g.undefined){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.undefined,received:s.parsedType}),b}return N(t.data)}};Oe.create=n=>new Oe({typeName:S.ZodUndefined,...x(n)});var Ie=class extends k{_parse(t){if(this._getType(t)!==g.null){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.null,received:s.parsedType}),b}return N(t.data)}};Ie.create=n=>new Ie({typeName:S.ZodNull,...x(n)});var ye=class extends k{constructor(){super(...arguments),this._any=!0}_parse(t){return N(t.data)}};ye.create=n=>new ye({typeName:S.ZodAny,...x(n)});var ce=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(t){return N(t.data)}};ce.create=n=>new ce({typeName:S.ZodUnknown,...x(n)});var Y=class extends k{_parse(t){let r=this._getOrReturnCtx(t);return f(r,{code:p.invalid_type,expected:g.never,received:r.parsedType}),b}};Y.create=n=>new Y({typeName:S.ZodNever,...x(n)});var ot=class extends k{_parse(t){if(this._getType(t)!==g.undefined){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.void,received:s.parsedType}),b}return N(t.data)}};ot.create=n=>new ot({typeName:S.ZodVoid,...x(n)});var le=class n extends k{_parse(t){let{ctx:r,status:s}=this._processInputParams(t),o=this._def;if(r.parsedType!==g.array)return f(r,{code:p.invalid_type,expected:g.array,received:r.parsedType}),b;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,c=r.data.length<o.exactLength.value;(i||c)&&(f(r,{code:i?p.too_big:p.too_small,minimum:c?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),s.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(f(r,{code:p.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),s.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(f(r,{code:p.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((i,c)=>o.type._parseAsync(new q(r,i,r.path,c)))).then(i=>L.mergeArray(s,i));let a=[...r.data].map((i,c)=>o.type._parseSync(new q(r,i,r.path,c)));return L.mergeArray(s,a)}get element(){return this._def.type}min(t,r){return new n({...this._def,minLength:{value:t,message:_.toString(r)}})}max(t,r){return new n({...this._def,maxLength:{value:t,message:_.toString(r)}})}length(t,r){return new n({...this._def,exactLength:{value:t,message:_.toString(r)}})}nonempty(t){return this.min(1,t)}};le.create=(n,t)=>new le({type:n,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...x(t)});function rt(n){if(n instanceof $){let t={};for(let r in n.shape){let s=n.shape[r];t[r]=W.create(rt(s))}return new $({...n._def,shape:()=>t})}else return n instanceof le?new le({...n._def,type:rt(n.element)}):n instanceof W?W.create(rt(n.unwrap())):n instanceof te?te.create(rt(n.unwrap())):n instanceof ee?ee.create(n.items.map(t=>rt(t))):n}var $=class n extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=w.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==g.object){let l=this._getOrReturnCtx(t);return f(l,{code:p.invalid_type,expected:g.object,received:l.parsedType}),b}let{status:s,ctx:o}=this._processInputParams(t),{shape:a,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Y&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||c.push(l);let d=[];for(let l of i){let m=a[l],h=o.data[l];d.push({key:{status:"valid",value:l},value:m._parse(new q(o,h,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Y){let l=this._def.unknownKeys;if(l==="passthrough")for(let m of c)d.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(l==="strict")c.length>0&&(f(o,{code:p.unrecognized_keys,keys:c}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let m of c){let h=o.data[m];d.push({key:{status:"valid",value:m},value:l._parse(new q(o,h,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let m of d){let h=await m.key,v=await m.value;l.push({key:h,value:v,alwaysSet:m.alwaysSet})}return l}).then(l=>L.mergeObjectSync(s,l)):L.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(t){return _.errToObj,new n({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,s)=>{let o=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:_.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(t){return new n({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new n({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:S.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new n({...this._def,catchall:t})}pick(t){let r={};for(let s of w.objectKeys(t))t[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new n({...this._def,shape:()=>r})}omit(t){let r={};for(let s of w.objectKeys(this.shape))t[s]||(r[s]=this.shape[s]);return new n({...this._def,shape:()=>r})}deepPartial(){return rt(this)}partial(t){let r={};for(let s of w.objectKeys(this.shape)){let o=this.shape[s];t&&!t[s]?r[s]=o:r[s]=o.optional()}return new n({...this._def,shape:()=>r})}required(t){let r={};for(let s of w.objectKeys(this.shape))if(t&&!t[s])r[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof W;)a=a._def.innerType;r[s]=a}return new n({...this._def,shape:()=>r})}keyof(){return Ks(w.objectKeys(this.shape))}};$.create=(n,t)=>new $({shape:()=>n,unknownKeys:"strip",catchall:Y.create(),typeName:S.ZodObject,...x(t)});$.strictCreate=(n,t)=>new $({shape:()=>n,unknownKeys:"strict",catchall:Y.create(),typeName:S.ZodObject,...x(t)});$.lazycreate=(n,t)=>new $({shape:n,unknownKeys:"strip",catchall:Y.create(),typeName:S.ZodObject,...x(t)});var Me=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=this._def.options;function o(a){for(let c of a)if(c.result.status==="valid")return c.result;for(let c of a)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let i=a.map(c=>new z(c.ctx.common.issues));return f(r,{code:p.invalid_union,unionErrors:i}),b}if(r.common.async)return Promise.all(s.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let a,i=[];for(let d of s){let l={...r,common:{...r.common,issues:[]},parent:null},m=d._parseSync({data:r.data,path:r.path,parent:l});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let c=i.map(d=>new z(d));return f(r,{code:p.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}};Me.create=(n,t)=>new Me({options:n,typeName:S.ZodUnion,...x(t)});var ie=n=>n instanceof Le?ie(n.schema):n instanceof B?ie(n.innerType()):n instanceof je?[n.value]:n instanceof Ne?n.options:n instanceof Fe?w.objectValues(n.enum):n instanceof ze?ie(n._def.innerType):n instanceof Oe?[void 0]:n instanceof Ie?[null]:n instanceof W?[void 0,...ie(n.unwrap())]:n instanceof te?[null,...ie(n.unwrap())]:n instanceof At||n instanceof He?ie(n.unwrap()):n instanceof $e?ie(n._def.innerType):[],Qt=class n extends k{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.object)return f(r,{code:p.invalid_type,expected:g.object,received:r.parsedType}),b;let s=this.discriminator,o=r.data[s],a=this.optionsMap.get(o);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(f(r,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,s){let o=new Map;for(let a of r){let i=ie(a.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of i){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,a)}}return new n({typeName:S.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...x(s)})}};function mr(n,t){let r=Q(n),s=Q(t);if(n===t)return{valid:!0,data:n};if(r===g.object&&s===g.object){let o=w.objectKeys(t),a=w.objectKeys(n).filter(c=>o.indexOf(c)!==-1),i={...n,...t};for(let c of a){let d=mr(n[c],t[c]);if(!d.valid)return{valid:!1};i[c]=d.data}return{valid:!0,data:i}}else if(r===g.array&&s===g.array){if(n.length!==t.length)return{valid:!1};let o=[];for(let a=0;a<n.length;a++){let i=n[a],c=t[a],d=mr(i,c);if(!d.valid)return{valid:!1};o.push(d.data)}return{valid:!0,data:o}}else return r===g.date&&s===g.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}var De=class extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t),o=(a,i)=>{if(Jt(a)||Jt(i))return b;let c=mr(a.value,i.value);return c.valid?((Xt(a)||Xt(i))&&r.dirty(),{status:r.value,value:c.data}):(f(s,{code:p.invalid_intersection_types}),b)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>o(a,i)):o(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};De.create=(n,t,r)=>new De({left:n,right:t,typeName:S.ZodIntersection,...x(r)});var ee=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.array)return f(s,{code:p.invalid_type,expected:g.array,received:s.parsedType}),b;if(s.data.length<this._def.items.length)return f(s,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&s.data.length>this._def.items.length&&(f(s,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...s.data].map((i,c)=>{let d=this._def.items[c]||this._def.rest;return d?d._parse(new q(s,i,s.path,c)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>L.mergeArray(r,i)):L.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new n({...this._def,rest:t})}};ee.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:n,typeName:S.ZodTuple,rest:null,...x(t)})};var en=class n extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.object)return f(s,{code:p.invalid_type,expected:g.object,received:s.parsedType}),b;let o=[],a=this._def.keyType,i=this._def.valueType;for(let c in s.data)o.push({key:a._parse(new q(s,c,s.path,c)),value:i._parse(new q(s,s.data[c],s.path,c)),alwaysSet:c in s.data});return s.common.async?L.mergeObjectAsync(r,o):L.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,s){return r instanceof k?new n({keyType:t,valueType:r,typeName:S.ZodRecord,...x(s)}):new n({keyType:_e.create(),valueType:t,typeName:S.ZodRecord,...x(r)})}},at=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.map)return f(s,{code:p.invalid_type,expected:g.map,received:s.parsedType}),b;let o=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([c,d],l)=>({key:o._parse(new q(s,c,s.path,[l,"key"])),value:a._parse(new q(s,d,s.path,[l,"value"]))}));if(s.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let d of i){let l=await d.key,m=await d.value;if(l.status==="aborted"||m.status==="aborted")return b;(l.status==="dirty"||m.status==="dirty")&&r.dirty(),c.set(l.value,m.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let d of i){let l=d.key,m=d.value;if(l.status==="aborted"||m.status==="aborted")return b;(l.status==="dirty"||m.status==="dirty")&&r.dirty(),c.set(l.value,m.value)}return{status:r.value,value:c}}}};at.create=(n,t,r)=>new at({valueType:t,keyType:n,typeName:S.ZodMap,...x(r)});var it=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.set)return f(s,{code:p.invalid_type,expected:g.set,received:s.parsedType}),b;let o=this._def;o.minSize!==null&&s.data.size<o.minSize.value&&(f(s,{code:p.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&s.data.size>o.maxSize.value&&(f(s,{code:p.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let a=this._def.valueType;function i(d){let l=new Set;for(let m of d){if(m.status==="aborted")return b;m.status==="dirty"&&r.dirty(),l.add(m.value)}return{status:r.value,value:l}}let c=[...s.data.values()].map((d,l)=>a._parse(new q(s,d,s.path,l)));return s.common.async?Promise.all(c).then(d=>i(d)):i(c)}min(t,r){return new n({...this._def,minSize:{value:t,message:_.toString(r)}})}max(t,r){return new n({...this._def,maxSize:{value:t,message:_.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};it.create=(n,t)=>new it({valueType:n,minSize:null,maxSize:null,typeName:S.ZodSet,...x(t)});var tn=class n extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.function)return f(r,{code:p.invalid_type,expected:g.function,received:r.parsedType}),b;function s(c,d){return Ct({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,tt(),ae].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:d}})}function o(c,d){return Ct({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,tt(),ae].filter(l=>!!l),issueData:{code:p.invalid_return_type,returnTypeError:d}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ve){let c=this;return N(async function(...d){let l=new z([]),m=await c._def.args.parseAsync(d,a).catch(R=>{throw l.addIssue(s(d,R)),l}),h=await Reflect.apply(i,this,m);return await c._def.returns._def.type.parseAsync(h,a).catch(R=>{throw l.addIssue(o(h,R)),l})})}else{let c=this;return N(function(...d){let l=c._def.args.safeParse(d,a);if(!l.success)throw new z([s(d,l.error)]);let m=Reflect.apply(i,this,l.data),h=c._def.returns.safeParse(m,a);if(!h.success)throw new z([o(m,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new n({...this._def,args:ee.create(t).rest(ce.create())})}returns(t){return new n({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,s){return new n({args:t||ee.create([]).rest(ce.create()),returns:r||ce.create(),typeName:S.ZodFunction,...x(s)})}},Le=class extends k{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Le.create=(n,t)=>new Le({getter:n,typeName:S.ZodLazy,...x(t)});var je=class extends k{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return f(r,{received:r.data,code:p.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:t.data}}get value(){return this._def.value}};je.create=(n,t)=>new je({value:n,typeName:S.ZodLiteral,...x(t)});function Ks(n,t){return new Ne({values:n,typeName:S.ZodEnum,...x(t)})}var Ne=class n extends k{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),s=this._def.values;return f(r,{expected:w.joinValues(s),received:r.parsedType,code:p.invalid_type}),b}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),s=this._def.values;return f(r,{received:r.data,code:p.invalid_enum_value,options:s}),b}return N(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return n.create(t,{...this._def,...r})}exclude(t,r=this._def){return n.create(this.options.filter(s=>!t.includes(s)),{...this._def,...r})}};Ne.create=Ks;var Fe=class extends k{_parse(t){let r=w.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==g.string&&s.parsedType!==g.number){let o=w.objectValues(r);return f(s,{expected:w.joinValues(o),received:s.parsedType,code:p.invalid_type}),b}if(this._cache||(this._cache=new Set(w.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=w.objectValues(r);return f(s,{received:s.data,code:p.invalid_enum_value,options:o}),b}return N(t.data)}get enum(){return this._def.values}};Fe.create=(n,t)=>new Fe({values:n,typeName:S.ZodNativeEnum,...x(t)});var ve=class extends k{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.promise&&r.common.async===!1)return f(r,{code:p.invalid_type,expected:g.promise,received:r.parsedType}),b;let s=r.parsedType===g.promise?r.data:Promise.resolve(r.data);return N(s.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ve.create=(n,t)=>new ve({type:n,typeName:S.ZodPromise,...x(t)});var B=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:s}=this._processInputParams(t),o=this._def.effect||null,a={addIssue:i=>{f(s,i),i.fatal?r.abort():r.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){let i=o.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async c=>{if(r.value==="aborted")return b;let d=await this._def.schema._parseAsync({data:c,path:s.path,parent:s});return d.status==="aborted"?b:d.status==="dirty"?Ee(d.value):r.value==="dirty"?Ee(d.value):d});{if(r.value==="aborted")return b;let c=this._def.schema._parseSync({data:i,path:s.path,parent:s});return c.status==="aborted"?b:c.status==="dirty"?Ee(c.value):r.value==="dirty"?Ee(c.value):c}}if(o.type==="refinement"){let i=c=>{let d=o.refinement(c,a);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(s.common.async===!1){let c=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?b:(c.status==="dirty"&&r.dirty(),i(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(c=>c.status==="aborted"?b:(c.status==="dirty"&&r.dirty(),i(c.value).then(()=>({status:r.value,value:c.value}))))}if(o.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ge(i))return b;let c=o.transform(i.value,a);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:s.data,path:s.path,parent:s}).then(i=>ge(i)?Promise.resolve(o.transform(i.value,a)).then(c=>({status:r.value,value:c})):b);w.assertNever(o)}};B.create=(n,t,r)=>new B({schema:n,typeName:S.ZodEffects,effect:t,...x(r)});B.createWithPreprocess=(n,t,r)=>new B({schema:t,effect:{type:"preprocess",transform:n},typeName:S.ZodEffects,...x(r)});var W=class extends k{_parse(t){return this._getType(t)===g.undefined?N(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};W.create=(n,t)=>new W({innerType:n,typeName:S.ZodOptional,...x(t)});var te=class extends k{_parse(t){return this._getType(t)===g.null?N(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};te.create=(n,t)=>new te({innerType:n,typeName:S.ZodNullable,...x(t)});var ze=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=r.data;return r.parsedType===g.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ze.create=(n,t)=>new ze({innerType:n,typeName:S.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...x(t)});var $e=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return nt(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new z(s.common.issues)},input:s.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};$e.create=(n,t)=>new $e({innerType:n,typeName:S.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...x(t)});var ct=class extends k{_parse(t){if(this._getType(t)!==g.nan){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.nan,received:s.parsedType}),b}return{status:"valid",value:t.data}}};ct.create=n=>new ct({typeName:S.ZodNaN,...x(n)});var Mc=Symbol("zod_brand"),At=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Tt=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?b:a.status==="dirty"?(r.dirty(),Ee(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{let o=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?b:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:s.path,parent:s})}}static create(t,r){return new n({in:t,out:r,typeName:S.ZodPipeline})}},He=class extends k{_parse(t){let r=this._def.innerType._parse(t),s=o=>(ge(o)&&(o.value=Object.freeze(o.value)),o);return nt(r)?r.then(o=>s(o)):s(r)}unwrap(){return this._def.innerType}};He.create=(n,t)=>new He({innerType:n,typeName:S.ZodReadonly,...x(t)});function qs(n,t){let r=typeof n=="function"?n(t):typeof n=="string"?{message:n}:n;return typeof r=="string"?{message:r}:r}function Zs(n,t={},r){return n?ye.create().superRefine((s,o)=>{let a=n(s);if(a instanceof Promise)return a.then(i=>{if(!i){let c=qs(t,s),d=c.fatal??r??!0;o.addIssue({code:"custom",...c,fatal:d})}});if(!a){let i=qs(t,s),c=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:c})}}):ye.create()}var Dc={object:$.lazycreate},S;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(S||(S={}));var Lc=(n,t={message:`Input not instance of ${n.name}`})=>Zs(r=>r instanceof n,t),Ys=_e.create,Js=Ce.create,jc=ct.create,Nc=Ae.create,Xs=Te.create,Fc=Pe.create,zc=st.create,$c=Oe.create,Hc=Ie.create,Uc=ye.create,Wc=ce.create,qc=Y.create,Bc=ot.create,Vc=le.create,Gc=$.create,Kc=$.strictCreate,Zc=Me.create,Yc=Qt.create,Jc=De.create,Xc=ee.create,Qc=en.create,el=at.create,tl=it.create,nl=tn.create,rl=Le.create,sl=je.create,ol=Ne.create,al=Fe.create,il=ve.create,cl=B.create,ll=W.create,dl=te.create,ul=B.createWithPreprocess,ml=Tt.create,pl=()=>Ys().optional(),hl=()=>Js().optional(),fl=()=>Xs().optional(),gl={string:(n=>_e.create({...n,coerce:!0})),number:(n=>Ce.create({...n,coerce:!0})),boolean:(n=>Te.create({...n,coerce:!0})),bigint:(n=>Ae.create({...n,coerce:!0})),date:(n=>Pe.create({...n,coerce:!0}))};var _l=b;var F=e.enum(["claude","codex","cursor","gemini","qoder"]),lt=e.enum(["none","low","medium","high","xhigh","max"]),nn=e.boolean(),rn=e.enum(["local","remote"]),Qs=e.enum(["app_install","user_invite","system"]),bg=e.enum(["long_lived","bootstrap"]),ne=e.enum(["regular","agent_home"]),V=e.enum(["channel","dm_channel"]),eo=e.enum(["starting","active","idle","archived","crashed"]),sn=e.enum(["idle","starting","active","crashed"]),on=e.enum(["user","agent","system"]),J=e.enum(["todo","in_progress","in_review","done","closed"]),to=e.enum(["agent","user"]),no=e.enum(["session_init","thinking","text","tool_call","tool_output","file_change","shell","stderr","compaction_started","compaction_finished","turn_end","error","unknown","parsed_event_dropped"]),ro=e.enum(["pending_materialization","active","failed"]),so=["read_messages","send_messages","read_tasks","create_tasks","write_tasks","read_attachments","upload_attachments","create_threads","create_channels","manage_conversation_members","manage_schedules"],oo=e.enum(["local","s3","oss"]),ao=e.enum(["user","agent"]),io=e.enum(["mention_external","mention_self","agent_start_failed"]);var yl=e.enum(["pending","attached","active","revoked"]),re=e.object({id:e.string(),name:e.string(),kind:rn,created_at:e.number(),revoked_at:e.number().nullable(),last_seen_at:e.number().nullable(),activated_at:e.number().nullable().optional().default(null),finalized_at:e.number().nullable().optional().default(null),connected_host_name:e.string().nullable().optional().default(null),provisioning_source:Qs.optional().default("system"),status:yl.optional().default("pending"),placeable:e.boolean().optional().default(!1),creator_user_id:e.string().nullable().optional().default(null),display_label:e.string().nullable()}),wg=e.object({display_label:e.string().max(256).nullable()}).strict(),Rg=e.object({host:re}),Eg=e.enum(["available","disconnected","unreachable","revoked"]);var Cg=e.object({host_id:e.string()}).strict(),vl=e.enum(["daemon_unreachable","timeout","protocol_error"]),an=e.object({agent_id:e.string(),display_name:e.string(),handle:e.string(),runtime:e.string(),avatar_url:e.string().nullable().optional().default(null),online:e.enum(["online","offline"])}),bl=e.object({os:e.string().min(1),os_arch:e.string().optional(),daemon_version:e.string(),daemon_pid:e.number().int(),started_at:e.number().int(),uptime_ms:e.number().int()}),Sl=e.object({host_id:e.string(),availability:e.literal("available"),snapshot:bl,agents:e.array(an),last_seen_at:e.number().nullable().optional()}).strict(),xl=e.object({host_id:e.string(),availability:e.literal("disconnected"),agents:e.array(an),last_seen_at:e.number().nullable().optional()}).strict(),kl=e.object({host_id:e.string(),availability:e.literal("unreachable"),reason:vl,agents:e.array(an),last_seen_at:e.number().nullable().optional()}).strict(),wl=e.object({host_id:e.string(),availability:e.literal("revoked"),agents:e.array(an),last_seen_at:e.number().nullable().optional()}).strict(),Ag=e.discriminatedUnion("availability",[Sl,xl,kl,wl]),pr=e.object({proxy_url:e.string().nullable(),proxy_runtimes:e.array(F)}),Tg=e.object({config:pr}).strict(),Rl="computer_offline",Pg=e.object({error:e.string(),error_code:e.literal(Rl)}).strict(),Og=e.object({installation_id:e.string().uuid(),label:e.string().trim().min(1).max(128).optional(),current_host_id:e.string().min(1).optional()}).strict(),Ig=e.object({host_id:e.string(),host:re,server_url:e.string().url(),host_token:e.string().min(1).optional()}),Mg=e.object({hosts:e.array(re)}),Dg=e.object({}).strict(),Lg=e.object({host_id:e.string(),host:re,server_url:e.string().url(),connect_token:e.string().min(1),daemon_command:e.string().min(1)}),jg=e.object({host_id:e.string().min(1)}),Ng=e.object({host:re}),Fg=e.object({host_id:e.string(),deleted:e.literal(!0)});var El=e.object({agents:e.number().int().nonnegative(),workspaces:e.number().int().nonnegative()}),zg=e.object({error:e.string(),error_code:e.literal("has_dependents"),dependents:El}),$g=e.object({host:re}),Cl=e.object({host_id:e.string(),host:re,host_token:e.string().min(1)}),Al=e.object({host_id:e.string(),host:re,status:e.literal("rotated")}),Tl=e.object({host_id:e.string(),host:re,status:e.literal("rotated"),connect_token:e.string().min(1),daemon_command:e.string().min(1)}),Hg=e.object({host_id:e.string(),host:re,disconnected:e.boolean()}),Ug=e.union([Cl,Al,Tl]);var Pt=e.object({id:e.string(),name:e.string(),display_name:e.string(),avatar_url:e.string().nullable(),created_at:e.number(),updated_at:e.number()}),Bg=e.object({users:e.array(Pt)}),Pl=e.object({registration_required:e.literal(!0),suggested_name:e.string()}),Vg=e.union([Pt,Pl]),Ol=/[\x00-\x1F\x7F-\x9F\u2028\u2029]/,Il="display_name must not contain control characters or Unicode line separators",Ot=e.string().trim().min(1).max(64).refine(n=>!Ol.test(n),{message:Il}),co=e.string().trim().email().max(320),Gg=e.object({email:co,password:e.string().min(8).max(1024),display_name:Ot.optional()}),Kg=e.object({email:co,password:e.string().min(1).max(1024)}),Zg=e.object({user_token:e.string().min(1),user:Pt}),Yg=e.object({ok:e.literal(!0)}),Jg=e.object({display_name:Ot.optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),Xg=e.object({avatar_url:e.string()});var Ml=e.enum(["loopback","lan","public"]),t_=e.object({signup_enabled:e.boolean(),bind_address_scope:Ml.optional()});var lo={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:[]}},Dl=["claude","codex","qoder","cursor","gemini"],s_=Dl.map(n=>lo[n]);function uo(n,t){return t==null?!0:lo[n].reasoningEffortOptions.includes(t)}var mo=e.object({id:e.string(),name:e.string(),display_name:e.string(),runtime:F,model:e.string().nullable(),reasoning_effort:lt.nullable(),fast_mode:nn.nullable(),host_id:e.string(),description:e.string().nullable(),created_by_user_id:e.string(),avatar_url:e.string().nullable(),materialization_status:ro,materialization_failed_code:e.string().nullable(),materialization_failed_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),d_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),runtime:F,model:e.string().optional(),reasoning_effort:lt.optional(),fast_mode:nn.optional(),host_id:e.string().optional(),description:e.string().optional()}).superRefine((n,t)=>{uo(n.runtime,n.reasoning_effort)||t.addIssue({code:e.ZodIssueCode.custom,path:["reasoning_effort"],message:`reasoning_effort '${n.reasoning_effort}' is not valid for runtime '${n.runtime}'`})}),u_=e.object({display_name:Ot.optional(),description:e.string().max(2e3).nullable().optional(),runtime:e.never().optional(),model:e.string().nullable().optional(),reasoning_effort:lt.nullable().optional(),fast_mode:nn.nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),m_=e.object({id:e.string(),name:e.string(),display_name:e.string(),description:e.string().nullable(),avatar_url:e.string().nullable()}),po=e.object({display_name:Ot.optional(),description:e.string().max(2e3).nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),p_=e.object({agent_id:e.string()}),Ll=e.object({path:e.string().min(1),kind:e.enum(["file","directory"]),size:e.number(),mtime:e.number()}).strict(),ho=e.object({nodes:e.array(Ll)}).strict(),fo=e.object({path:e.string().min(1),content:e.string(),size:e.number(),mtime:e.number(),truncated:e.boolean()}).strict(),go=e.object({conversation_id:e.string(),workspace_id:e.string(),workspace_name:e.string(),workspace_kind:ne,conversation_kind:V,channel_id:e.string(),channel_title:e.string(),status:sn,pid:e.number().nullable(),closed_at:e.number().nullable()}),h_=e.object({conversation_agents:e.array(go)}),f_=e.object({agent_id:e.string(),agent_name:e.string(),agent_display_name:e.string(),dm_channel:e.object({id:e.string(),name:e.string(),conversation_count:e.number(),message_count:e.number()}).nullable(),regular_workspaces:e.array(e.object({id:e.string(),name:e.string()})),regular_memberships:e.array(e.object({id:e.string(),name:e.string()})),owned_home:e.object({id:e.string(),name:e.string(),workspace_kind:ne,owner_agent_id:e.string().nullable()}).nullable(),attachments_count:e.number(),running_conversation_agents:e.array(go),pending_inbox_count:e.number()}),g_=e.object({confirm:e.literal(!0)});var x_=e.object({id:e.string(),name:e.string(),description:e.string().nullable(),workspace_kind:ne,workspace_path:e.string(),workspace_host_id:e.string(),owner_agent_id:e.string().nullable(),owner_user_id:e.string().nullable(),dm_channel_id:e.string().nullable(),dm_channel_ids:e.array(e.string()),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),k_=e.object({workspace_id:e.string(),agent_id:e.string(),joined_at:e.number()}),cn=e.enum(["owner","admin","member"]),jl=e.object({workspace_id:e.string(),user_id:e.string(),joined_at:e.number(),role:cn}),_o=Pt.extend({workspace_id:e.string(),user_id:e.string(),joined_at:e.number(),role:cn}),It=e.enum(so),w_=e.object({workspace_id:e.string(),agent_id:e.string(),capabilities:e.array(It)}),R_=e.object({capabilities:e.array(It)}),E_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),description:e.string().optional(),workspace_path:e.string().optional(),workspace_host_id:e.string().optional(),member_agent_ids:e.array(e.string()).default([]),member_user_ids:e.array(e.string()).default([])}),C_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore").optional(),description:e.string().nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),A_=e.object({archived:e.boolean()}),Nl=e.object({agent_id:e.string()}),Fl=e.object({kind:e.literal("agent"),agent_id:e.string()}),zl=e.object({kind:e.literal("human"),user_id:e.string()}),T_=e.union([Fl,zl,Nl]),P_=e.object({role:cn}),O_=e.object({member:jl,human_member:_o}),I_=e.object({members:e.array(mo),human_members:e.array(_o),viewer_role:cn.nullable()});var yo=e.object({id:e.string(),workspace_id:e.string(),workspace_path:e.string(),kind:V,title:e.string(),status:eo,spawned_by_agent_id:e.string().nullable(),closed_at:e.number().nullable(),close_summary:e.string().nullable(),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),$l=yo.extend({kind:e.literal("channel")}),Hl=yo.extend({kind:e.literal("dm_channel")}),vo=e.string().trim().min(1).max(128),j_=e.object({title:vo,member_agent_ids:e.array(e.string()).default([]),member_user_ids:e.array(e.string()).optional()}),Ul=e.enum(["regular","dm"]),Wl=e.object({id:e.string(),kind:V,title:e.string(),workspace_id:e.string(),workspace_kind:Ul,workspace_path:e.string(),closed_at:e.number().nullable(),archived_at:e.number().nullable()}),N_=e.object({ref:Wl}),F_=e.object({conversation_id:e.string(),agent_id:e.string(),cli_session_id:e.string().nullable(),pid:e.number().nullable(),status:sn,joined_at:e.number()}),z_=e.object({conversation_id:e.string(),user_id:e.string(),joined_at:e.number()}),ql=e.object({kind:e.literal("agent"),agent_id:e.string(),name:e.string(),display_name:e.string(),runtime:F}),Bl=e.object({kind:e.literal("human"),user_id:e.string(),name:e.string(),display_name:e.string(),avatar_url:e.string().nullable()}),hr=e.discriminatedUnion("kind",[ql,Bl]),$_=e.object({members:e.array(hr)}),Vl=e.string().trim().regex(/^@?[a-zA-Z0-9_-]{1,64}$/,{message:"handle must be @optional alphanumeric / dash / underscore"}),Gl=e.discriminatedUnion("kind",[e.object({kind:e.literal("agent"),agent_id:e.string()}),e.object({kind:e.literal("human"),user_id:e.string()})]),Kl=e.object({handle:Vl}),H_=e.union([Gl,Kl]),U_=e.object({ok:e.literal(!0),prev_cli_session_id:e.string().nullable(),was_running:e.boolean()}),Zl=e.record(e.string(),e.unknown()).nullable(),Yl=e.object({id:e.number().int(),conversation_id:e.string(),agent_id:e.string().nullable(),kind:no,payload:Zl,created_at:e.number().int()}),W_=e.object({events:e.array(Yl),next_before_id:e.number().int().nullable()});var Jl=e.union([$l,Hl]),q_=e.object({archived:e.boolean()}),B_=e.object({title:vo}),V_=e.object({workspace_id:e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().optional()),since:e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional())}),Xl=e.object({channel:Jl,workspace:e.object({id:e.string(),name:e.string(),archived_at:e.number().nullable()})}),G_=e.object({channels:e.array(Xl)});var Ql=e.enum(["starting","thinking","tool_running","idle","failed"]),ed=e.enum(["replied","turn_ended","replaced","stopped","crashed","timeout","conversation_closed"]),dt=e.object({runId:e.string(),agentId:e.string(),conversationId:e.string(),status:Ql,startedAt:e.number(),updatedAt:e.number(),lastActivityAt:e.number(),terminalReason:ed.optional(),activitySnippet:e.string().optional(),toolCallCounts:e.record(e.string(),e.number()).optional(),compacting:e.boolean().optional(),compactingSince:e.number().optional(),compactionStale:e.boolean().optional(),detail:e.string().optional()});var J_=e.object({states:e.array(dt)}),X_=e.object({kind:F,installed:e.boolean(),binary:e.string().nullable(),version:e.string().nullable()});var ny=e.object({id:e.string(),channel_id:e.string(),source_conversation_id:e.string().nullable(),filename:e.string(),size:e.number(),content_type:e.string(),storage:oo,created_by_kind:ao,created_by_id:e.string(),created_at:e.number()}),td=/^(Image|File) #([1-9]\d{0,3})$/,bo=e.string().trim().regex(td,'label must be "Image #N" or "File #N"');var ln=e.object({id:e.string(),filename:e.string(),size:e.number(),content_type:e.string(),label:bo.optional()}),So=e.object({id:e.string().min(1),label:bo.optional()});var ry=e.union([e.object({storage:e.literal("local"),local_path:e.string(),filename:e.string(),content_type:e.string()}),e.object({storage:e.enum(["s3","oss"]),download_url:e.string(),filename:e.string(),content_type:e.string()})]);var xo=e.enum(["user","agent"]),dn=e.object({emoji:e.string(),count:e.number().int().positive(),viewer_reacted:e.boolean()}),nd=e.object({kind:xo,id:e.string(),display_name:e.string()}),ay=e.object({emoji:e.string(),reactors:e.array(nd)}),iy=e.object({emoji:e.string()}),cy=e.object({message_id:e.string().min(1),emoji:e.string()}),ly=e.object({message_id:e.string(),conversation_id:e.string(),thread_root_id:e.string().nullable(),emoji:e.string(),op:e.enum(["add","remove"]),reactor_kind:xo,reactor_id:e.string(),count:e.number().int().nonnegative()});var dy=new RegExp("^(?:\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");var be=e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().trim().optional()),un=e.array(e.union([e.string().min(1),So])).max(20).refine(n=>{let t=n.map(r=>typeof r=="string"?void 0:r.label).filter(r=>r!==void 0);return new Set(t).size===t.length},{message:"attachment labels must be unique within a message"}).optional();function mn(n){return n.content.trim().length>0||(n.attachment_ids?.length??0)>0}var fr=e.union([e.object({kind:e.literal("channel")}).strict(),e.object({kind:e.literal("thread"),message_id:e.string().min(1)}).strict()]),rd=e.literal("self"),gr=e.union([fr,rd]),by=e.enum(["unaffected","revised","obsolete","force_send"]),_r=e.enum(["unaffected","revised","force_send"]),Sy=e.object({content:e.string(),target:gr.optional(),reply_to_message_id:e.string().min(1).optional(),stream_key:e.string().min(1).optional(),seen_up_to_seq:e.number().int().nonnegative().optional(),stale_event_id:e.string().min(1).optional(),stale_resolution_reason:_r.optional(),freshness_bypass:e.boolean().optional(),attachment_ids:un}).refine(mn,{message:"message must include text or at least one attachment",path:["content"]}),xy=e.object({stale_event_id:e.string().min(1),resolution_reason:e.literal("obsolete")}),ky=e.object({message_id:e.string(),message_seq:e.number().int().positive(),thread_root_id:e.string().nullable()}),wy=e.object({title:e.string().min(1).max(128),context_summary:e.string().min(1),initial_prompt:e.string().min(1)}),Ry=e.object({root_message_id:e.string().min(1)}),Ey=e.object({thread_root_id:e.string(),changed:e.boolean()}),Cy=e.object({task_number:e.number().int().positive(),status:e.enum(["todo","in_progress","in_review"]),title:e.string(),assignee_name:e.string().nullable(),assignee_agent_id:e.string().nullable()}),ko=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional()),sd=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().positive().max(100).optional().default(50)),od=e.union([e.literal("self"),e.object({thread_root_id:e.string().min(1)}),e.object({conversation_id:e.string().min(1)})]),Ay=e.object({target:od.optional(),before_seq:ko,after_seq:ko,around_message_id:e.string().min(1).optional(),include_content:e.boolean().optional().default(!1),include_system:e.boolean().optional().default(!0),limit:sd}).refine(n=>[n.before_seq,n.after_seq,n.around_message_id].filter(t=>t!==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"]}),wo=e.object({id:e.string(),workspace_id:e.string(),conversation_id:e.string(),conversation_kind:V,channel_id:e.string(),seq:e.number(),created_at:e.number()}),Ro=e.object({kind:on,agent_id:e.string().nullable(),user_id:e.string().nullable(),display_name:e.string().nullable()}),ad=e.object({conversation_id:e.string(),conversation_kind:V,channel_id:e.string(),thread_root_id:e.string().nullable(),workspace_id:e.string(),title:e.string()}),id=e.object({message_ref:wo,sender:Ro,snippet:e.string(),metadata:e.record(e.unknown()).nullable(),attachments:e.array(ln).nullable(),reactions:e.array(dn).nullable(),content:e.string().optional()}),cd=e.union([e.object({type:e.literal("head")}),e.object({type:e.literal("before_seq"),seq:e.number()}),e.object({type:e.literal("after_seq"),seq:e.number()}),e.object({type:e.literal("around_message_id"),message_id:e.string()})]),Ty=e.object({target:ad,anchor:cd,limit:e.number(),include_content:e.boolean(),include_system:e.boolean(),messages:e.array(id),has_more_before:e.boolean(),has_more_after:e.boolean()}),ld=e.object({id:e.string(),name:e.string(),kind:ne,archived:e.boolean(),updated_at:e.number(),agent_dir:e.string()}),Py=e.object({workspaces:e.array(ld)}),Oy=e.object({workspace_id:e.string().min(1).optional()}),dd=e.object({id:e.string(),title:e.string(),kind:e.enum(["channel","dm_channel"]),archived:e.boolean(),updated_at:e.number()}),Iy=e.object({workspace_id:e.string(),channels:e.array(dd)}),Eo=e.enum(["current","workspace","channel"]),ud=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().positive().max(100).optional().default(50)),My=e.object({q:e.string().trim().min(1).max(200),scope:Eo.optional().default("current"),workspace_id:e.string().min(1).optional(),channel_id:be,include_system:e.boolean().optional().default(!0),limit:ud}).superRefine((n,t)=>{n.scope==="channel"!=!!n.channel_id&&t.addIssue({code:e.ZodIssueCode.custom,message:"channel_id is required only when scope is channel",path:["channel_id"]}),n.workspace_id&&n.scope!=="workspace"&&t.addIssue({code:e.ZodIssueCode.custom,message:"workspace_id is only valid with scope=workspace",path:["workspace_id"]})}),md=e.object({message_ref:wo,sender:Ro,excerpt:e.string(),match_offset:e.number().int().nonnegative()}),Dy=e.object({query:e.string(),scope:Eo,workspace_id:e.string().nullable(),channel_id:e.string().nullable(),include_system:e.boolean(),limit:e.number(),hits:e.array(md)}),Ly=e.object({noun:e.string().max(64).optional(),verb:e.string().max(64).optional(),flags_seen:e.array(e.string().max(64)).max(64).optional(),error_code:e.string().max(64).optional(),error_subkind:e.string().max(64).optional(),error_message:e.string().max(500).optional(),duration_ms:e.number().nonnegative().optional()}).strict(),jy=e.object({ok:e.literal(!0)}),Ny=e.object({enabled:e.boolean()}).strict(),Fy=e.object({conversationId:e.string(),enabled:e.boolean(),expiresAt:e.number().int().nullable(),daemonSynced:e.boolean().optional()}).strict();var ut=e.object({type:to,id:e.string(),name:e.string()}),Co=e.object({id:e.string(),title:e.string()}),pd=e.object({type:e.enum(["agent","user","system"]),id:e.string().nullable(),name:e.string()}),qy=e.object({message_id:e.string(),task_number:e.number(),workspace_id:e.string(),workspace_name:e.string(),channel_id:e.string(),channel_name:e.string(),thread_root_id:e.string().nullable(),conversation:Co,status:J,title:e.string(),assignee:ut.nullable(),creator:pd,created_at:e.number(),closed_at:e.number().nullable()}),By=e.object({workspace_id:e.string().optional(),conversation_id:e.string().optional(),status:e.array(J).optional(),task_number:e.array(e.coerce.number().int().positive()).optional(),assignee_id:e.string().optional(),limit:e.coerce.number().int().positive().max(500).optional()}),Vy=e.object({tasks:e.array(e.object({title:e.string().min(1).max(200),body:e.string().optional()})).min(1),target:fr.optional(),reply_to_message_id:e.string().min(1).optional()}),hd=e.enum(["conversation_not_found","conversation_closed","not_conversation_member","agent_not_found","reply_target_not_found"]),fd=e.object({tasks:e.array(e.object({message_id:e.string(),task_number:e.number(),title:e.string()}))}),gd=e.object({error:hd}),Gy=e.union([fd,gd]),Ky=e.object({task_numbers:e.array(e.number()).optional(),message_ids:e.array(e.string()).optional(),workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>(n.task_numbers?.length??0)+(n.message_ids?.length??0)>0,{message:"provide at least one of task_numbers or message_ids"}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),_d=e.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"]),yd=e.object({success:e.boolean(),task_number:e.number().optional(),message_id:e.string().optional(),reason:e.string().optional(),code:_d.optional(),capability:It.optional(),owner_conversation:Co.optional(),workspace_candidates:e.array(e.string()).optional()}),Zy=e.object({results:e.array(yd)}),Yy=e.object({task_number:e.number().int().positive(),workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),Jy=e.object({task_number:e.number().int().positive(),status:J,workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),vd=e.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"]),Xy=e.object({success:e.boolean(),reason:e.string().optional(),code:vd.optional(),capability:It.optional(),workspace_candidates:e.array(e.string()).optional()}),Qy=e.object({status:J}),ev=e.object({agent_id:e.string().optional()}),tv=e.object({kind:e.enum(["create","claim","unclaim","status"]),workspace_id:e.string(),channel_id:e.string(),thread_root_id:e.string().nullable(),conversation_id:e.string(),task_number:e.number(),message_id:e.string(),status:J,assignee:ut.nullable(),title:e.string(),closed_at:e.number().nullable()});function pn(n,t){if(!Number.isInteger(n)||n<0)throw new RangeError(`${t}: cannot decode ${n} \u2014 expected a non-negative integer seq`)}function bd(n){return pn(n,"MessageSeq"),n}function Sd(n){return pn(n,"TransportSeq"),n}function xd(n){return pn(n,"ReadSeq"),n}function kd(n){return pn(n,"ObservedSeq"),n}function wd(n){if(typeof n!="string"||n.length===0)throw new RangeError(`TransportEpoch: cannot decode ${JSON.stringify(n)} \u2014 expected a non-empty string`);return n}var hn=e.number().int().nonnegative(),Ue=hn.transform(bd),sv=hn.transform(Sd),ov=hn.transform(xd),av=hn.transform(kd),iv=e.string().min(1).transform(wd);var Rd=e.enum(["agent","human","system"]),Ed=e.object({kind:Rd,id:e.string()}),Cd=e.object({kind:e.enum(["agent","human"]),id:e.string()}),Ao=e.object({root_message_id:e.string(),root_author:Ed,root_preview:e.string(),root_created_at:e.number(),root_seq:Ue,reply_count:e.number().int().nonnegative(),last_reply_at:e.number(),last_reply_message_id:e.string(),repliers:e.array(Cd),replier_total:e.number().int().nonnegative(),viewer_following:e.boolean()}),To=Ao.omit({viewer_following:!0}),uv=e.object({threads:e.array(Ao),next_cursor:e.string().nullable()});var fn=e.object({id:e.string(),conversation_id:e.string(),from_kind:on,from_agent_id:e.string().nullable(),from_user_id:e.string().nullable(),content:e.string(),metadata:e.record(e.unknown()).nullable(),attachments:e.array(ln).nullable(),reactions:e.array(dn).nullable(),seq:Ue,created_at:e.number(),thread_root_id:e.string().nullable(),task_number:e.number().nullable(),task_status:J.nullable(),task_title:e.string().nullable(),task_workspace_id:e.string().nullable(),task_closed_at:e.number().nullable(),task_assignee:ut.nullable()}),Ad=e.object({root_id:e.string(),reply_count:e.number().int().nonnegative()}),Td=e.object({thread_root_reply_count:Ad.optional(),threads_list_entry:e.object({entry:To}).optional()}),Sv=e.object({message:fn,projections:Td.optional()}),Pd=e.object({reply_count:e.number().int().nonnegative(),last_reply_at:e.number(),repliers:e.array(e.object({kind:e.enum(["agent","human"]),id:e.string()})),replier_total:e.number().int().nonnegative()}),xv=e.object({messages:e.array(fn),reply_counts_by_root:e.record(e.string(),e.number().int().nonnegative()),reply_summaries_by_root:e.record(e.string(),Pd).optional(),has_more_before:e.boolean(),stream_head_seq:Ue,has_more_after:e.boolean()}),kv=e.object({thread_root_id:e.string(),viewer_following:e.boolean(),follower_agent_ids:e.array(e.string())}),wv=e.object({thread_root_id:e.string(),changed:e.boolean(),viewer_following:e.boolean()}),Rv=e.object({content:e.string(),attachment_ids:un,reply_to_message_id:e.string().min(1).optional(),as_task:e.boolean().optional()}).refine(mn,{message:"message must include text or at least one attachment",path:["content"]}),Po=e.object({unread_count:e.number().int().nonnegative(),first_unread_message_id:e.string().nullable(),first_unread_seq:Ue.nullable()}),Ev=e.object({mainline:Po,threads:e.record(e.string(),Po)}),Mo=e.object({conversation_id:e.string(),message_id:e.string(),seq:Ue,thread_root_id:e.string().nullable()}),Cv=e.object({by_conversation:e.record(e.string(),e.number()),latest_by_conversation:e.record(e.string(),Mo),total:e.number()}),Av=e.object({by_workspace:e.record(e.string(),e.number())}),Tv=e.object({conversation_id:e.string(),workspace_id:e.string(),conversation_unread_count:e.number(),workspace_unread_count:e.number(),latest_unread:Mo.nullable()}),Oo=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional()),Od=e.enum(["all","regular","dm"]),Id=e.enum(["all","mainline","thread"]),Md=e.enum(["recency_desc","seq_asc"]),Dd=e.object({q:e.string().trim().max(200).optional().default(""),scope:Od.optional().default("all"),stream:Id.optional().default("all"),workspace_id:be,conversation_id:be,thread_root_id:be,user_id:be,agent_id:be,from:Oo,to:Oo,order:Md.optional().default("recency_desc"),limit:e.coerce.number().int().positive().max(500).optional().default(80)}).refine(n=>!(n.user_id&&n.agent_id),{message:"user_id and agent_id cannot both be set",path:["user_id"]}).refine(n=>n.stream==="all"||!!n.conversation_id,{message:"stream filter requires conversation_id",path:["stream"]}).refine(n=>n.stream!=="thread"||!!n.thread_root_id,{message:"stream=thread requires thread_root_id",path:["thread_root_id"]}).refine(n=>n.order!=="seq_asc"||!!n.conversation_id,{message:"order=seq_asc requires conversation_id",path:["order"]}),yr=e.object({id:e.string(),name:e.string(),kind:e.enum(["regular","dm"])}),Io=e.object({id:e.string(),title:e.string(),kind:V,channel_id:e.string(),closed_at:e.number().nullable(),created_at:e.number()}),Ld=e.discriminatedUnion("type",[e.object({type:e.literal("workspace"),workspace:yr.extend({description:e.string().nullable(),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()})}),e.object({type:e.literal("conversation"),workspace:yr,conversation:Io}),e.object({type:e.literal("message"),workspace:yr,conversation:Io,message:fn,agent_name:e.string().nullable()})]),Pv=e.object({query:Dd,results:e.array(Ld),total:e.number(),truncated:e.boolean()}),Ov=e.object({id:e.string(),message:fn,workspace_id:e.string(),workspace_name:e.string(),conversation_id:e.string(),conversation_title:e.string(),channel_id:e.string(),agent_name:e.string().nullable(),saved_at:e.number()}),Iv=e.object({workspace_id:e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().optional()),since:e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional())});var Do=["all","mentions"];var Lv=e.object({conversation_id:e.string(),mode:e.enum(Do)}),jv=e.object({mode:e.enum(Do)}),jd=["directed","ambient"],Nd=["mention","agent_failed","unread"],Fd=e.object({kind:e.enum(["user","agent"]),id:e.string(),display_name:e.string(),avatar_url:e.string().nullable()}),zd=e.object({id:e.string(),kind:e.enum(Nd),salience:e.enum(jd),workspace_id:e.string(),conversation_id:e.string(),thread_root_id:e.string().nullable(),message_id:e.string().nullable(),notification_id:e.string().nullable(),conversation_kind:e.enum(["channel","dm_channel"]),title:e.string(),thread_root_preview:e.string().nullable(),preview:e.string().nullable(),preview_sender:Fd.nullable(),timestamp:e.number(),unread_count:e.number().int().nonnegative().nullable()}),Nv=e.object({items:e.array(zd)}),$d=e.discriminatedUnion("kind",[e.object({kind:e.literal("at_seq"),seq:e.number().int().nonnegative()}),e.object({kind:e.literal("stream_head")})]),Hd=e.discriminatedUnion("kind",[e.object({kind:e.literal("stream"),conversation_id:e.string().min(1),thread_root_id:e.string().min(1).nullable(),position:$d}),e.object({kind:e.literal("notification"),notification_id:e.string().min(1)})]),Fv=e.object({sources:e.array(Hd).min(1).max(1e3)}),zv=e.object({changed:e.boolean()});var Wv=e.object({id:e.string(),kind:io,user_id:e.string().nullable(),agent_id:e.string().nullable(),workspace_id:e.string().nullable(),conversation_id:e.string().nullable(),message_id:e.string().nullable(),thread_root_id:e.string().nullable().optional(),source_workspace_id:e.string().nullable(),source_conversation_id:e.string().nullable(),source_message_id:e.string().nullable(),payload:e.record(e.unknown()).nullable(),read_at:e.number().nullable(),created_at:e.number()}),qv=e.object({id:e.string().optional(),workspace_id:e.string().optional(),conversation_id:e.string().optional(),all:e.boolean().optional()}).refine(n=>!!(n.id||n.workspace_id||n.conversation_id||n.all),{message:"must specify id, workspace_id, conversation_id, or all"});var Gv=2160*60*60,Ud=60;var Wd=120,qd=500,Bd=e.enum(["pending","firing","done","cancelled","failed"]),Vd=e.object({kind:e.literal("once"),fire_at:e.number().int().positive()}),Lo=e.object({kind:e.literal("interval"),every_seconds:e.number().int().min(Ud),start_at:e.number().int().positive().optional()}),jo=e.object({kind:e.literal("cron"),expression:e.string().min(1).max(200),timezone:e.string().min(1).max(64)}),Gd=e.discriminatedUnion("kind",[Vd,Lo,jo]),vr=e.object({id:e.string(),owner_agent_id:e.string(),target_conversation_id:e.string(),target_label:e.string(),title:e.string(),message:e.string(),spec:Gd,next_fire_at:e.number(),status:Bd,fired_count:e.number(),last_fired_at:e.number().nullable(),max_occurrences:e.number().nullable(),until_at:e.number().nullable(),failure_reason:e.string().nullable(),cancelled_at:e.number().nullable(),last_failure_reason:e.string().nullable(),last_failure_at:e.number().nullable(),consecutive_failure_count:e.number(),created_at:e.number(),updated_at:e.number()}),Kd=e.object({kind:e.literal("once"),fire_at:e.number().int().positive().optional(),delay_seconds:e.number().int().positive().optional()}),Kv=e.object({title:e.string().trim().min(1).max(Wd),message:e.string().min(1).max(qd),target_conversation_id:e.string().optional(),spec:e.discriminatedUnion("kind",[Kd,Lo,jo]),until_at:e.number().int().positive().optional(),max_occurrences:e.number().int().positive().optional(),allow_unbounded:e.boolean().optional()}).superRefine((n,t)=>{n.spec.kind==="once"&&(n.until_at!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["until_at"],message:"until_at is not valid on a `once` schedule"}),n.max_occurrences!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["max_occurrences"],message:"max_occurrences is not valid on a `once` schedule"}),n.allow_unbounded!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["allow_unbounded"],message:"allow_unbounded is not valid on a `once` schedule"}),!!n.spec.fire_at==!!n.spec.delay_seconds&&t.addIssue({code:e.ZodIssueCode.custom,path:["spec","fire_at"],message:"once spec requires exactly one of fire_at or delay_seconds"}))}),Zd=e.enum(["pending","firing","active","done","cancelled","failed","all"]),Zv=e.object({status:Zd.optional(),limit:e.number().int().min(1).max(200).optional()}),Yv=e.object({schedule_id:e.string()}),Jv=e.object({schedule:vr}),Xv=e.object({schedules:e.array(vr)}),Qv=e.object({schedule:vr});var Yd=e.enum(["online","offline"]),Jd=e.object({user_id:e.string(),presence:Yd,last_seen_at:e.number().nullable()});var nb=e.object({users:e.array(Jd)});var No=e.enum(["recent","manual"]),Fo=e.enum(["starred","dm","regular","unstarred","favorites"]),br=e.string().refine(n=>n==="workspaces"||n==="favorites"||n.startsWith("channels:"),{message:"list_key must be 'workspaces', 'favorites', or 'channels:<ws_id>'"}),Xd=e.object({entity_id:e.string(),rank:e.number().nullable(),last_accessed_at:e.number().nullable(),starred_at:e.number().nullable()}),zo=e.object({list_key:e.string(),modes:e.record(No),entries:e.array(Xd)}),ob=e.object({list_key:br,group:Fo.optional(),mode:No}),ab=e.object({list_key:br,group:Fo,ordered_ids:e.array(e.string())}),ib=e.object({list_key:br,entity_id:e.string()});var Qd=e.enum(["workspace","dm"]),eu=e.object({kind:Qd,favorite_key:e.string(),entity_id:e.string(),workspace_id:e.string(),title:e.string(),icon_url:e.string().nullable(),runtime:F.nullable(),starred_at:e.number(),created_at:e.number(),unread_count:e.number().nullable()}),mb=e.object({items:e.array(eu),viewer_sort:zo});var C={agentSendConversationMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/send-message`,agentResolveStaleMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/stale-message-resolution`,agentCreateChannel:(n,t)=>`/internal/conversations/${n}/agents/${t}/create-channel`,agentReadHistory:(n,t)=>`/internal/conversations/${n}/agents/${t}/read-history`,agentFollowThread:(n,t)=>`/internal/conversations/${n}/agents/${t}/follow-thread`,agentUnfollowThread:(n,t)=>`/internal/conversations/${n}/agents/${t}/unfollow-thread`,agentListWorkspaces:(n,t)=>`/internal/conversations/${n}/agents/${t}/list-workspaces`,agentListChannels:(n,t)=>`/internal/conversations/${n}/agents/${t}/list-channels`,agentSearchMessages:(n,t)=>`/internal/conversations/${n}/agents/${t}/search-messages`,agentAddConversationMember:(n,t)=>`/internal/conversations/${n}/agents/${t}/members`,agentReactMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/react-message`,agentListConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks`,agentCreateConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/create`,agentClaimConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/claim`,agentUnclaimConversationTask:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/unclaim`,agentUpdateConversationTaskStatus:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/update-status`,agentScheduleCreate:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules`,agentScheduleList:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules/list`,agentScheduleCancel:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules/cancel`,agentUploadAttachment:(n,t)=>`/internal/conversations/${n}/agents/${t}/attachments`,agentLocateAttachment:(n,t,r)=>`/internal/conversations/${n}/agents/${t}/attachments/${r}/locate`,agentDownloadAttachment:(n,t,r)=>`/internal/conversations/${n}/agents/${t}/attachments/${r}/download`,agentUploadAvatar:(n,t)=>`/internal/conversations/${n}/agents/${t}/avatar`,agentDeleteAvatar:(n,t)=>`/internal/conversations/${n}/agents/${t}/avatar`,agentCliTrace:(n,t)=>`/internal/conversations/${n}/agents/${t}/cli-trace`,agentProfileMcpGet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp`,agentProfileMcpSet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp`,agentProfileMcpProbe:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp/probe`,agentProfileGet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile`,agentProfileUpdate:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile`};var tu=e.unknown().refine(n=>n!==void 0,{message:"field is required (opaque payload must be present)"}),gn=e.discriminatedUnion("kind",[e.object({kind:e.literal("session_init"),sessionId:e.string().min(1)}).strict(),e.object({kind:e.literal("thinking"),text:e.string()}).strict(),e.object({kind:e.literal("text"),text:e.string()}).strict(),e.object({kind:e.literal("tool_call"),name:e.string().min(1),input:tu,toolCallId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("tool_output"),name:e.string().min(1).optional(),toolCallId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("turn_end"),sessionId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("compaction_started")}).strict(),e.object({kind:e.literal("compaction_finished")}).strict(),e.object({kind:e.literal("error"),message:e.string(),code:e.string().optional(),fatal:e.boolean().optional()}).strict(),e.object({kind:e.literal("unknown"),raw:e.string()}).strict()]),nu=["session_init","thinking","text","tool_call","tool_output","turn_end","compaction_started","compaction_finished","error","unknown"],_n=e.enum(nu);var ru=e.enum(["embedded","remote"]),su=e.object({max_concurrent_per_parent:e.number().int().positive().nullable().default(null),spawn_cooldown_seconds:e.number().int().nonnegative().nullable().default(null),max_depth:e.literal(1).default(1)}),qb=e.object({mode:ru,url:e.string().url(),auth_token:e.string().min(16).optional(),event_ws_allowed_origins:e.array(e.string().url()).optional(),refresh_token:e.string().nullable().default(null),child_sessions:su.default({max_concurrent_per_parent:null,spawn_cooldown_seconds:null,max_depth:1})});var mt="authorization",Bb=e.object({server_url:e.string().url(),host_id:e.string().min(1),host_token:e.string().min(1),allow_insecure_remote:e.boolean().optional(),profile_version:e.number().int().nonnegative().optional()}).strict(),Sr="SILVERHAND_CONVERSATION_ID",xr="SILVERHAND_AGENT_ID",yn="SILVERHAND_SERVER_URL",kr="SILVERHAND_AUTH_TOKEN",$o="SILVERHAND_LAST_DELIVERED_SEQ_FILE",Ho="SILVERHAND_DAEMON_SOCKET";var ou=/^[A-Za-z0-9_-]{1,64}$/,au=e.object({type:e.literal("stdio").optional(),command:e.string().min(1),args:e.array(e.string()).optional(),env:e.record(e.string()).optional()}).strict(),iu=e.object({type:e.enum(["http","sse"]),url:e.string().url(),headers:e.record(e.string()).optional()}).strict(),cu=e.union([au,iu]),lu=e.object({mcpServers:e.record(cu).default({}).superRefine((n,t)=>{for(let r of Object.keys(n))ou.test(r)||t.addIssue({code:e.ZodIssueCode.custom,message:`invalid MCP server name "${r}": use 1-64 chars of [A-Za-z0-9_-]`,path:["mcpServers",r]})})}).strict(),du={mcpServers:{}};function Mt(n){let t=n.trim();if(t.length===0)return{ok:!0,config:du};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}}let s=lu.safeParse(r);if(!s.success){let o=s.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:s.data}}var uu=["parse","not_found","connect","initialize","tools"],mu=e.enum(uu),pu=e.object({name:e.string(),description:e.string().optional()}).strict(),vn=e.object({ok:e.boolean(),phase:mu,message:e.string().optional(),server_info:e.object({name:e.string().optional(),version:e.string().optional()}).strict().optional(),tools:e.array(pu).optional()}).strict(),Zb=e.object({server_name:e.string().min(1),include_tools:e.boolean().optional()}).strict();var Jb=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 Xb=Object.freeze(new Set(["html","htm","pdf","txt","log","md","markdown","json","csv","png","jpg","jpeg","gif","webp"]));var hu=1,rS=e.object({version:e.number().int().gte(hu),server_url:e.string().min(1),created_at:e.number().int().nonnegative(),updated_at:e.number().int().nonnegative()}),sS=e.object({server_url:e.string().min(1),updated_at:e.number().int().nonnegative()});var Uo=["task_create","task_claim","task_unclaim","task_status"];var fu=e.discriminatedUnion("kind",[e.object({kind:e.literal("user"),id:e.string().nullable(),name:e.string()}),e.object({kind:e.literal("agent"),id:e.string(),name:e.string()})]),Wo={actor_kind:e.enum(["user","agent","system"]),actor_id:e.string(),actor_name:e.string(),actor_display_name:e.string().nullable(),member_kind:e.enum(["human","agent"]),member_id:e.string(),member_name:e.string(),member_display_name:e.string().nullable()},gu=e.object({subtype:e.literal("conversation_member_added"),...Wo}),_u=e.object({subtype:e.literal("conversation_member_removed"),...Wo}),dS=e.discriminatedUnion("subtype",[gu,_u]);var uS=e.object({subtype:e.enum(Uo),task_number:e.number(),task_status:J,task_message_id:e.string(),task_title:e.string(),task_assignee:ut.nullable(),actor:fu});var mS=e.object({subtype:e.enum(Uo),task_number:e.number(),task_status:J});var pS=e.object({subtype:e.literal("session_cleared"),agent_id:e.string(),agent_name:e.string(),actor_user_id:e.string().nullable(),previous_cli_session_id_prefix:e.string().nullable(),was_running:e.boolean()});var hS=e.object({subtype:e.literal("schedule_fire"),schedule_id:e.string(),title:e.string().optional(),spec_kind:e.enum(["once","interval","cron"]),spec_summary:e.string().optional(),body:e.string().optional(),actual_fire_at:e.number(),planned_fire_at:e.number().nullable(),missed_count:e.number(),next_fire_at:e.number().nullable()});var yu=e.enum(["user","agent","system"]),fS=e.object({subtype:e.literal("thread_anchor"),quoted_message_id:e.string(),quoted_conversation_id:e.string(),quoted_channel_name:e.string(),quoted_content:e.string(),quoted_from_kind:yu,quoted_from_agent_id:e.string().nullable(),quoted_from_user_id:e.string().nullable(),quoted_agent_name:e.string().nullable(),quoted_created_at:e.number()});var gS=e.object({subtype:e.literal("child_context"),parent_conversation_id:e.string(),parent_title:e.string(),summary:e.string()});var _S=e.object({subtype:e.literal("channel_context"),source_conversation_id:e.string(),source_conversation_title:e.string().optional(),created_by_agent_id:e.string(),created_by_agent_name:e.string().optional()});var yS=e.object({subtype:e.literal("rename"),old_name:e.string(),new_name:e.string(),scope:e.enum(["workspace","conversation"]).default("workspace")});import{readFile as Au}from"node:fs/promises";import{basename as Tu,isAbsolute as Pu}from"node:path";var vu=["not_found","forbidden","capability_denied","unauthorized","validation_error","conflict","rate_limited","upstream_unavailable","internal"],u=class extends Error{code;subkind;retriable;details;constructor(t){super(t.message),this.code=t.code,this.subkind=t.subkind,this.retriable=t.retriable,this.details=t.details}toPayload(){return{code:this.code,...this.subkind?{subkind:this.subkind}:{},message:this.message,retriable:this.retriable,...this.details?{details:this.details}:{}}}};function de(n,t){let r=ku(t);if(r?.code&&vu.includes(r.code)){let o=r.code;return new u({code:o,message:r.message??Ko(o),retriable:qo(o),...r.details?{details:r.details}:{}})}let s=Su(n);return new u({code:s,message:r?.message??xu(n,s),retriable:qo(s),...r?.details?{details:r.details}:{}})}function pt(n){let t=n instanceof Error?n.message:String(n);return new u({code:"upstream_unavailable",message:`cannot reach silverhand backend: ${t}`,retriable:!0})}function Bo(n){if(n instanceof u)return n;if(wu(n))return new u({code:"validation_error",message:Ru(n),retriable:!1});let t=n instanceof Error?n.message:String(n);return new u({code:"internal",message:`internal cli error: ${t}`,retriable:!1})}function Vo(n){switch(n){case"unauthorized":case"forbidden":case"capability_denied":return 3;case"rate_limited":case"upstream_unavailable":return 2;default:return 1}}function Go(n,t={json:!0}){let r=t.stderr??process.stderr;if(t.json){r.write(JSON.stringify({error:n.toPayload()})+`
|
|
9
|
+
`+r)}function Je(n,t,r,s,a,o){if(n.listenerCount("wsClientError")){let i=new Error(a);Error.captureStackTrace(i,Je),n.emit("wsClientError",i,r,t)}else Gt(r,s,a,o)}});import{performance as nc}from"node:perf_hooks";var Et="5 MB";var e={};lc(e,{BRAND:()=>jc,DIRTY:()=>Ee,EMPTY_PATH:()=>hc,INVALID:()=>b,NEVER:()=>bl,OK:()=>N,ParseStatus:()=>L,Schema:()=>k,ZodAny:()=>ye,ZodArray:()=>le,ZodBigInt:()=>Ae,ZodBoolean:()=>Te,ZodBranded:()=>At,ZodCatch:()=>$e,ZodDate:()=>Pe,ZodDefault:()=>ze,ZodDiscriminatedUnion:()=>Qt,ZodEffects:()=>B,ZodEnum:()=>Ne,ZodError:()=>z,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>tn,ZodIntersection:()=>De,ZodIssueCode:()=>p,ZodLazy:()=>Le,ZodLiteral:()=>je,ZodMap:()=>ot,ZodNaN:()=>ct,ZodNativeEnum:()=>Fe,ZodNever:()=>Y,ZodNull:()=>Ie,ZodNullable:()=>te,ZodNumber:()=>Ce,ZodObject:()=>$,ZodOptional:()=>W,ZodParsedType:()=>g,ZodPipeline:()=>Tt,ZodPromise:()=>ve,ZodReadonly:()=>He,ZodRecord:()=>en,ZodSchema:()=>k,ZodSet:()=>it,ZodString:()=>_e,ZodSymbol:()=>st,ZodTransformer:()=>B,ZodTuple:()=>ee,ZodType:()=>k,ZodUndefined:()=>Oe,ZodUnion:()=>Me,ZodUnknown:()=>ce,ZodVoid:()=>at,addIssueToContext:()=>f,any:()=>Bc,array:()=>Zc,bigint:()=>$c,boolean:()=>ea,coerce:()=>vl,custom:()=>Js,date:()=>Hc,datetimeRegex:()=>Zs,defaultErrorMap:()=>oe,discriminatedUnion:()=>Qc,effect:()=>ul,enum:()=>cl,function:()=>al,getErrorMap:()=>tt,getParsedType:()=>Q,instanceof:()=>Fc,intersection:()=>el,isAborted:()=>Jt,isAsync:()=>nt,isDirty:()=>Xt,isValid:()=>ge,late:()=>Nc,lazy:()=>ol,literal:()=>il,makeIssue:()=>Ct,map:()=>rl,nan:()=>zc,nativeEnum:()=>ll,never:()=>Gc,null:()=>qc,nullable:()=>pl,number:()=>Qs,object:()=>Yc,objectUtil:()=>mr,oboolean:()=>yl,onumber:()=>_l,optional:()=>ml,ostring:()=>gl,pipeline:()=>fl,preprocess:()=>hl,promise:()=>dl,quotelessJson:()=>uc,record:()=>nl,set:()=>sl,setErrorMap:()=>pc,strictObject:()=>Jc,string:()=>Xs,symbol:()=>Uc,transformer:()=>ul,tuple:()=>tl,undefined:()=>Wc,union:()=>Xc,unknown:()=>Vc,util:()=>w,void:()=>Kc});var w;(function(n){n.assertEqual=a=>{};function t(a){}n.assertIs=t;function r(a){throw new Error}n.assertNever=r,n.arrayToEnum=a=>{let o={};for(let i of a)o[i]=i;return o},n.getValidEnumValues=a=>{let o=n.objectKeys(a).filter(c=>typeof a[a[c]]!="number"),i={};for(let c of o)i[c]=a[c];return n.objectValues(i)},n.objectValues=a=>n.objectKeys(a).map(function(o){return a[o]}),n.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let o=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&o.push(i);return o},n.find=(a,o)=>{for(let i of a)if(o(i))return i},n.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,o=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}n.joinValues=s,n.jsonStringifyReplacer=(a,o)=>typeof o=="bigint"?o.toString():o})(w||(w={}));var mr;(function(n){n.mergeShapes=(t,r)=>({...t,...r})})(mr||(mr={}));var g=w.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Q=n=>{switch(typeof n){case"undefined":return g.undefined;case"string":return g.string;case"number":return Number.isNaN(n)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":return Array.isArray(n)?g.array:n===null?g.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?g.promise:typeof Map<"u"&&n instanceof Map?g.map:typeof Set<"u"&&n instanceof Set?g.set:typeof Date<"u"&&n instanceof Date?g.date:g.object;default:return g.unknown}};var p=w.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"]),uc=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),z=class n extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},s={_errors:[]},a=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(r(i));else{let c=s,d=0;for(;d<i.path.length;){let l=i.path[d];d===i.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(i))):c[l]=c[l]||{_errors:[]},c=c[l],d++}}};return a(this),s}static assert(t){if(!(t instanceof n))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,w.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},s=[];for(let a of this.issues)if(a.path.length>0){let o=a.path[0];r[o]=r[o]||[],r[o].push(t(a))}else s.push(t(a));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};z.create=n=>new z(n);var mc=(n,t)=>{let r;switch(n.code){case p.invalid_type:n.received===g.undefined?r="Required":r=`Expected ${n.expected}, received ${n.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(n.expected,w.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${w.joinValues(n.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${w.joinValues(n.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${w.joinValues(n.options)}, received '${n.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(r=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?r=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?r=`Invalid input: must end with "${n.validation.endsWith}"`:w.assertNever(n.validation):n.validation!=="regex"?r=`Invalid ${n.validation}`:r="Invalid";break;case p.too_small:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?r=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:r="Invalid input";break;case p.too_big:n.type==="array"?r=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?r=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?r=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?r=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?r=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:r="Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${n.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,w.assertNever(n)}return{message:r}},oe=mc;var qs=oe;function pc(n){qs=n}function tt(){return qs}var Ct=n=>{let{data:t,path:r,errorMaps:s,issueData:a}=n,o=[...r,...a.path||[]],i={...a,path:o};if(a.message!==void 0)return{...a,path:o,message:a.message};let c="",d=s.filter(l=>!!l).slice().reverse();for(let l of d)c=l(i,{data:t,defaultError:c}).message;return{...a,path:o,message:c}},hc=[];function f(n,t){let r=tt(),s=Ct({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,r,r===oe?void 0:oe].filter(a=>!!a)});n.common.issues.push(s)}var L=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let s=[];for(let a of r){if(a.status==="aborted")return b;a.status==="dirty"&&t.dirty(),s.push(a.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,r){let s=[];for(let a of r){let o=await a.key,i=await a.value;s.push({key:o,value:i})}return n.mergeObjectSync(t,s)}static mergeObjectSync(t,r){let s={};for(let a of r){let{key:o,value:i}=a;if(o.status==="aborted"||i.status==="aborted")return b;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[o.value]=i.value)}return{status:t.value,value:s}}},b=Object.freeze({status:"aborted"}),Ee=n=>({status:"dirty",value:n}),N=n=>({status:"valid",value:n}),Jt=n=>n.status==="aborted",Xt=n=>n.status==="dirty",ge=n=>n.status==="valid",nt=n=>typeof Promise<"u"&&n instanceof Promise;var _;(function(n){n.errToObj=t=>typeof t=="string"?{message:t}:t||{},n.toString=t=>typeof t=="string"?t:t?.message})(_||(_={}));var q=class{constructor(t,r,s,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=s,this._key=a}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}},Bs=(n,t)=>{if(ge(t))return{success:!0,data:t.value};if(!n.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 z(n.common.issues);return this._error=r,this._error}}};function x(n){if(!n)return{};let{errorMap:t,invalid_type_error:r,required_error:s,description:a}=n;if(t&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(i,c)=>{let{message:d}=n;return i.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:d??s??c.defaultError}:i.code!=="invalid_type"?{message:c.defaultError}:{message:d??r??c.defaultError}},description:a}}var k=class{get description(){return this._def.description}_getType(t){return Q(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Q(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:Q(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(nt(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let s=this.safeParse(t,r);if(s.success)return s.data;throw s.error}safeParse(t,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)},a=this._parseSync({data:t,path:s.path,parent:s});return Bs(s,a)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:r});return ge(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(s=>ge(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(t,r){let s=await this.safeParseAsync(t,r);if(s.success)return s.data;throw s.error}async safeParseAsync(t,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Q(t)},a=this._parse({data:t,path:s.path,parent:s}),o=await(nt(a)?a:Promise.resolve(a));return Bs(s,o)}refine(t,r){let s=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,o)=>{let i=t(a),c=()=>o.addIssue({code:p.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(c(),!1)):i?!0:(c(),!1)})}refinement(t,r){return this._refinement((s,a)=>t(s)?!0:(a.addIssue(typeof r=="function"?r(s,a):r),!1))}_refinement(t){return new B({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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 W.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return le.create(this)}promise(){return ve.create(this,this._def)}or(t){return Me.create([this,t],this._def)}and(t){return De.create(this,t,this._def)}transform(t){return new B({...x(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new ze({...x(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new At({typeName:S.ZodBranded,type:this,...x(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new $e({...x(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Tt.create(this,t)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},fc=/^c[^\s-]{8,}$/i,gc=/^[0-9a-z]+$/,_c=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yc=/^[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,vc=/^[a-z0-9_-]{21}$/i,bc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sc=/^[-+]?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)?)??$/,xc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pr,wc=/^(?:(?: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])$/,Rc=/^(?:(?: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])$/,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]))$/,Cc=/^(([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])$/,Ac=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gs="((\\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])))",Pc=new RegExp(`^${Gs}$`);function Ks(n){let t="[0-5]\\d";n.precision?t=`${t}\\.\\d{${n.precision}}`:n.precision==null&&(t=`${t}(\\.\\d+)?`);let r=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Oc(n){return new RegExp(`^${Ks(n)}$`)}function Zs(n){let t=`${Gs}T${Ks(n)}`,r=[];return r.push(n.local?"Z?":"Z"),n.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Ic(n,t){return!!((t==="v4"||!t)&&wc.test(n)||(t==="v6"||!t)&&Ec.test(n))}function Mc(n,t){if(!bc.test(n))return!1;try{let[r]=n.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(s));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function Dc(n,t){return!!((t==="v4"||!t)&&Rc.test(n)||(t==="v6"||!t)&&Cc.test(n))}var _e=class n extends k{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==g.string){let o=this._getOrReturnCtx(t);return f(o,{code:p.invalid_type,expected:g.string,received:o.parsedType}),b}let s=new L,a;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(a=this._getOrReturnCtx(t,a),f(a,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="max")t.data.length>o.value&&(a=this._getOrReturnCtx(t,a),f(a,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,c=t.data.length<o.value;(i||c)&&(a=this._getOrReturnCtx(t,a),i?f(a,{code:p.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&f(a,{code:p.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),s.dirty())}else if(o.kind==="email")xc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"email",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="emoji")pr||(pr=new RegExp(kc,"u")),pr.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"emoji",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="uuid")yc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"uuid",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="nanoid")vc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"nanoid",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid")fc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"cuid",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid2")gc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"cuid2",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="ulid")_c.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"ulid",code:p.invalid_string,message:o.message}),s.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),f(a,{validation:"url",code:p.invalid_string,message:o.message}),s.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"regex",code:p.invalid_string,message:o.message}),s.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),s.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:{startsWith:o.value},message:o.message}),s.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:{endsWith:o.value},message:o.message}),s.dirty()):o.kind==="datetime"?Zs(o).test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:"datetime",message:o.message}),s.dirty()):o.kind==="date"?Pc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:"date",message:o.message}),s.dirty()):o.kind==="time"?Oc(o).test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{code:p.invalid_string,validation:"time",message:o.message}),s.dirty()):o.kind==="duration"?Sc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"duration",code:p.invalid_string,message:o.message}),s.dirty()):o.kind==="ip"?Ic(t.data,o.version)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"ip",code:p.invalid_string,message:o.message}),s.dirty()):o.kind==="jwt"?Mc(t.data,o.alg)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"jwt",code:p.invalid_string,message:o.message}),s.dirty()):o.kind==="cidr"?Dc(t.data,o.version)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"cidr",code:p.invalid_string,message:o.message}),s.dirty()):o.kind==="base64"?Ac.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"base64",code:p.invalid_string,message:o.message}),s.dirty()):o.kind==="base64url"?Tc.test(t.data)||(a=this._getOrReturnCtx(t,a),f(a,{validation:"base64url",code:p.invalid_string,message:o.message}),s.dirty()):w.assertNever(o);return{status:s.value,value:t.data}}_regex(t,r,s){return this.refinement(a=>t.test(a),{validation:r,code:p.invalid_string,..._.errToObj(s)})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",..._.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",..._.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",..._.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,..._.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,..._.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",..._.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,..._.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,..._.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,..._.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,..._.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,..._.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,..._.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,..._.errToObj(r)})}nonempty(t){return this.min(1,_.errToObj(t))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};_e.create=n=>new _e({checks:[],typeName:S.ZodString,coerce:n?.coerce??!1,...x(n)});function Lc(n,t){let r=(n.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,a=r>s?r:s,o=Number.parseInt(n.toFixed(a).replace(".","")),i=Number.parseInt(t.toFixed(a).replace(".",""));return o%i/10**a}var Ce=class n extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==g.number){let o=this._getOrReturnCtx(t);return f(o,{code:p.invalid_type,expected:g.number,received:o.parsedType}),b}let s,a=new L;for(let o of this._def.checks)o.kind==="int"?w.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),f(s,{code:p.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="multipleOf"?Lc(t.data,o.value)!==0&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_finite,message:o.message}),a.dirty()):w.assertNever(o);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,_.toString(r))}gt(t,r){return this.setLimit("min",t,!1,_.toString(r))}lte(t,r){return this.setLimit("max",t,!0,_.toString(r))}lt(t,r){return this.setLimit("max",t,!1,_.toString(r))}setLimit(t,r,s,a){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:s,message:_.toString(a)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:_.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&w.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Ce.create=n=>new Ce({checks:[],typeName:S.ZodNumber,coerce:n?.coerce||!1,...x(n)});var Ae=class n extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==g.bigint)return this._getInvalidInput(t);let s,a=new L;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),f(s,{code:p.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):w.assertNever(o);return{status:a.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return f(r,{code:p.invalid_type,expected:g.bigint,received:r.parsedType}),b}gte(t,r){return this.setLimit("min",t,!0,_.toString(r))}gt(t,r){return this.setLimit("min",t,!1,_.toString(r))}lte(t,r){return this.setLimit("max",t,!0,_.toString(r))}lt(t,r){return this.setLimit("max",t,!1,_.toString(r))}setLimit(t,r,s,a){return new n({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:s,message:_.toString(a)}]})}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Ae.create=n=>new Ae({checks:[],typeName:S.ZodBigInt,coerce:n?.coerce??!1,...x(n)});var Te=class extends k{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==g.boolean){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.boolean,received:s.parsedType}),b}return N(t.data)}};Te.create=n=>new Te({typeName:S.ZodBoolean,coerce:n?.coerce||!1,...x(n)});var Pe=class n extends k{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==g.date){let o=this._getOrReturnCtx(t);return f(o,{code:p.invalid_type,expected:g.date,received:o.parsedType}),b}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return f(o,{code:p.invalid_date}),b}let s=new L,a;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(a=this._getOrReturnCtx(t,a),f(a,{code:p.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),s.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(a=this._getOrReturnCtx(t,a),f(a,{code:p.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),s.dirty()):w.assertNever(o);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new n({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:_.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:_.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Pe.create=n=>new Pe({checks:[],coerce:n?.coerce||!1,typeName:S.ZodDate,...x(n)});var st=class extends k{_parse(t){if(this._getType(t)!==g.symbol){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.symbol,received:s.parsedType}),b}return N(t.data)}};st.create=n=>new st({typeName:S.ZodSymbol,...x(n)});var Oe=class extends k{_parse(t){if(this._getType(t)!==g.undefined){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.undefined,received:s.parsedType}),b}return N(t.data)}};Oe.create=n=>new Oe({typeName:S.ZodUndefined,...x(n)});var Ie=class extends k{_parse(t){if(this._getType(t)!==g.null){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.null,received:s.parsedType}),b}return N(t.data)}};Ie.create=n=>new Ie({typeName:S.ZodNull,...x(n)});var ye=class extends k{constructor(){super(...arguments),this._any=!0}_parse(t){return N(t.data)}};ye.create=n=>new ye({typeName:S.ZodAny,...x(n)});var ce=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(t){return N(t.data)}};ce.create=n=>new ce({typeName:S.ZodUnknown,...x(n)});var Y=class extends k{_parse(t){let r=this._getOrReturnCtx(t);return f(r,{code:p.invalid_type,expected:g.never,received:r.parsedType}),b}};Y.create=n=>new Y({typeName:S.ZodNever,...x(n)});var at=class extends k{_parse(t){if(this._getType(t)!==g.undefined){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.void,received:s.parsedType}),b}return N(t.data)}};at.create=n=>new at({typeName:S.ZodVoid,...x(n)});var le=class n extends k{_parse(t){let{ctx:r,status:s}=this._processInputParams(t),a=this._def;if(r.parsedType!==g.array)return f(r,{code:p.invalid_type,expected:g.array,received:r.parsedType}),b;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,c=r.data.length<a.exactLength.value;(i||c)&&(f(r,{code:i?p.too_big:p.too_small,minimum:c?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(f(r,{code:p.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(f(r,{code:p.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((i,c)=>a.type._parseAsync(new q(r,i,r.path,c)))).then(i=>L.mergeArray(s,i));let o=[...r.data].map((i,c)=>a.type._parseSync(new q(r,i,r.path,c)));return L.mergeArray(s,o)}get element(){return this._def.type}min(t,r){return new n({...this._def,minLength:{value:t,message:_.toString(r)}})}max(t,r){return new n({...this._def,maxLength:{value:t,message:_.toString(r)}})}length(t,r){return new n({...this._def,exactLength:{value:t,message:_.toString(r)}})}nonempty(t){return this.min(1,t)}};le.create=(n,t)=>new le({type:n,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...x(t)});function rt(n){if(n instanceof $){let t={};for(let r in n.shape){let s=n.shape[r];t[r]=W.create(rt(s))}return new $({...n._def,shape:()=>t})}else return n instanceof le?new le({...n._def,type:rt(n.element)}):n instanceof W?W.create(rt(n.unwrap())):n instanceof te?te.create(rt(n.unwrap())):n instanceof ee?ee.create(n.items.map(t=>rt(t))):n}var $=class n extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=w.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==g.object){let l=this._getOrReturnCtx(t);return f(l,{code:p.invalid_type,expected:g.object,received:l.parsedType}),b}let{status:s,ctx:a}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof Y&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||c.push(l);let d=[];for(let l of i){let m=o[l],h=a.data[l];d.push({key:{status:"valid",value:l},value:m._parse(new q(a,h,a.path,l)),alwaysSet:l in a.data})}if(this._def.catchall instanceof Y){let l=this._def.unknownKeys;if(l==="passthrough")for(let m of c)d.push({key:{status:"valid",value:m},value:{status:"valid",value:a.data[m]}});else if(l==="strict")c.length>0&&(f(a,{code:p.unrecognized_keys,keys:c}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let m of c){let h=a.data[m];d.push({key:{status:"valid",value:m},value:l._parse(new q(a,h,a.path,m)),alwaysSet:m in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let m of d){let h=await m.key,v=await m.value;l.push({key:h,value:v,alwaysSet:m.alwaysSet})}return l}).then(l=>L.mergeObjectSync(s,l)):L.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(t){return _.errToObj,new n({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,s)=>{let a=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:_.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(t){return new n({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new n({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:S.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new n({...this._def,catchall:t})}pick(t){let r={};for(let s of w.objectKeys(t))t[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new n({...this._def,shape:()=>r})}omit(t){let r={};for(let s of w.objectKeys(this.shape))t[s]||(r[s]=this.shape[s]);return new n({...this._def,shape:()=>r})}deepPartial(){return rt(this)}partial(t){let r={};for(let s of w.objectKeys(this.shape)){let a=this.shape[s];t&&!t[s]?r[s]=a:r[s]=a.optional()}return new n({...this._def,shape:()=>r})}required(t){let r={};for(let s of w.objectKeys(this.shape))if(t&&!t[s])r[s]=this.shape[s];else{let o=this.shape[s];for(;o instanceof W;)o=o._def.innerType;r[s]=o}return new n({...this._def,shape:()=>r})}keyof(){return Ys(w.objectKeys(this.shape))}};$.create=(n,t)=>new $({shape:()=>n,unknownKeys:"strip",catchall:Y.create(),typeName:S.ZodObject,...x(t)});$.strictCreate=(n,t)=>new $({shape:()=>n,unknownKeys:"strict",catchall:Y.create(),typeName:S.ZodObject,...x(t)});$.lazycreate=(n,t)=>new $({shape:n,unknownKeys:"strip",catchall:Y.create(),typeName:S.ZodObject,...x(t)});var Me=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=this._def.options;function a(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let i=o.map(c=>new z(c.ctx.common.issues));return f(r,{code:p.invalid_union,unionErrors:i}),b}if(r.common.async)return Promise.all(s.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let o,i=[];for(let d of s){let l={...r,common:{...r.common,issues:[]},parent:null},m=d._parseSync({data:r.data,path:r.path,parent:l});if(m.status==="valid")return m;m.status==="dirty"&&!o&&(o={result:m,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let c=i.map(d=>new z(d));return f(r,{code:p.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}};Me.create=(n,t)=>new Me({options:n,typeName:S.ZodUnion,...x(t)});var ie=n=>n instanceof Le?ie(n.schema):n instanceof B?ie(n.innerType()):n instanceof je?[n.value]:n instanceof Ne?n.options:n instanceof Fe?w.objectValues(n.enum):n instanceof ze?ie(n._def.innerType):n instanceof Oe?[void 0]:n instanceof Ie?[null]:n instanceof W?[void 0,...ie(n.unwrap())]:n instanceof te?[null,...ie(n.unwrap())]:n instanceof At||n instanceof He?ie(n.unwrap()):n instanceof $e?ie(n._def.innerType):[],Qt=class n extends k{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.object)return f(r,{code:p.invalid_type,expected:g.object,received:r.parsedType}),b;let s=this.discriminator,a=r.data[s],o=this.optionsMap.get(a);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(f(r,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,s){let a=new Map;for(let o of r){let i=ie(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of i){if(a.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);a.set(c,o)}}return new n({typeName:S.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:a,...x(s)})}};function hr(n,t){let r=Q(n),s=Q(t);if(n===t)return{valid:!0,data:n};if(r===g.object&&s===g.object){let a=w.objectKeys(t),o=w.objectKeys(n).filter(c=>a.indexOf(c)!==-1),i={...n,...t};for(let c of o){let d=hr(n[c],t[c]);if(!d.valid)return{valid:!1};i[c]=d.data}return{valid:!0,data:i}}else if(r===g.array&&s===g.array){if(n.length!==t.length)return{valid:!1};let a=[];for(let o=0;o<n.length;o++){let i=n[o],c=t[o],d=hr(i,c);if(!d.valid)return{valid:!1};a.push(d.data)}return{valid:!0,data:a}}else return r===g.date&&s===g.date&&+n==+t?{valid:!0,data:n}:{valid:!1}}var De=class extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t),a=(o,i)=>{if(Jt(o)||Jt(i))return b;let c=hr(o.value,i.value);return c.valid?((Xt(o)||Xt(i))&&r.dirty(),{status:r.value,value:c.data}):(f(s,{code:p.invalid_intersection_types}),b)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([o,i])=>a(o,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};De.create=(n,t,r)=>new De({left:n,right:t,typeName:S.ZodIntersection,...x(r)});var ee=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.array)return f(s,{code:p.invalid_type,expected:g.array,received:s.parsedType}),b;if(s.data.length<this._def.items.length)return f(s,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&s.data.length>this._def.items.length&&(f(s,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...s.data].map((i,c)=>{let d=this._def.items[c]||this._def.rest;return d?d._parse(new q(s,i,s.path,c)):null}).filter(i=>!!i);return s.common.async?Promise.all(o).then(i=>L.mergeArray(r,i)):L.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new n({...this._def,rest:t})}};ee.create=(n,t)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:n,typeName:S.ZodTuple,rest:null,...x(t)})};var en=class n extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.object)return f(s,{code:p.invalid_type,expected:g.object,received:s.parsedType}),b;let a=[],o=this._def.keyType,i=this._def.valueType;for(let c in s.data)a.push({key:o._parse(new q(s,c,s.path,c)),value:i._parse(new q(s,s.data[c],s.path,c)),alwaysSet:c in s.data});return s.common.async?L.mergeObjectAsync(r,a):L.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(t,r,s){return r instanceof k?new n({keyType:t,valueType:r,typeName:S.ZodRecord,...x(s)}):new n({keyType:_e.create(),valueType:t,typeName:S.ZodRecord,...x(r)})}},ot=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.map)return f(s,{code:p.invalid_type,expected:g.map,received:s.parsedType}),b;let a=this._def.keyType,o=this._def.valueType,i=[...s.data.entries()].map(([c,d],l)=>({key:a._parse(new q(s,c,s.path,[l,"key"])),value:o._parse(new q(s,d,s.path,[l,"value"]))}));if(s.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let d of i){let l=await d.key,m=await d.value;if(l.status==="aborted"||m.status==="aborted")return b;(l.status==="dirty"||m.status==="dirty")&&r.dirty(),c.set(l.value,m.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let d of i){let l=d.key,m=d.value;if(l.status==="aborted"||m.status==="aborted")return b;(l.status==="dirty"||m.status==="dirty")&&r.dirty(),c.set(l.value,m.value)}return{status:r.value,value:c}}}};ot.create=(n,t,r)=>new ot({valueType:t,keyType:n,typeName:S.ZodMap,...x(r)});var it=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.parsedType!==g.set)return f(s,{code:p.invalid_type,expected:g.set,received:s.parsedType}),b;let a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(f(s,{code:p.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(f(s,{code:p.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());let o=this._def.valueType;function i(d){let l=new Set;for(let m of d){if(m.status==="aborted")return b;m.status==="dirty"&&r.dirty(),l.add(m.value)}return{status:r.value,value:l}}let c=[...s.data.values()].map((d,l)=>o._parse(new q(s,d,s.path,l)));return s.common.async?Promise.all(c).then(d=>i(d)):i(c)}min(t,r){return new n({...this._def,minSize:{value:t,message:_.toString(r)}})}max(t,r){return new n({...this._def,maxSize:{value:t,message:_.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};it.create=(n,t)=>new it({valueType:n,minSize:null,maxSize:null,typeName:S.ZodSet,...x(t)});var tn=class n extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.function)return f(r,{code:p.invalid_type,expected:g.function,received:r.parsedType}),b;function s(c,d){return Ct({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,tt(),oe].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:d}})}function a(c,d){return Ct({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,tt(),oe].filter(l=>!!l),issueData:{code:p.invalid_return_type,returnTypeError:d}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ve){let c=this;return N(async function(...d){let l=new z([]),m=await c._def.args.parseAsync(d,o).catch(R=>{throw l.addIssue(s(d,R)),l}),h=await Reflect.apply(i,this,m);return await c._def.returns._def.type.parseAsync(h,o).catch(R=>{throw l.addIssue(a(h,R)),l})})}else{let c=this;return N(function(...d){let l=c._def.args.safeParse(d,o);if(!l.success)throw new z([s(d,l.error)]);let m=Reflect.apply(i,this,l.data),h=c._def.returns.safeParse(m,o);if(!h.success)throw new z([a(m,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new n({...this._def,args:ee.create(t).rest(ce.create())})}returns(t){return new n({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,s){return new n({args:t||ee.create([]).rest(ce.create()),returns:r||ce.create(),typeName:S.ZodFunction,...x(s)})}},Le=class extends k{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Le.create=(n,t)=>new Le({getter:n,typeName:S.ZodLazy,...x(t)});var je=class extends k{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return f(r,{received:r.data,code:p.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:t.data}}get value(){return this._def.value}};je.create=(n,t)=>new je({value:n,typeName:S.ZodLiteral,...x(t)});function Ys(n,t){return new Ne({values:n,typeName:S.ZodEnum,...x(t)})}var Ne=class n extends k{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),s=this._def.values;return f(r,{expected:w.joinValues(s),received:r.parsedType,code:p.invalid_type}),b}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),s=this._def.values;return f(r,{received:r.data,code:p.invalid_enum_value,options:s}),b}return N(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return n.create(t,{...this._def,...r})}exclude(t,r=this._def){return n.create(this.options.filter(s=>!t.includes(s)),{...this._def,...r})}};Ne.create=Ys;var Fe=class extends k{_parse(t){let r=w.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==g.string&&s.parsedType!==g.number){let a=w.objectValues(r);return f(s,{expected:w.joinValues(a),received:s.parsedType,code:p.invalid_type}),b}if(this._cache||(this._cache=new Set(w.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let a=w.objectValues(r);return f(s,{received:s.data,code:p.invalid_enum_value,options:a}),b}return N(t.data)}get enum(){return this._def.values}};Fe.create=(n,t)=>new Fe({values:n,typeName:S.ZodNativeEnum,...x(t)});var ve=class extends k{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==g.promise&&r.common.async===!1)return f(r,{code:p.invalid_type,expected:g.promise,received:r.parsedType}),b;let s=r.parsedType===g.promise?r.data:Promise.resolve(r.data);return N(s.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ve.create=(n,t)=>new ve({type:n,typeName:S.ZodPromise,...x(t)});var B=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:s}=this._processInputParams(t),a=this._def.effect||null,o={addIssue:i=>{f(s,i),i.fatal?r.abort():r.dirty()},get path(){return s.path}};if(o.addIssue=o.addIssue.bind(o),a.type==="preprocess"){let i=a.transform(s.data,o);if(s.common.async)return Promise.resolve(i).then(async c=>{if(r.value==="aborted")return b;let d=await this._def.schema._parseAsync({data:c,path:s.path,parent:s});return d.status==="aborted"?b:d.status==="dirty"?Ee(d.value):r.value==="dirty"?Ee(d.value):d});{if(r.value==="aborted")return b;let c=this._def.schema._parseSync({data:i,path:s.path,parent:s});return c.status==="aborted"?b:c.status==="dirty"?Ee(c.value):r.value==="dirty"?Ee(c.value):c}}if(a.type==="refinement"){let i=c=>{let d=a.refinement(c,o);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(s.common.async===!1){let c=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?b:(c.status==="dirty"&&r.dirty(),i(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(c=>c.status==="aborted"?b:(c.status==="dirty"&&r.dirty(),i(c.value).then(()=>({status:r.value,value:c.value}))))}if(a.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ge(i))return b;let c=a.transform(i.value,o);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:s.data,path:s.path,parent:s}).then(i=>ge(i)?Promise.resolve(a.transform(i.value,o)).then(c=>({status:r.value,value:c})):b);w.assertNever(a)}};B.create=(n,t,r)=>new B({schema:n,typeName:S.ZodEffects,effect:t,...x(r)});B.createWithPreprocess=(n,t,r)=>new B({schema:t,effect:{type:"preprocess",transform:n},typeName:S.ZodEffects,...x(r)});var W=class extends k{_parse(t){return this._getType(t)===g.undefined?N(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};W.create=(n,t)=>new W({innerType:n,typeName:S.ZodOptional,...x(t)});var te=class extends k{_parse(t){return this._getType(t)===g.null?N(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};te.create=(n,t)=>new te({innerType:n,typeName:S.ZodNullable,...x(t)});var ze=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=r.data;return r.parsedType===g.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ze.create=(n,t)=>new ze({innerType:n,typeName:S.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...x(t)});var $e=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return nt(a)?a.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new z(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};$e.create=(n,t)=>new $e({innerType:n,typeName:S.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...x(t)});var ct=class extends k{_parse(t){if(this._getType(t)!==g.nan){let s=this._getOrReturnCtx(t);return f(s,{code:p.invalid_type,expected:g.nan,received:s.parsedType}),b}return{status:"valid",value:t.data}}};ct.create=n=>new ct({typeName:S.ZodNaN,...x(n)});var jc=Symbol("zod_brand"),At=class extends k{_parse(t){let{ctx:r}=this._processInputParams(t),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Tt=class n extends k{_parse(t){let{status:r,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?b:o.status==="dirty"?(r.dirty(),Ee(o.value)):this._def.out._parseAsync({data:o.value,path:s.path,parent:s})})();{let a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?b:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(t,r){return new n({in:t,out:r,typeName:S.ZodPipeline})}},He=class extends k{_parse(t){let r=this._def.innerType._parse(t),s=a=>(ge(a)&&(a.value=Object.freeze(a.value)),a);return nt(r)?r.then(a=>s(a)):s(r)}unwrap(){return this._def.innerType}};He.create=(n,t)=>new He({innerType:n,typeName:S.ZodReadonly,...x(t)});function Vs(n,t){let r=typeof n=="function"?n(t):typeof n=="string"?{message:n}:n;return typeof r=="string"?{message:r}:r}function Js(n,t={},r){return n?ye.create().superRefine((s,a)=>{let o=n(s);if(o instanceof Promise)return o.then(i=>{if(!i){let c=Vs(t,s),d=c.fatal??r??!0;a.addIssue({code:"custom",...c,fatal:d})}});if(!o){let i=Vs(t,s),c=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:c})}}):ye.create()}var Nc={object:$.lazycreate},S;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(S||(S={}));var Fc=(n,t={message:`Input not instance of ${n.name}`})=>Js(r=>r instanceof n,t),Xs=_e.create,Qs=Ce.create,zc=ct.create,$c=Ae.create,ea=Te.create,Hc=Pe.create,Uc=st.create,Wc=Oe.create,qc=Ie.create,Bc=ye.create,Vc=ce.create,Gc=Y.create,Kc=at.create,Zc=le.create,Yc=$.create,Jc=$.strictCreate,Xc=Me.create,Qc=Qt.create,el=De.create,tl=ee.create,nl=en.create,rl=ot.create,sl=it.create,al=tn.create,ol=Le.create,il=je.create,cl=Ne.create,ll=Fe.create,dl=ve.create,ul=B.create,ml=W.create,pl=te.create,hl=B.createWithPreprocess,fl=Tt.create,gl=()=>Xs().optional(),_l=()=>Qs().optional(),yl=()=>ea().optional(),vl={string:(n=>_e.create({...n,coerce:!0})),number:(n=>Ce.create({...n,coerce:!0})),boolean:(n=>Te.create({...n,coerce:!0})),bigint:(n=>Ae.create({...n,coerce:!0})),date:(n=>Pe.create({...n,coerce:!0}))};var bl=b;var F=e.enum(["claude","codex","cursor","gemini","qoder"]),lt=e.enum(["none","low","medium","high","xhigh","max"]),nn=e.boolean(),rn=e.enum(["local","remote"]),ta=e.enum(["app_install","user_invite","system"]),Eg=e.enum(["long_lived","bootstrap"]),ne=e.enum(["regular","agent_home"]),V=e.enum(["channel","dm_channel"]),na=e.enum(["starting","active","idle","archived","crashed"]),sn=e.enum(["idle","starting","active","crashed"]),an=e.enum(["user","agent","system"]),J=e.enum(["todo","in_progress","in_review","done","closed"]),ra=e.enum(["agent","user"]),sa=e.enum(["session_init","thinking","text","tool_call","tool_output","file_change","shell","stderr","compaction_started","compaction_finished","turn_end","error","unknown","parsed_event_dropped"]),aa=e.enum(["pending_materialization","active","failed"]),oa=["read_messages","send_messages","read_tasks","create_tasks","write_tasks","read_attachments","upload_attachments","create_threads","create_channels","manage_conversation_members","manage_schedules"],ia=e.enum(["local","s3","oss"]),ca=e.enum(["user","agent"]),la=e.enum(["mention_external","mention_self","agent_start_failed"]);var Sl=e.enum(["pending","attached","active","revoked"]),re=e.object({id:e.string(),name:e.string(),kind:rn,created_at:e.number(),revoked_at:e.number().nullable(),last_seen_at:e.number().nullable(),activated_at:e.number().nullable().optional().default(null),finalized_at:e.number().nullable().optional().default(null),connected_host_name:e.string().nullable().optional().default(null),provisioning_source:ta.optional().default("system"),status:Sl.optional().default("pending"),placeable:e.boolean().optional().default(!1),creator_user_id:e.string().nullable().optional().default(null),display_label:e.string().nullable()}),Pg=e.object({display_label:e.string().max(256).nullable()}).strict(),Og=e.object({host:re}),Ig=e.enum(["available","disconnected","unreachable","revoked"]);var Mg=e.object({host_id:e.string()}).strict(),xl=e.enum(["daemon_unreachable","timeout","protocol_error"]),on=e.object({agent_id:e.string(),display_name:e.string(),handle:e.string(),runtime:e.string(),avatar_url:e.string().nullable().optional().default(null),online:e.enum(["online","offline"])}),kl=e.object({os:e.string().min(1),os_arch:e.string().optional(),daemon_version:e.string(),daemon_pid:e.number().int(),started_at:e.number().int(),uptime_ms:e.number().int()}),wl=e.object({host_id:e.string(),availability:e.literal("available"),snapshot:kl,agents:e.array(on),last_seen_at:e.number().nullable().optional()}).strict(),Rl=e.object({host_id:e.string(),availability:e.literal("disconnected"),agents:e.array(on),last_seen_at:e.number().nullable().optional()}).strict(),El=e.object({host_id:e.string(),availability:e.literal("unreachable"),reason:xl,agents:e.array(on),last_seen_at:e.number().nullable().optional()}).strict(),Cl=e.object({host_id:e.string(),availability:e.literal("revoked"),agents:e.array(on),last_seen_at:e.number().nullable().optional()}).strict(),Dg=e.discriminatedUnion("availability",[wl,Rl,El,Cl]),fr=e.object({proxy_url:e.string().nullable(),proxy_runtimes:e.array(F)}),Lg=e.object({config:fr}).strict(),Al="computer_offline",jg=e.object({error:e.string(),error_code:e.literal(Al)}).strict(),Ng=e.object({installation_id:e.string().uuid(),label:e.string().trim().min(1).max(128).optional(),current_host_id:e.string().min(1).optional()}).strict(),Fg=e.object({host_id:e.string(),host:re,server_url:e.string().url(),host_token:e.string().min(1).optional()}),zg=e.object({hosts:e.array(re)}),$g=e.object({}).strict(),Hg=e.object({host_id:e.string(),host:re,server_url:e.string().url(),connect_token:e.string().min(1),daemon_command:e.string().min(1)}),Ug=e.object({host_id:e.string().min(1)}),Wg=e.object({host:re}),qg=e.object({host_id:e.string(),deleted:e.literal(!0)});var Tl=e.object({agents:e.number().int().nonnegative(),workspaces:e.number().int().nonnegative()}),Bg=e.object({error:e.string(),error_code:e.literal("has_dependents"),dependents:Tl}),Vg=e.object({host:re}),Pl=e.object({host_id:e.string(),host:re,host_token:e.string().min(1)}),Ol=e.object({host_id:e.string(),host:re,status:e.literal("rotated")}),Il=e.object({host_id:e.string(),host:re,status:e.literal("rotated"),connect_token:e.string().min(1),daemon_command:e.string().min(1)}),Gg=e.object({host_id:e.string(),host:re,disconnected:e.boolean()}),Kg=e.union([Pl,Ol,Il]);var Pt=e.object({id:e.string(),name:e.string(),display_name:e.string(),avatar_url:e.string().nullable(),created_at:e.number(),updated_at:e.number()}),Jg=e.object({users:e.array(Pt)}),Ml=e.object({registration_required:e.literal(!0),suggested_name:e.string()}),Xg=e.union([Pt,Ml]),Dl=/[\x00-\x1F\x7F-\x9F\u2028\u2029]/,Ll="display_name must not contain control characters or Unicode line separators",Ot=e.string().trim().min(1).max(64).refine(n=>!Dl.test(n),{message:Ll}),da=e.string().trim().email().max(320),Qg=e.object({email:da,password:e.string().min(8).max(1024),display_name:Ot.optional()}),e_=e.object({email:da,password:e.string().min(1).max(1024)}),t_=e.object({user_token:e.string().min(1),user:Pt}),n_=e.object({ok:e.literal(!0)}),r_=e.object({display_name:Ot.optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),s_=e.object({avatar_url:e.string()});var jl=e.enum(["loopback","lan","public"]),i_=e.object({signup_enabled:e.boolean(),bind_address_scope:jl.optional()});var ua={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:[]}},Nl=["claude","codex","qoder","cursor","gemini"],d_=Nl.map(n=>ua[n]);function ma(n,t){return t==null?!0:ua[n].reasoningEffortOptions.includes(t)}var pa=e.object({id:e.string(),name:e.string(),display_name:e.string(),runtime:F,model:e.string().nullable(),reasoning_effort:lt.nullable(),fast_mode:nn.nullable(),host_id:e.string(),description:e.string().nullable(),created_by_user_id:e.string(),avatar_url:e.string().nullable(),materialization_status:aa,materialization_failed_code:e.string().nullable(),materialization_failed_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),g_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),runtime:F,model:e.string().optional(),reasoning_effort:lt.optional(),fast_mode:nn.optional(),host_id:e.string().optional(),description:e.string().optional()}).superRefine((n,t)=>{ma(n.runtime,n.reasoning_effort)||t.addIssue({code:e.ZodIssueCode.custom,path:["reasoning_effort"],message:`reasoning_effort '${n.reasoning_effort}' is not valid for runtime '${n.runtime}'`})}),__=e.object({display_name:Ot.optional(),description:e.string().max(2e3).nullable().optional(),runtime:e.never().optional(),model:e.string().nullable().optional(),reasoning_effort:lt.nullable().optional(),fast_mode:nn.nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),y_=e.object({id:e.string(),name:e.string(),display_name:e.string(),description:e.string().nullable(),avatar_url:e.string().nullable()}),ha=e.object({display_name:Ot.optional(),description:e.string().max(2e3).nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),v_=e.object({agent_id:e.string()}),Fl=e.object({path:e.string().min(1),kind:e.enum(["file","directory"]),size:e.number(),mtime:e.number()}).strict(),fa=e.object({nodes:e.array(Fl)}).strict(),ga=e.object({path:e.string().min(1),content:e.string(),size:e.number(),mtime:e.number(),truncated:e.boolean()}).strict(),_a=e.object({conversation_id:e.string(),workspace_id:e.string(),workspace_name:e.string(),workspace_kind:ne,conversation_kind:V,channel_id:e.string(),channel_title:e.string(),status:sn,pid:e.number().nullable(),closed_at:e.number().nullable()}),b_=e.object({conversation_agents:e.array(_a)}),S_=e.object({agent_id:e.string(),agent_name:e.string(),agent_display_name:e.string(),dm_channel:e.object({id:e.string(),name:e.string(),conversation_count:e.number(),message_count:e.number()}).nullable(),regular_workspaces:e.array(e.object({id:e.string(),name:e.string()})),regular_memberships:e.array(e.object({id:e.string(),name:e.string()})),owned_home:e.object({id:e.string(),name:e.string(),workspace_kind:ne,owner_agent_id:e.string().nullable()}).nullable(),attachments_count:e.number(),running_conversation_agents:e.array(_a),pending_inbox_count:e.number()}),x_=e.object({confirm:e.literal(!0)});var A_=e.object({id:e.string(),name:e.string(),description:e.string().nullable(),workspace_kind:ne,workspace_path:e.string(),workspace_host_id:e.string(),owner_agent_id:e.string().nullable(),owner_user_id:e.string().nullable(),dm_channel_id:e.string().nullable(),dm_channel_ids:e.array(e.string()),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),T_=e.object({workspace_id:e.string(),agent_id:e.string(),joined_at:e.number()}),cn=e.enum(["owner","admin","member"]),zl=e.object({workspace_id:e.string(),user_id:e.string(),joined_at:e.number(),role:cn}),ya=Pt.extend({workspace_id:e.string(),user_id:e.string(),joined_at:e.number(),role:cn}),It=e.enum(oa),P_=e.object({workspace_id:e.string(),agent_id:e.string(),capabilities:e.array(It)}),O_=e.object({capabilities:e.array(It)}),I_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore"),description:e.string().optional(),workspace_path:e.string().optional(),workspace_host_id:e.string().optional(),member_agent_ids:e.array(e.string()).default([]),member_user_ids:e.array(e.string()).default([])}),M_=e.object({name:e.string().min(1).max(64).regex(/^[a-zA-Z0-9_\-]+$/,"name must be alphanumeric / dash / underscore").optional(),description:e.string().nullable().optional()}).refine(n=>Object.keys(n).length>0,{message:"no fields to update"}),D_=e.object({archived:e.boolean()}),$l=e.object({agent_id:e.string()}),Hl=e.object({kind:e.literal("agent"),agent_id:e.string()}),Ul=e.object({kind:e.literal("human"),user_id:e.string()}),L_=e.union([Hl,Ul,$l]),j_=e.object({role:cn}),N_=e.object({member:zl,human_member:ya}),F_=e.object({members:e.array(pa),human_members:e.array(ya),viewer_role:cn.nullable()});var va=e.object({id:e.string(),workspace_id:e.string(),workspace_path:e.string(),kind:V,title:e.string(),status:na,spawned_by_agent_id:e.string().nullable(),closed_at:e.number().nullable(),close_summary:e.string().nullable(),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()}),Wl=va.extend({kind:e.literal("channel")}),ql=va.extend({kind:e.literal("dm_channel")}),ba=e.string().trim().min(1).max(128),U_=e.object({title:ba,member_agent_ids:e.array(e.string()).default([]),member_user_ids:e.array(e.string()).optional()}),Bl=e.enum(["regular","dm"]),Vl=e.object({id:e.string(),kind:V,title:e.string(),workspace_id:e.string(),workspace_kind:Bl,workspace_path:e.string(),closed_at:e.number().nullable(),archived_at:e.number().nullable()}),W_=e.object({ref:Vl}),q_=e.object({conversation_id:e.string(),agent_id:e.string(),cli_session_id:e.string().nullable(),pid:e.number().nullable(),status:sn,joined_at:e.number()}),B_=e.object({conversation_id:e.string(),user_id:e.string(),joined_at:e.number()}),Gl=e.object({kind:e.literal("agent"),agent_id:e.string(),name:e.string(),display_name:e.string(),runtime:F}),Kl=e.object({kind:e.literal("human"),user_id:e.string(),name:e.string(),display_name:e.string(),avatar_url:e.string().nullable()}),gr=e.discriminatedUnion("kind",[Gl,Kl]),V_=e.object({members:e.array(gr)}),Zl=e.string().trim().regex(/^@?[a-zA-Z0-9_-]{1,64}$/,{message:"handle must be @optional alphanumeric / dash / underscore"}),Yl=e.discriminatedUnion("kind",[e.object({kind:e.literal("agent"),agent_id:e.string()}),e.object({kind:e.literal("human"),user_id:e.string()})]),Jl=e.object({handle:Zl}),G_=e.union([Yl,Jl]),K_=e.object({ok:e.literal(!0),prev_cli_session_id:e.string().nullable(),was_running:e.boolean()}),Xl=e.record(e.string(),e.unknown()).nullable(),Ql=e.object({id:e.number().int(),conversation_id:e.string(),agent_id:e.string().nullable(),kind:sa,payload:Xl,created_at:e.number().int()}),Z_=e.object({events:e.array(Ql),next_before_id:e.number().int().nullable()});var ed=e.union([Wl,ql]),Y_=e.object({archived:e.boolean()}),J_=e.object({title:ba}),X_=e.object({workspace_id:e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().optional()),since:e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional())}),td=e.object({channel:ed,workspace:e.object({id:e.string(),name:e.string(),archived_at:e.number().nullable()})}),Q_=e.object({channels:e.array(td)});var nd=e.enum(["starting","thinking","tool_running","idle","failed"]),rd=e.enum(["replied","turn_ended","replaced","stopped","crashed","timeout","conversation_closed"]),dt=e.object({runId:e.string(),agentId:e.string(),conversationId:e.string(),status:nd,startedAt:e.number(),updatedAt:e.number(),lastActivityAt:e.number(),terminalReason:rd.optional(),activitySnippet:e.string().optional(),toolCallCounts:e.record(e.string(),e.number()).optional(),compacting:e.boolean().optional(),compactingSince:e.number().optional(),compactionStale:e.boolean().optional(),detail:e.string().optional()});var ry=e.object({states:e.array(dt)}),sd=e.enum(["present","present_unverified","absent","unknown"]),ad=e.enum(["resolved","version_unavailable","not_found","probe_failed"]),od=e.object({kind:F,state:sd,reason:ad,installed:e.boolean(),binary:e.string().nullable(),version:e.string().nullable()}),Sa=e.object({runtimes:e.array(od),detected_at:e.number()});var iy=e.object({id:e.string(),channel_id:e.string(),source_conversation_id:e.string().nullable(),filename:e.string(),size:e.number(),content_type:e.string(),storage:ia,created_by_kind:ca,created_by_id:e.string(),created_at:e.number()}),id=/^(Image|File) #([1-9]\d{0,3})$/,xa=e.string().trim().regex(id,'label must be "Image #N" or "File #N"');var ln=e.object({id:e.string(),filename:e.string(),size:e.number(),content_type:e.string(),label:xa.optional()}),ka=e.object({id:e.string().min(1),label:xa.optional()});var cy=e.union([e.object({storage:e.literal("local"),local_path:e.string(),filename:e.string(),content_type:e.string()}),e.object({storage:e.enum(["s3","oss"]),download_url:e.string(),filename:e.string(),content_type:e.string()})]);var wa=e.enum(["user","agent"]),dn=e.object({emoji:e.string(),count:e.number().int().positive(),viewer_reacted:e.boolean()}),cd=e.object({kind:wa,id:e.string(),display_name:e.string()}),uy=e.object({emoji:e.string(),reactors:e.array(cd)}),my=e.object({emoji:e.string()}),py=e.object({message_id:e.string().min(1),emoji:e.string()}),hy=e.object({message_id:e.string(),conversation_id:e.string(),thread_root_id:e.string().nullable(),emoji:e.string(),op:e.enum(["add","remove"]),reactor_kind:wa,reactor_id:e.string(),count:e.number().int().nonnegative()});var fy=new RegExp("^(?:\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");var be=e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().trim().optional()),un=e.array(e.union([e.string().min(1),ka])).max(20).refine(n=>{let t=n.map(r=>typeof r=="string"?void 0:r.label).filter(r=>r!==void 0);return new Set(t).size===t.length},{message:"attachment labels must be unique within a message"}).optional();function mn(n){return n.content.trim().length>0||(n.attachment_ids?.length??0)>0}var _r=e.union([e.object({kind:e.literal("channel")}).strict(),e.object({kind:e.literal("thread"),message_id:e.string().min(1)}).strict()]),ld=e.literal("self"),yr=e.union([_r,ld]),Ry=e.enum(["unaffected","revised","obsolete","force_send"]),vr=e.enum(["unaffected","revised","force_send"]),Ey=e.object({content:e.string(),target:yr.optional(),reply_to_message_id:e.string().min(1).optional(),stream_key:e.string().min(1).optional(),seen_up_to_seq:e.number().int().nonnegative().optional(),stale_event_id:e.string().min(1).optional(),stale_resolution_reason:vr.optional(),freshness_bypass:e.boolean().optional(),attachment_ids:un}).refine(mn,{message:"message must include text or at least one attachment",path:["content"]}),Cy=e.object({stale_event_id:e.string().min(1),resolution_reason:e.literal("obsolete")}),Ay=e.object({message_id:e.string(),message_seq:e.number().int().positive(),thread_root_id:e.string().nullable()}),Ty=e.object({title:e.string().min(1).max(128),context_summary:e.string().min(1),initial_prompt:e.string().min(1)}),Py=e.object({root_message_id:e.string().min(1)}),Oy=e.object({thread_root_id:e.string(),changed:e.boolean()}),Iy=e.object({task_number:e.number().int().positive(),status:e.enum(["todo","in_progress","in_review"]),title:e.string(),assignee_name:e.string().nullable(),assignee_agent_id:e.string().nullable()}),Ra=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional()),dd=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().positive().max(100).optional().default(50)),ud=e.union([e.literal("self"),e.object({thread_root_id:e.string().min(1)}),e.object({conversation_id:e.string().min(1)})]),My=e.object({target:ud.optional(),before_seq:Ra,after_seq:Ra,around_message_id:e.string().min(1).optional(),include_content:e.boolean().optional().default(!1),include_system:e.boolean().optional().default(!0),limit:dd}).refine(n=>[n.before_seq,n.after_seq,n.around_message_id].filter(t=>t!==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"]}),Ea=e.object({id:e.string(),workspace_id:e.string(),conversation_id:e.string(),conversation_kind:V,channel_id:e.string(),seq:e.number(),created_at:e.number()}),Ca=e.object({kind:an,agent_id:e.string().nullable(),user_id:e.string().nullable(),display_name:e.string().nullable()}),md=e.object({conversation_id:e.string(),conversation_kind:V,channel_id:e.string(),thread_root_id:e.string().nullable(),workspace_id:e.string(),title:e.string()}),pd=e.object({message_ref:Ea,sender:Ca,snippet:e.string(),metadata:e.record(e.unknown()).nullable(),attachments:e.array(ln).nullable(),reactions:e.array(dn).nullable(),content:e.string().optional()}),hd=e.union([e.object({type:e.literal("head")}),e.object({type:e.literal("before_seq"),seq:e.number()}),e.object({type:e.literal("after_seq"),seq:e.number()}),e.object({type:e.literal("around_message_id"),message_id:e.string()})]),Dy=e.object({target:md,anchor:hd,limit:e.number(),include_content:e.boolean(),include_system:e.boolean(),messages:e.array(pd),has_more_before:e.boolean(),has_more_after:e.boolean()}),fd=e.object({id:e.string(),name:e.string(),kind:ne,archived:e.boolean(),updated_at:e.number(),agent_dir:e.string()}),Ly=e.object({workspaces:e.array(fd)}),jy=e.object({workspace_id:e.string().min(1).optional()}),gd=e.object({id:e.string(),title:e.string(),kind:e.enum(["channel","dm_channel"]),archived:e.boolean(),updated_at:e.number()}),Ny=e.object({workspace_id:e.string(),channels:e.array(gd)}),Aa=e.enum(["current","workspace","channel"]),_d=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().positive().max(100).optional().default(50)),Fy=e.object({q:e.string().trim().min(1).max(200),scope:Aa.optional().default("current"),workspace_id:e.string().min(1).optional(),channel_id:be,include_system:e.boolean().optional().default(!0),limit:_d}).superRefine((n,t)=>{n.scope==="channel"!=!!n.channel_id&&t.addIssue({code:e.ZodIssueCode.custom,message:"channel_id is required only when scope is channel",path:["channel_id"]}),n.workspace_id&&n.scope!=="workspace"&&t.addIssue({code:e.ZodIssueCode.custom,message:"workspace_id is only valid with scope=workspace",path:["workspace_id"]})}),yd=e.object({message_ref:Ea,sender:Ca,excerpt:e.string(),match_offset:e.number().int().nonnegative()}),zy=e.object({query:e.string(),scope:Aa,workspace_id:e.string().nullable(),channel_id:e.string().nullable(),include_system:e.boolean(),limit:e.number(),hits:e.array(yd)}),$y=e.object({noun:e.string().max(64).optional(),verb:e.string().max(64).optional(),flags_seen:e.array(e.string().max(64)).max(64).optional(),error_code:e.string().max(64).optional(),error_subkind:e.string().max(64).optional(),error_message:e.string().max(500).optional(),duration_ms:e.number().nonnegative().optional()}).strict(),Hy=e.object({ok:e.literal(!0)}),Uy=e.object({enabled:e.boolean()}).strict(),Wy=e.object({conversationId:e.string(),enabled:e.boolean(),expiresAt:e.number().int().nullable(),daemonSynced:e.boolean().optional()}).strict();var ut=e.object({type:ra,id:e.string(),name:e.string()}),Ta=e.object({id:e.string(),title:e.string()}),vd=e.object({type:e.enum(["agent","user","system"]),id:e.string().nullable(),name:e.string()}),Zy=e.object({message_id:e.string(),task_number:e.number(),workspace_id:e.string(),workspace_name:e.string(),channel_id:e.string(),channel_name:e.string(),thread_root_id:e.string().nullable(),conversation:Ta,status:J,title:e.string(),assignee:ut.nullable(),creator:vd,created_at:e.number(),closed_at:e.number().nullable()}),Yy=e.object({workspace_id:e.string().optional(),conversation_id:e.string().optional(),status:e.array(J).optional(),task_number:e.array(e.coerce.number().int().positive()).optional(),assignee_id:e.string().optional(),limit:e.coerce.number().int().positive().max(500).optional()}),Jy=e.object({tasks:e.array(e.object({title:e.string().min(1).max(200),body:e.string().optional()})).min(1),target:_r.optional(),reply_to_message_id:e.string().min(1).optional()}),bd=e.enum(["conversation_not_found","conversation_closed","not_conversation_member","agent_not_found","reply_target_not_found"]),Sd=e.object({tasks:e.array(e.object({message_id:e.string(),task_number:e.number(),title:e.string()}))}),xd=e.object({error:bd}),Xy=e.union([Sd,xd]),Qy=e.object({task_numbers:e.array(e.number()).optional(),message_ids:e.array(e.string()).optional(),workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>(n.task_numbers?.length??0)+(n.message_ids?.length??0)>0,{message:"provide at least one of task_numbers or message_ids"}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),kd=e.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"]),wd=e.object({success:e.boolean(),task_number:e.number().optional(),message_id:e.string().optional(),reason:e.string().optional(),code:kd.optional(),capability:It.optional(),owner_conversation:Ta.optional(),workspace_candidates:e.array(e.string()).optional()}),ev=e.object({results:e.array(wd)}),tv=e.object({task_number:e.number().int().positive(),workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),nv=e.object({task_number:e.number().int().positive(),status:J,workspace_id:e.string().optional(),workspace_name:e.string().optional()}).refine(n=>!(n.workspace_id&&n.workspace_name),{message:"workspace_id and workspace_name are mutually exclusive"}),Rd=e.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"]),rv=e.object({success:e.boolean(),reason:e.string().optional(),code:Rd.optional(),capability:It.optional(),workspace_candidates:e.array(e.string()).optional()}),sv=e.object({status:J}),av=e.object({agent_id:e.string().optional()}),ov=e.object({kind:e.enum(["create","claim","unclaim","status"]),workspace_id:e.string(),channel_id:e.string(),thread_root_id:e.string().nullable(),conversation_id:e.string(),task_number:e.number(),message_id:e.string(),status:J,assignee:ut.nullable(),title:e.string(),closed_at:e.number().nullable()});function pn(n,t){if(!Number.isInteger(n)||n<0)throw new RangeError(`${t}: cannot decode ${n} \u2014 expected a non-negative integer seq`)}function Ed(n){return pn(n,"MessageSeq"),n}function Cd(n){return pn(n,"TransportSeq"),n}function Ad(n){return pn(n,"ReadSeq"),n}function Td(n){return pn(n,"ObservedSeq"),n}function Pd(n){if(typeof n!="string"||n.length===0)throw new RangeError(`TransportEpoch: cannot decode ${JSON.stringify(n)} \u2014 expected a non-empty string`);return n}var hn=e.number().int().nonnegative(),Ue=hn.transform(Ed),lv=hn.transform(Cd),dv=hn.transform(Ad),uv=hn.transform(Td),mv=e.string().min(1).transform(Pd);var Od=e.enum(["agent","human","system"]),Id=e.object({kind:Od,id:e.string()}),Md=e.object({kind:e.enum(["agent","human"]),id:e.string()}),Pa=e.object({root_message_id:e.string(),root_author:Id,root_preview:e.string(),root_created_at:e.number(),root_seq:Ue,reply_count:e.number().int().nonnegative(),last_reply_at:e.number(),last_reply_message_id:e.string(),repliers:e.array(Md),replier_total:e.number().int().nonnegative(),viewer_following:e.boolean()}),Oa=Pa.omit({viewer_following:!0}),gv=e.object({threads:e.array(Pa),next_cursor:e.string().nullable()});var fn=e.object({id:e.string(),conversation_id:e.string(),from_kind:an,from_agent_id:e.string().nullable(),from_user_id:e.string().nullable(),content:e.string(),metadata:e.record(e.unknown()).nullable(),attachments:e.array(ln).nullable(),reactions:e.array(dn).nullable(),seq:Ue,created_at:e.number(),thread_root_id:e.string().nullable(),task_number:e.number().nullable(),task_status:J.nullable(),task_title:e.string().nullable(),task_workspace_id:e.string().nullable(),task_closed_at:e.number().nullable(),task_assignee:ut.nullable()}),Dd=e.object({root_id:e.string(),reply_count:e.number().int().nonnegative()}),Ld=e.object({thread_root_reply_count:Dd.optional(),threads_list_entry:e.object({entry:Oa}).optional()}),Ev=e.object({message:fn,projections:Ld.optional()}),jd=e.object({reply_count:e.number().int().nonnegative(),last_reply_at:e.number(),repliers:e.array(e.object({kind:e.enum(["agent","human"]),id:e.string()})),replier_total:e.number().int().nonnegative()}),Cv=e.object({messages:e.array(fn),reply_counts_by_root:e.record(e.string(),e.number().int().nonnegative()),reply_summaries_by_root:e.record(e.string(),jd).optional(),has_more_before:e.boolean(),stream_head_seq:Ue,has_more_after:e.boolean()}),Av=e.object({thread_root_id:e.string(),viewer_following:e.boolean(),follower_agent_ids:e.array(e.string())}),Tv=e.object({thread_root_id:e.string(),changed:e.boolean(),viewer_following:e.boolean()}),Pv=e.object({content:e.string(),attachment_ids:un,reply_to_message_id:e.string().min(1).optional(),as_task:e.boolean().optional()}).refine(mn,{message:"message must include text or at least one attachment",path:["content"]}),Ia=e.object({unread_count:e.number().int().nonnegative(),first_unread_message_id:e.string().nullable(),first_unread_seq:Ue.nullable()}),Ov=e.object({mainline:Ia,threads:e.record(e.string(),Ia)}),La=e.object({conversation_id:e.string(),message_id:e.string(),seq:Ue,thread_root_id:e.string().nullable()}),Iv=e.object({by_conversation:e.record(e.string(),e.number()),latest_by_conversation:e.record(e.string(),La),total:e.number()}),Mv=e.object({by_workspace:e.record(e.string(),e.number())}),Dv=e.object({conversation_id:e.string(),workspace_id:e.string(),conversation_unread_count:e.number(),workspace_unread_count:e.number(),latest_unread:La.nullable()}),Ma=e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional()),Nd=e.enum(["all","regular","dm"]),Fd=e.enum(["all","mainline","thread"]),zd=e.enum(["recency_desc","seq_asc"]),$d=e.object({q:e.string().trim().max(200).optional().default(""),scope:Nd.optional().default("all"),stream:Fd.optional().default("all"),workspace_id:be,conversation_id:be,thread_root_id:be,user_id:be,agent_id:be,from:Ma,to:Ma,order:zd.optional().default("recency_desc"),limit:e.coerce.number().int().positive().max(500).optional().default(80)}).refine(n=>!(n.user_id&&n.agent_id),{message:"user_id and agent_id cannot both be set",path:["user_id"]}).refine(n=>n.stream==="all"||!!n.conversation_id,{message:"stream filter requires conversation_id",path:["stream"]}).refine(n=>n.stream!=="thread"||!!n.thread_root_id,{message:"stream=thread requires thread_root_id",path:["thread_root_id"]}).refine(n=>n.order!=="seq_asc"||!!n.conversation_id,{message:"order=seq_asc requires conversation_id",path:["order"]}),br=e.object({id:e.string(),name:e.string(),kind:e.enum(["regular","dm"])}),Da=e.object({id:e.string(),title:e.string(),kind:V,channel_id:e.string(),closed_at:e.number().nullable(),created_at:e.number()}),Hd=e.discriminatedUnion("type",[e.object({type:e.literal("workspace"),workspace:br.extend({description:e.string().nullable(),archived_at:e.number().nullable(),created_at:e.number(),updated_at:e.number()})}),e.object({type:e.literal("conversation"),workspace:br,conversation:Da}),e.object({type:e.literal("message"),workspace:br,conversation:Da,message:fn,agent_name:e.string().nullable()})]),Lv=e.object({query:$d,results:e.array(Hd),total:e.number(),truncated:e.boolean()}),jv=e.object({id:e.string(),message:fn,workspace_id:e.string(),workspace_name:e.string(),conversation_id:e.string(),conversation_title:e.string(),channel_id:e.string(),agent_name:e.string().nullable(),saved_at:e.number()}),Nv=e.object({workspace_id:e.preprocess(n=>typeof n=="string"&&n.trim()===""?void 0:n,e.string().optional()),since:e.preprocess(n=>n===""||n===void 0?void 0:n,e.coerce.number().int().nonnegative().optional())});var ja=["all","mentions"];var $v=e.object({conversation_id:e.string(),mode:e.enum(ja)}),Hv=e.object({mode:e.enum(ja)}),Ud=["directed","ambient"],Wd=["mention","agent_failed","unread"],qd=e.object({kind:e.enum(["user","agent"]),id:e.string(),display_name:e.string(),avatar_url:e.string().nullable()}),Bd=e.object({id:e.string(),kind:e.enum(Wd),salience:e.enum(Ud),workspace_id:e.string(),conversation_id:e.string(),thread_root_id:e.string().nullable(),message_id:e.string().nullable(),notification_id:e.string().nullable(),conversation_kind:e.enum(["channel","dm_channel"]),title:e.string(),thread_root_preview:e.string().nullable(),preview:e.string().nullable(),preview_sender:qd.nullable(),timestamp:e.number(),unread_count:e.number().int().nonnegative().nullable()}),Uv=e.object({items:e.array(Bd)}),Vd=e.discriminatedUnion("kind",[e.object({kind:e.literal("at_seq"),seq:e.number().int().nonnegative()}),e.object({kind:e.literal("stream_head")})]),Gd=e.discriminatedUnion("kind",[e.object({kind:e.literal("stream"),conversation_id:e.string().min(1),thread_root_id:e.string().min(1).nullable(),position:Vd}),e.object({kind:e.literal("notification"),notification_id:e.string().min(1)})]),Wv=e.object({sources:e.array(Gd).min(1).max(1e3)}),qv=e.object({changed:e.boolean()});var Kv=e.object({id:e.string(),kind:la,user_id:e.string().nullable(),agent_id:e.string().nullable(),workspace_id:e.string().nullable(),conversation_id:e.string().nullable(),message_id:e.string().nullable(),thread_root_id:e.string().nullable().optional(),source_workspace_id:e.string().nullable(),source_conversation_id:e.string().nullable(),source_message_id:e.string().nullable(),payload:e.record(e.unknown()).nullable(),read_at:e.number().nullable(),created_at:e.number()}),Zv=e.object({id:e.string().optional(),workspace_id:e.string().optional(),conversation_id:e.string().optional(),all:e.boolean().optional()}).refine(n=>!!(n.id||n.workspace_id||n.conversation_id||n.all),{message:"must specify id, workspace_id, conversation_id, or all"});var Xv=2160*60*60,Kd=60;var Zd=120,Yd=500,Jd=e.enum(["pending","firing","done","cancelled","failed"]),Xd=e.object({kind:e.literal("once"),fire_at:e.number().int().positive()}),Na=e.object({kind:e.literal("interval"),every_seconds:e.number().int().min(Kd),start_at:e.number().int().positive().optional()}),Fa=e.object({kind:e.literal("cron"),expression:e.string().min(1).max(200),timezone:e.string().min(1).max(64)}),Qd=e.discriminatedUnion("kind",[Xd,Na,Fa]),Sr=e.object({id:e.string(),owner_agent_id:e.string(),target_conversation_id:e.string(),target_label:e.string(),title:e.string(),message:e.string(),spec:Qd,next_fire_at:e.number(),status:Jd,fired_count:e.number(),last_fired_at:e.number().nullable(),max_occurrences:e.number().nullable(),until_at:e.number().nullable(),failure_reason:e.string().nullable(),cancelled_at:e.number().nullable(),last_failure_reason:e.string().nullable(),last_failure_at:e.number().nullable(),consecutive_failure_count:e.number(),created_at:e.number(),updated_at:e.number()}),eu=e.object({kind:e.literal("once"),fire_at:e.number().int().positive().optional(),delay_seconds:e.number().int().positive().optional()}),Qv=e.object({title:e.string().trim().min(1).max(Zd),message:e.string().min(1).max(Yd),target_conversation_id:e.string().optional(),spec:e.discriminatedUnion("kind",[eu,Na,Fa]),until_at:e.number().int().positive().optional(),max_occurrences:e.number().int().positive().optional(),allow_unbounded:e.boolean().optional()}).superRefine((n,t)=>{n.spec.kind==="once"&&(n.until_at!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["until_at"],message:"until_at is not valid on a `once` schedule"}),n.max_occurrences!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["max_occurrences"],message:"max_occurrences is not valid on a `once` schedule"}),n.allow_unbounded!==void 0&&t.addIssue({code:e.ZodIssueCode.custom,path:["allow_unbounded"],message:"allow_unbounded is not valid on a `once` schedule"}),!!n.spec.fire_at==!!n.spec.delay_seconds&&t.addIssue({code:e.ZodIssueCode.custom,path:["spec","fire_at"],message:"once spec requires exactly one of fire_at or delay_seconds"}))}),tu=e.enum(["pending","firing","active","done","cancelled","failed","all"]),eb=e.object({status:tu.optional(),limit:e.number().int().min(1).max(200).optional()}),tb=e.object({schedule_id:e.string()}),nb=e.object({schedule:Sr}),rb=e.object({schedules:e.array(Sr)}),sb=e.object({schedule:Sr});var nu=e.enum(["online","offline"]),ru=e.object({user_id:e.string(),presence:nu,last_seen_at:e.number().nullable()});var ib=e.object({users:e.array(ru)});var za=e.enum(["recent","manual"]),$a=e.enum(["starred","dm","regular","unstarred","favorites"]),xr=e.string().refine(n=>n==="workspaces"||n==="favorites"||n.startsWith("channels:"),{message:"list_key must be 'workspaces', 'favorites', or 'channels:<ws_id>'"}),su=e.object({entity_id:e.string(),rank:e.number().nullable(),last_accessed_at:e.number().nullable(),starred_at:e.number().nullable()}),Ha=e.object({list_key:e.string(),modes:e.record(za),entries:e.array(su)}),db=e.object({list_key:xr,group:$a.optional(),mode:za}),ub=e.object({list_key:xr,group:$a,ordered_ids:e.array(e.string())}),mb=e.object({list_key:xr,entity_id:e.string()});var au=e.enum(["workspace","dm"]),ou=e.object({kind:au,favorite_key:e.string(),entity_id:e.string(),workspace_id:e.string(),title:e.string(),icon_url:e.string().nullable(),runtime:F.nullable(),starred_at:e.number(),created_at:e.number(),unread_count:e.number().nullable()}),_b=e.object({items:e.array(ou),viewer_sort:Ha});var C={agentSendConversationMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/send-message`,agentResolveStaleMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/stale-message-resolution`,agentCreateChannel:(n,t)=>`/internal/conversations/${n}/agents/${t}/create-channel`,agentReadHistory:(n,t)=>`/internal/conversations/${n}/agents/${t}/read-history`,agentFollowThread:(n,t)=>`/internal/conversations/${n}/agents/${t}/follow-thread`,agentUnfollowThread:(n,t)=>`/internal/conversations/${n}/agents/${t}/unfollow-thread`,agentListWorkspaces:(n,t)=>`/internal/conversations/${n}/agents/${t}/list-workspaces`,agentListChannels:(n,t)=>`/internal/conversations/${n}/agents/${t}/list-channels`,agentSearchMessages:(n,t)=>`/internal/conversations/${n}/agents/${t}/search-messages`,agentAddConversationMember:(n,t)=>`/internal/conversations/${n}/agents/${t}/members`,agentReactMessage:(n,t)=>`/internal/conversations/${n}/agents/${t}/react-message`,agentListConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks`,agentCreateConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/create`,agentClaimConversationTasks:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/claim`,agentUnclaimConversationTask:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/unclaim`,agentUpdateConversationTaskStatus:(n,t)=>`/internal/conversations/${n}/agents/${t}/tasks/update-status`,agentScheduleCreate:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules`,agentScheduleList:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules/list`,agentScheduleCancel:(n,t)=>`/internal/conversations/${n}/agents/${t}/schedules/cancel`,agentUploadAttachment:(n,t)=>`/internal/conversations/${n}/agents/${t}/attachments`,agentLocateAttachment:(n,t,r)=>`/internal/conversations/${n}/agents/${t}/attachments/${r}/locate`,agentDownloadAttachment:(n,t,r)=>`/internal/conversations/${n}/agents/${t}/attachments/${r}/download`,agentUploadAvatar:(n,t)=>`/internal/conversations/${n}/agents/${t}/avatar`,agentDeleteAvatar:(n,t)=>`/internal/conversations/${n}/agents/${t}/avatar`,agentCliTrace:(n,t)=>`/internal/conversations/${n}/agents/${t}/cli-trace`,agentProfileMcpGet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp`,agentProfileMcpSet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp`,agentProfileMcpProbe:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile/mcp/probe`,agentProfileGet:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile`,agentProfileUpdate:(n,t)=>`/internal/conversations/${n}/agents/${t}/profile`};var iu=e.unknown().refine(n=>n!==void 0,{message:"field is required (opaque payload must be present)"}),gn=e.discriminatedUnion("kind",[e.object({kind:e.literal("session_init"),sessionId:e.string().min(1)}).strict(),e.object({kind:e.literal("thinking"),text:e.string()}).strict(),e.object({kind:e.literal("text"),text:e.string()}).strict(),e.object({kind:e.literal("tool_call"),name:e.string().min(1),input:iu,toolCallId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("tool_output"),name:e.string().min(1).optional(),toolCallId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("turn_end"),sessionId:e.string().min(1).optional()}).strict(),e.object({kind:e.literal("compaction_started")}).strict(),e.object({kind:e.literal("compaction_finished")}).strict(),e.object({kind:e.literal("error"),message:e.string(),code:e.string().optional(),fatal:e.boolean().optional()}).strict(),e.object({kind:e.literal("unknown"),raw:e.string()}).strict()]),cu=["session_init","thinking","text","tool_call","tool_output","turn_end","compaction_started","compaction_finished","error","unknown"],_n=e.enum(cu);var lu=e.enum(["embedded","remote"]),du=e.object({max_concurrent_per_parent:e.number().int().positive().nullable().default(null),spawn_cooldown_seconds:e.number().int().nonnegative().nullable().default(null),max_depth:e.literal(1).default(1)}),Zb=e.object({mode:lu,url:e.string().url(),auth_token:e.string().min(16).optional(),event_ws_allowed_origins:e.array(e.string().url()).optional(),refresh_token:e.string().nullable().default(null),child_sessions:du.default({max_concurrent_per_parent:null,spawn_cooldown_seconds:null,max_depth:1})});var mt="authorization",Yb=e.object({server_url:e.string().url(),host_id:e.string().min(1),host_token:e.string().min(1),allow_insecure_remote:e.boolean().optional(),profile_version:e.number().int().nonnegative().optional()}).strict(),kr="SILVERHAND_CONVERSATION_ID",wr="SILVERHAND_AGENT_ID",yn="SILVERHAND_SERVER_URL",Rr="SILVERHAND_AUTH_TOKEN",Ua="SILVERHAND_LAST_DELIVERED_SEQ_FILE",Wa="SILVERHAND_DAEMON_SOCKET";var uu=/^[A-Za-z0-9_-]{1,64}$/,mu=e.object({type:e.literal("stdio").optional(),command:e.string().min(1),args:e.array(e.string()).optional(),env:e.record(e.string()).optional()}).strict(),pu=e.object({type:e.enum(["http","sse"]),url:e.string().url(),headers:e.record(e.string()).optional()}).strict(),hu=e.union([mu,pu]),fu=e.object({mcpServers:e.record(hu).default({}).superRefine((n,t)=>{for(let r of Object.keys(n))uu.test(r)||t.addIssue({code:e.ZodIssueCode.custom,message:`invalid MCP server name "${r}": use 1-64 chars of [A-Za-z0-9_-]`,path:["mcpServers",r]})})}).strict(),gu={mcpServers:{}};function Mt(n){let t=n.trim();if(t.length===0)return{ok:!0,config:gu};let r;try{r=JSON.parse(t)}catch(a){return{ok:!1,error:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}let s=fu.safeParse(r);if(!s.success){let a=s.error.issues[0];return{ok:!1,error:`invalid MCP config${a?.path.length?` at ${a.path.join(".")}`:""}: ${a?.message??"schema mismatch"}`}}return{ok:!0,config:s.data}}var _u=["parse","not_found","connect","initialize","tools"],yu=e.enum(_u),vu=e.object({name:e.string(),description:e.string().optional()}).strict(),vn=e.object({ok:e.boolean(),phase:yu,message:e.string().optional(),server_info:e.object({name:e.string().optional(),version:e.string().optional()}).strict().optional(),tools:e.array(vu).optional()}).strict(),eS=e.object({server_name:e.string().min(1),include_tools:e.boolean().optional()}).strict();var nS=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 rS=Object.freeze(new Set(["html","htm","pdf","txt","log","md","markdown","json","csv","png","jpg","jpeg","gif","webp"]));var bu=1,cS=e.object({version:e.number().int().gte(bu),server_url:e.string().min(1),created_at:e.number().int().nonnegative(),updated_at:e.number().int().nonnegative()}),lS=e.object({server_url:e.string().min(1),updated_at:e.number().int().nonnegative()});var qa=["task_create","task_claim","task_unclaim","task_status"];var Su=e.discriminatedUnion("kind",[e.object({kind:e.literal("user"),id:e.string().nullable(),name:e.string()}),e.object({kind:e.literal("agent"),id:e.string(),name:e.string()})]),Ba={actor_kind:e.enum(["user","agent","system"]),actor_id:e.string(),actor_name:e.string(),actor_display_name:e.string().nullable(),member_kind:e.enum(["human","agent"]),member_id:e.string(),member_name:e.string(),member_display_name:e.string().nullable()},xu=e.object({subtype:e.literal("conversation_member_added"),...Ba}),ku=e.object({subtype:e.literal("conversation_member_removed"),...Ba}),fS=e.discriminatedUnion("subtype",[xu,ku]);var gS=e.object({subtype:e.enum(qa),task_number:e.number(),task_status:J,task_message_id:e.string(),task_title:e.string(),task_assignee:ut.nullable(),actor:Su});var _S=e.object({subtype:e.enum(qa),task_number:e.number(),task_status:J});var yS=e.object({subtype:e.literal("session_cleared"),agent_id:e.string(),agent_name:e.string(),actor_user_id:e.string().nullable(),previous_cli_session_id_prefix:e.string().nullable(),was_running:e.boolean()});var vS=e.object({subtype:e.literal("schedule_fire"),schedule_id:e.string(),title:e.string().optional(),spec_kind:e.enum(["once","interval","cron"]),spec_summary:e.string().optional(),body:e.string().optional(),actual_fire_at:e.number(),planned_fire_at:e.number().nullable(),missed_count:e.number(),next_fire_at:e.number().nullable()});var wu=e.enum(["user","agent","system"]),bS=e.object({subtype:e.literal("thread_anchor"),quoted_message_id:e.string(),quoted_conversation_id:e.string(),quoted_channel_name:e.string(),quoted_content:e.string(),quoted_from_kind:wu,quoted_from_agent_id:e.string().nullable(),quoted_from_user_id:e.string().nullable(),quoted_agent_name:e.string().nullable(),quoted_created_at:e.number()});var SS=e.object({subtype:e.literal("child_context"),parent_conversation_id:e.string(),parent_title:e.string(),summary:e.string()});var xS=e.object({subtype:e.literal("channel_context"),source_conversation_id:e.string(),source_conversation_title:e.string().optional(),created_by_agent_id:e.string(),created_by_agent_name:e.string().optional()});var kS=e.object({subtype:e.literal("rename"),old_name:e.string(),new_name:e.string(),scope:e.enum(["workspace","conversation"]).default("workspace")});import{readFile as Du}from"node:fs/promises";import{basename as Lu,isAbsolute as ju}from"node:path";var Ru=["not_found","forbidden","capability_denied","unauthorized","validation_error","conflict","rate_limited","upstream_unavailable","internal"],u=class extends Error{code;subkind;retriable;details;constructor(t){super(t.message),this.code=t.code,this.subkind=t.subkind,this.retriable=t.retriable,this.details=t.details}toPayload(){return{code:this.code,...this.subkind?{subkind:this.subkind}:{},message:this.message,retriable:this.retriable,...this.details?{details:this.details}:{}}}};function de(n,t){let r=Tu(t);if(r?.code&&Ru.includes(r.code)){let a=r.code;return new u({code:a,message:r.message??Ya(a),retriable:Va(a),...r.details?{details:r.details}:{}})}let s=Cu(n);return new u({code:s,message:r?.message??Au(n,s),retriable:Va(s),...r?.details?{details:r.details}:{}})}function pt(n){let t=n instanceof Error?n.message:String(n);return new u({code:"upstream_unavailable",message:`cannot reach silverhand backend: ${t}`,retriable:!0})}function Ga(n){if(n instanceof u)return n;if(Pu(n))return new u({code:"validation_error",message:Ou(n),retriable:!1});let t=n instanceof Error?n.message:String(n);return new u({code:"internal",message:`internal cli error: ${t}`,retriable:!1})}function Ka(n){switch(n){case"unauthorized":case"forbidden":case"capability_denied":return 3;case"rate_limited":case"upstream_unavailable":return 2;default:return 1}}function Za(n,t={json:!0}){let r=t.stderr??process.stderr;if(t.json){r.write(JSON.stringify({error:n.toPayload()})+`
|
|
10
10
|
`);return}let s=n.subkind?`${n.code}/${n.subkind}`:n.code;r.write(`silverhand: ${s}: ${n.message}
|
|
11
|
-
`);let
|
|
12
|
-
`)}}function bu(n){if(!n)return null;let t=n.blocking_tasks;if(!Array.isArray(t))return null;let r=[];for(let s of t){if(!s||typeof s!="object")continue;let o=s,a=typeof o.task_number=="number"?o.task_number:null,i=typeof o.status=="string"?o.status:null;a===null||i===null||r.push({task_number:a,status:i,title:typeof o.title=="string"?o.title:"",assignee_name:typeof o.assignee_name=="string"?o.assignee_name:null})}return r}function Su(n){return n===400||n===422?"validation_error":n===401?"unauthorized":n===403?"forbidden":n===404?"not_found":n===409?"conflict":n===429?"rate_limited":n>=500&&n<600?"upstream_unavailable":n>=400&&n<500?"validation_error":"internal"}function qo(n){return n==="rate_limited"||n==="upstream_unavailable"}function Ko(n){switch(n){case"not_found":return"resource not found";case"forbidden":return"forbidden";case"capability_denied":return"missing a required workspace capability";case"unauthorized":return"auth token rejected by backend";case"validation_error":return"request rejected: invalid input";case"conflict":return"request conflicts with current state";case"rate_limited":return"rate limited; back off and retry";case"upstream_unavailable":return"silverhand backend is unreachable";case"internal":return"silverhand backend reported an internal error"}}function xu(n,t){return`${Ko(t)} (HTTP ${n})`}function ku(n){if(!n)return null;try{let t=JSON.parse(n);if(t&&typeof t=="object"){let r=t,s=r.error&&typeof r.error=="object"?r.error:r,o=typeof s.code=="string"?s.code:void 0,a=typeof s.message=="string"?s.message:void 0,i=s.details&&typeof s.details=="object"?s.details:void 0;if(o||a||i)return{code:o,message:a,details:i}}}catch{}return null}function wu(n){return!!n&&typeof n=="object"&&"name"in n&&n.name==="ZodError"&&Array.isArray(n.errors)}function Ru(n){let t=n.errors[0];return t?`invalid argument \`${t.path.length>0?t.path.join("."):"<root>"}\`: ${t.message}`:"request rejected: invalid input"}function wr(n=process.env){let t=[],r=n[Sr],s=n[xr],o=n[yn],a=n[kr],i=n[Ho],c=n[$o];if(r||t.push(Sr),s||t.push(xr),o||t.push(yn),a||t.push(kr),t.length>0)throw new u({code:"validation_error",message:`silverhand CLI is missing required env: ${t.join(", ")}`,retriable:!1});try{new URL(o)}catch{throw new u({code:"validation_error",message:`${yn} is not a valid URL: ${o}`,retriable:!1})}return{conversationId:r,agentId:s,serverUrl:o,authToken:a,...i?{daemonSocketPath:i}:{},...c?{lastDeliveredSeqFile:c}:{}}}function Zo(n=process.env){try{return wr(n)}catch{return null}}var Eu=50,Rr=!1;function ht(){Rr=!0}function Yo(){return Rr}async function Jo(n){if(Rr)return;let t=Zo();if(!t)return;let r={...n,...n.error_message?{error_message:Cu(n.error_message)}:{}},s=`${t.serverUrl}${C.agentCliTrace(t.conversationId,t.agentId)}`,o=new AbortController,a=setTimeout(()=>o.abort(),Eu);try{await fetch(s,{method:"POST",headers:{[mt]:`Bearer ${t.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli-trace","Content-Type":"application/json"},body:JSON.stringify(r),signal:o.signal})}catch{}finally{clearTimeout(a)}}function Cu(n){let t=n;return t=t.replace(/(\B\/)(?:[\w.@%+\-]+\/)*[\w.@%+\-]+/g,"<path>"),t=t.replace(/[A-Za-z]:[\\/](?:[^\s:"']+[\\/])*[^\s:"']+/g,"<path>"),t=t.replace(/"[^"]*"/g,'"<value>"'),t=t.replace(/'[^']*'/g,"'<value>'"),t=t.replace(/(--[a-z][a-z0-9-]*)\s+(?!-)[^\s]+/g,"$1 <value>"),t.length>500&&(t=t.slice(0,500)),t}var bn=class{constructor(t){this.env=t}env;headers(){return{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli","Content-Type":"application/json"}}async request(t,r,s,o){ht();let a=o?Ou(o):"",i=`${this.env.serverUrl}${r}${a}`,c;try{c=await fetch(i,{method:t,headers:this.headers(),body:s===void 0?void 0:JSON.stringify(s)})}catch(d){throw pt(d)}if(!c.ok){let d=await Dt(c);throw de(c.status,d)}return await c.json()}sendMessage(t){return this.request("POST",C.agentSendConversationMessage(this.env.conversationId,this.env.agentId),t)}resolveStaleMessage(t){return this.request("POST",C.agentResolveStaleMessage(this.env.conversationId,this.env.agentId),t)}reactToMessage(t){return this.request(t.remove?"DELETE":"POST",C.agentReactMessage(this.env.conversationId,this.env.agentId),{message_id:t.message_id,emoji:t.emoji})}followThread(t){return this.request("POST",C.agentFollowThread(this.env.conversationId,this.env.agentId),t)}unfollowThread(t){return this.request("POST",C.agentUnfollowThread(this.env.conversationId,this.env.agentId),t)}createChannel(t){return this.request("POST",C.agentCreateChannel(this.env.conversationId,this.env.agentId),t)}addConversationMember(t){return this.request("POST",C.agentAddConversationMember(this.env.conversationId,this.env.agentId),t)}readHistory(t){return this.request("POST",C.agentReadHistory(this.env.conversationId,this.env.agentId),t)}listWorkspaces(){return this.request("GET",C.agentListWorkspaces(this.env.conversationId,this.env.agentId))}listChannels(t={}){return this.request("GET",C.agentListChannels(this.env.conversationId,this.env.agentId),void 0,{workspace_id:t.workspace_id})}searchMessages(t){return this.request("POST",C.agentSearchMessages(this.env.conversationId,this.env.agentId),t)}listTasks(t){return this.request("GET",C.agentListConversationTasks(this.env.conversationId,this.env.agentId),void 0,{workspace_id:t.workspace_id,conversation_id:t.conversation_id,status:t.status,task_number:t.task_number,assignee_id:t.assignee_id,limit:t.limit})}createTasks(t){return this.request("POST",C.agentCreateConversationTasks(this.env.conversationId,this.env.agentId),t)}claimTasks(t){return this.request("POST",C.agentClaimConversationTasks(this.env.conversationId,this.env.agentId),t)}unclaimTask(t){return this.request("POST",C.agentUnclaimConversationTask(this.env.conversationId,this.env.agentId),t)}updateTaskStatus(t){return this.request("POST",C.agentUpdateConversationTaskStatus(this.env.conversationId,this.env.agentId),t)}createSchedule(t){return this.request("POST",C.agentScheduleCreate(this.env.conversationId,this.env.agentId),t)}listSchedules(t){return this.request("POST",C.agentScheduleList(this.env.conversationId,this.env.agentId),t)}cancelSchedule(t){return this.request("POST",C.agentScheduleCancel(this.env.conversationId,this.env.agentId),t)}getProfileMcp(){return this.request("GET",C.agentProfileMcpGet(this.env.conversationId,this.env.agentId))}async setProfileMcp(t){ht();let r=this.env.serverUrl+C.agentProfileMcpSet(this.env.conversationId,this.env.agentId),s;try{s=await fetch(r,{method:"POST",headers:this.headers(),body:t})}catch(o){throw pt(o)}if(!s.ok){let o=await Dt(s);throw de(s.status,o)}return await s.json()}probeProfileMcp(t,r){return this.request("POST",C.agentProfileMcpProbe(this.env.conversationId,this.env.agentId),{server_name:t,include_tools:r})}getProfile(){return this.request("GET",C.agentProfileGet(this.env.conversationId,this.env.agentId))}async updateProfile(t){ht();let r=this.env.serverUrl+C.agentProfileUpdate(this.env.conversationId,this.env.agentId),s=new FormData;if(t.display_name!==void 0&&s.append("display_name",t.display_name),t.description!==void 0&&s.append("description",t.description),t.avatar?.action==="set"){s.append("avatar_action","set");let a=new Blob([t.avatar.buffer],{type:t.avatar.contentType});s.append("file",a,t.avatar.filename)}else t.avatar?.action==="clear"&&s.append("avatar_action","clear");let o;try{o=await fetch(r,{method:"POST",headers:{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli"},body:s})}catch(a){throw pt(a)}if(!o.ok){let a=await Dt(o);throw de(o.status,a)}return await o.json()}async uploadAttachment(t){if(!Pu(t.path))throw new u({code:"validation_error",message:"file upload --path must be absolute",retriable:!1});let r;try{r=await Au(t.path)}catch(c){throw new u({code:"not_found",message:`cannot read file at ${t.path}: ${c instanceof Error?c.message:String(c)}`,retriable:!1})}let s=this.env.serverUrl+C.agentUploadAttachment(this.env.conversationId,this.env.agentId),o=new FormData,a=new Blob([r],{type:t.contentType??""});o.append("file",a,t.filename??Tu(t.path));let i;ht();try{i=await fetch(s,{method:"POST",headers:{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli"},body:o})}catch(c){throw pt(c)}if(!i.ok){let c=await Dt(i);throw de(i.status,c)}return await i.json()}locateAttachment(t){return this.request("GET",C.agentLocateAttachment(this.env.conversationId,this.env.agentId,t))}async downloadAttachment(t){ht();let r=this.env.serverUrl+C.agentDownloadAttachment(this.env.conversationId,this.env.agentId,t),s;try{s=await fetch(r,{method:"GET",headers:this.headers()})}catch(a){throw pt(a)}if(!s.ok){let a=await Dt(s);throw de(s.status,a)}return{buffer:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}};async function Dt(n){try{return await n.text()}catch{return""}}function Ou(n){let t=[];for(let[r,s]of Object.entries(n))if(s!==void 0)if(Array.isArray(s)){if(s.length===0)continue;for(let o of s)t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(o))}`)}else t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(s))}`);return t.length===0?"":`?${t.join("&")}`}import{randomBytes as bm}from"node:crypto";var Se=3;var ta=e.object({}).strict(),qe=e.object({protocol_version:e.number().int().positive(),daemon_version:e.string(),daemon_id:e.string().min(1),instance_id:e.string().min(1),host_descriptor:e.object({name:e.string().min(1),kind:rn}).strict(),capabilities:e.array(e.string())}).strict(),Iu=e.object({}).strict(),Mu=e.object({pong:e.literal(!0),daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int()}),Du=e.object({}).strict(),Lu=e.object({daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int(),uptime_ms:e.number().int(),intent_count:e.number().int(),runtimes:e.array(e.unknown())}),ju=e.object({message:e.string()}).strict(),Nu=e.object({echoed:e.string()}).strict(),Cr=e.object({}).strict(),Ar=e.object({os:e.string().min(1),os_arch:e.string().optional(),daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int(),uptime_ms:e.number().int(),active_agent_ids:e.array(e.string())}).strict(),Fu=e.discriminatedUnion("enabled",[e.object({conversation_id:e.string().min(1),enabled:e.literal(!0),expires_at:e.number().int().positive()}).strict(),e.object({conversation_id:e.string().min(1),enabled:e.literal(!1)}).strict()]),zu=e.object({ok:e.literal(!0),enabled:e.boolean(),expires_at:e.number().int().positive().nullable()}).strict(),na=e.object({ok:e.literal(!1),status:e.number().int().positive(),body_text:e.string()}).strict(),$u=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),content:e.string(),target:gr.optional(),reply_to_message_id:e.string().min(1).optional(),attachment_ids:e.array(e.string().min(1)).optional(),stale_resolution_reason:_r.optional(),freshness_bypass:e.boolean().optional()}).strict(),Hu=e.union([e.object({ok:e.literal(!0),message_id:e.string().min(1),message_seq:e.number().int().nonnegative().optional(),thread_root_id:e.string().min(1).nullable().optional()}).strict(),na]),Uu=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),stale_event_id:e.string().min(1).optional(),resolution_reason:e.literal("obsolete")}).strict(),Wu=e.union([e.object({ok:e.literal(!0),resolved:e.literal(!0)}).strict(),e.object({ok:e.literal(!0),resolved:e.literal(!1),reason:e.literal("no_pending_stale_event")}).strict(),na]),qu=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),thread_root_id:e.string().min(1),observed_seq:e.number().int().nonnegative(),reply_target_messages:e.array(e.string().min(1)).min(1)}).strict(),Bu=e.object({ok:e.literal(!0)}).strict(),Tr=e.string().min(1),Vu=e.object({command:e.string().min(1),args:e.array(e.string()),env_vars:e.record(e.string()).optional()}).strict(),Xo=e.object({id:e.string().min(1),name:e.string().min(1),kind:ne}).strict(),Gu=e.object({id:e.string().min(1),name:e.string().min(1)}).strict(),Ku=e.object({kind:F,cli_session_id:e.string().min(1).nullable(),model:e.string().nullable(),reasoning_effort:lt.nullable(),fast_mode:e.boolean().nullable()}).strict(),Zu=e.object({conversation_id:e.string().min(1),kind:V,title:e.string(),spawned_by_agent_id:e.string().min(1).nullable(),members:e.array(hr)}).strict(),Yu=e.object({silverhand:e.object({auth_token:e.string().min(1)}).strict(),silverhand_cli:Vu.optional()}).strict(),Ju=new Set(["cwd","workspace_path","home_dir","system_prompt_path","spawn_dir","system_prompt","system_prompt_text","memory_text","consensus_text","env"]);function Er(n,t,r=[]){if(!(n===null||typeof n!="object")){if(Array.isArray(n)){n.forEach((s,o)=>Er(s,t,[...r,o]));return}for(let[s,o]of Object.entries(n)){let a=[...r,s];Ju.has(s)&&t.addIssue({code:"custom",path:a,message:`runtime_start.options.${a.join(".")} is forbidden by the D2.0 path/byte boundary; daemon-host must derive cwd/spawn paths/prompt bytes/env locally.`}),Er(o,t,a)}}}var Xu=e.object({agent:Gu,workspace:Xo,workspace_memory_index:e.array(Xo),session:Zu,driver:Ku,env_policy:Yu}).strict().superRefine((n,t)=>Er(n,t)),Qu=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),pid:e.number().int().nullable(),phase:e.enum(["idle","spawning","startup_pending","ready","draining","exited"]),run_state:dt.nullable(),started_at:e.number().int().nullable()}),ra=e.object({delivery_id:e.number().int(),message_id:e.string().min(1),seq:e.number().int().nonnegative(),thread_root_id:e.string().min(1).nullable(),delivery_kind:e.enum(["turn","observe"])}).strict(),Pr=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),options:Xu,startup_delivery:e.object({delivery_ids:e.array(e.number().int()).min(1),delivered_up_to_seq:e.number().int().nonnegative().optional(),deliveries:e.array(ra).optional(),text:Tr}).strict().optional()}).strict(),Or=e.discriminatedUnion("started",[e.object({started:e.literal(!0),pid:e.number().int(),started_at:e.number().int(),startup_delivery_accepted:e.boolean().optional()}).strict(),e.object({started:e.literal(!1),reason:e.literal("init_cooldown"),cooldown_until:e.number().int().positive()}).strict()]),Ir=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),mode:e.enum(["soft","hard"]),soft_directive:Tr.optional()}).strict().superRefine((n,t)=>{n.mode==="hard"&&n.soft_directive!==void 0&&t.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is only valid when mode === 'soft'; hard mode kills the process and ignores stdin."}),n.mode==="soft"&&n.soft_directive===void 0&&t.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)."})}),Mr=e.discriminatedUnion("mode",[e.object({mode:e.literal("hard"),stopped:e.boolean(),exit_code:e.number().int().nullable()}).strict(),e.object({mode:e.literal("soft"),directive_delivered:e.boolean(),reason:e.enum(["not_running","write_failed","driver_refused"]).optional()}).strict()]).superRefine((n,t)=>{n.mode==="soft"&&(n.directive_delivered===!1&&n.reason===void 0&&t.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=false must carry a typed reason ('not_running' | 'write_failed' | 'driver_refused')"}),n.directive_delivered===!0&&n.reason!==void 0&&t.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=true must not carry a reason"}))}),Dr=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),delivered_up_to_seq:e.number().int().nonnegative().optional(),deliveries:e.array(ra).optional(),kind:e.enum(["message","schedule_fire"]),text:Tr}).strict(),em=e.enum(["not_running","not_initialized","startup_pending","draining","driver_not_ready","driver_refused"]),Lr=e.union([e.object({delivered:e.literal(!0),delivery_ids:e.array(e.number().int()).min(1)}).strict(),e.object({delivered:e.literal(!1),reason:em,delivery_ids:e.array(e.number().int()).min(1)}).strict()]),jr=e.object({conversation_id:e.string().min(1).optional(),agent_id:e.string().min(1).optional()}).strict(),Nr=e.object({runtimes:e.array(Qu)}).strict(),Fr=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),zr=e.object({cleared:e.boolean()}).strict(),$r=e.object({}).strict(),Hr=e.object({stopped_count:e.number().int().nonnegative()}).strict(),Ur=e.object({}).strict(),Wr=e.object({flushed:e.boolean()}).strict(),Sn=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),qr=e.object({paused:e.boolean()}).strict(),Br=Sn,Vr=e.object({resumed:e.boolean()}).strict(),tm=e.object({config_path:e.string().min(1)}).strict(),nm=e.enum(["path_not_absolute","path_not_found","path_not_a_file","parse_failed","invalid_server_url"]),rm=e.discriminatedUnion("attached",[e.object({attached:e.literal(!0),config_path:e.string().min(1),action:e.enum(["started","switched","noop"])}).strict(),e.object({attached:e.literal(!1),reason:nm,message:e.string().optional()}).strict()]),sm=e.object({}).strict(),om=e.object({detached:e.literal(!0),action:e.enum(["detached","noop"])}).strict(),am=e.object({}).strict(),im=e.enum(["not_attached","config_unreadable","parse_failed","invalid_server_url"]),cm=e.discriminatedUnion("reloaded",[e.object({reloaded:e.literal(!0),action:e.enum(["reloaded","unchanged"]),config_path:e.string().min(1),host_id:e.string().min(1)}).strict(),e.object({reloaded:e.literal(!1),reason:im,message:e.string().optional()}).strict()]),sa=pr,xn=e.object({}).strict(),Lt=e.object({config:sa}).strict(),kn=sa,wn=Lt,jt=e.object({agent_id:e.string().min(1),agent_home_workspace_id:e.string().min(1),name:e.string().min(1).max(64),runtime:F,model:e.string().nullable().optional(),description:e.string().nullable().optional(),template_choice:e.enum(["default","onboarding","minimal"]).default("default")}).strict(),Nt=e.object({ok:e.literal(!0),agent_dir:e.string().min(1),agent_home_workspace_path:e.string().min(1),materialized_at:e.number().int().positive()}).strict().superRefine((n,t)=>{n.agent_home_workspace_path!==n.agent_dir&&t.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)"})}),Ft=e.enum(["fs_quota_exceeded","fs_unavailable","agent_dir_collision","unsupported_template","unsupported_runtime","internal_error"]),se=e.enum(["unknown_intent","invalid_params","internal_error","shutting_down","request_too_large"]),lm=e.object({code:e.union([se,Ft]),message:e.string()}).strict(),Rn=e.enum(["workspace_not_provisioned","workspace_path_missing","registry_unavailable"]),dm=e.object({code:e.union([se,Rn]),message:e.string()}).strict(),En=e.object({workspace_id:e.string().min(1),kind:ne,requested_path:e.string().min(1).optional()}).strict(),Cn=e.object({ok:e.literal(!0),provisioned:e.boolean(),bound_workspace_path:e.string().min(1)}).strict(),An=e.enum(["unsupported_kind","invalid_path","path_conflict","fs_quota_exceeded","fs_unavailable","registry_unavailable","internal_error"]),um=e.object({code:e.union([se,An]),message:e.string()}).strict(),Tn=e.object({agent_id:e.string().min(1),workspace_ids:e.array(e.string().min(1))}).strict(),mm=e.object({workspace_id:e.string().min(1),agent_dir:e.string().min(1)}).strict(),Pn=e.object({ok:e.literal(!0),entries:e.array(mm),unresolved:e.array(e.string().min(1))}).strict(),On=e.enum(["registry_unavailable","internal_error"]),pm=e.object({code:e.union([se,On]),message:e.string()}).strict(),Gr=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1).optional()}).strict(),Kr=e.object({ok:e.literal(!0),tree:ho}).strict(),Zr=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1).optional(),path:e.string().min(1)}).strict(),Yr=e.object({ok:e.literal(!0),file:fo}).strict(),Jr=e.enum(["forbidden_path","not_found","workspace_not_provisioned","registry_unavailable","fs_unavailable","internal_error"]),Qo=e.object({code:e.union([se,Jr]),message:e.string()}).strict(),In=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1),template_choice:e.enum(["default","onboarding","minimal"]).default("default")}).strict(),Mn=e.object({ok:e.literal(!0),seeded:e.boolean(),l2_present:e.boolean()}).strict(),Dn=e.enum(["workspace_not_provisioned","registry_unavailable","unsupported_template","fs_unavailable","internal_error"]),hm=e.object({code:e.union([se,Dn]),message:e.string()}).strict(),Ln=e.object({agent_id:e.string().min(1),scope:e.enum(["all","l2"]),workspace_ids:e.array(e.string().min(1)).default([])}).strict(),jn=e.object({ok:e.literal(!0),purged_count:e.number().int().nonnegative(),skipped_unprovisioned:e.number().int().nonnegative()}).strict(),Nn=e.enum(["partial_purge","registry_unavailable","internal_error"]),fm=e.object({code:e.union([se,Nn]),message:e.string()}).strict(),Fn=e.object({agent_id:e.string().min(1)}).strict(),zn=e.object({ok:e.literal(!0),raw:e.string().nullable()}).strict(),$n=e.object({agent_id:e.string().min(1),raw:e.string()}).strict(),Hn=e.object({ok:e.literal(!0),bytes_written:e.number().int().nonnegative()}).strict(),Un=e.enum(["invalid_config","fs_unavailable","internal_error"]),ea=e.object({code:e.union([se,Un]),message:e.string()}).strict(),gm=e.discriminatedUnion("kind",[e.object({kind:e.literal("profile"),agent_id:e.string().min(1)}).strict()]),Xr=e.object({source:gm,server_name:e.string().min(1),include_tools:e.boolean().optional()}).strict(),Qr=e.enum(["fs_unavailable","internal_error"]),_m=e.object({code:e.union([se,Qr]),message:e.string()}).strict(),Wn={hello:{params:ta,result:qe},ping:{params:Iu,result:Mu},status:{params:Du,result:Lu},echo:{params:ju,result:Nu},host_status:{params:Cr,result:Ar},conversation_log_debug:{params:Fu,result:zu},agent_message_send:{params:$u,result:Hu},agent_stale_resolve:{params:Uu,result:Wu},agent_stream_observed:{params:qu,result:Bu},runtime_start:{params:Pr,result:Or,error:dm},runtime_stop:{params:Ir,result:Mr},runtime_wake:{params:Dr,result:Lr},runtime_status:{params:jr,result:Nr},runtime_clear_session:{params:Fr,result:zr},runtime_stop_all:{params:$r,result:Hr},runtime_close_activity_log:{params:Ur,result:Wr},runtime_output_pause:{params:Sn,result:qr},runtime_output_resume:{params:Br,result:Vr},host_outbound_attach:{params:tm,result:rm},host_outbound_detach:{params:sm,result:om},host_outbound_reload:{params:am,result:cm},host_proxy_config_get:{params:xn,result:Lt},host_proxy_config_set:{params:kn,result:wn},agent_materialize:{params:jt,result:Nt,error:lm},workspace_provision:{params:En,result:Cn,error:um},agent_workspace_index:{params:Tn,result:Pn,error:pm},agent_workspace_tree:{params:Gr,result:Kr,error:Qo},agent_workspace_file_read:{params:Zr,result:Yr,error:Qo},agent_l2_seed:{params:In,result:Mn,error:hm},agent_files_purge:{params:Ln,result:jn,error:fm},agent_profile_mcp_read:{params:Fn,result:zn,error:ea},agent_profile_mcp_write:{params:$n,result:Hn,error:ea},mcp_probe:{params:Xr,result:vn,error:_m}};function es(n){let r=Wn[n]?.error;return r||T}var ts=e.object({id:e.string().min(1),intent:e.string().min(1),params:e.unknown()}),T=e.object({code:se,message:e.string()}),oa=e.union([e.object({id:e.string().min(1),result:e.unknown()}).strict(),e.object({id:e.string().min(1),error:T}).strict()]),ym=e.object({code:e.string().min(1),message:e.string()}).strict(),aa=e.union([e.object({id:e.string().min(1),result:e.unknown()}).strict(),e.object({id:e.string().min(1),error:ym}).strict()]),qn=e.discriminatedUnion("event",[qe.extend({event:e.literal("ready"),socket_path:e.string(),daemon_pid:e.number().int(),started_at:e.number().int()}),e.object({event:e.literal("shutting_down"),reason:e.string()}),e.object({event:e.literal("runtime_state"),conversation_id:e.string().min(1),agent_id:e.string().min(1),state:dt,ts:e.number().int()}),e.object({event:e.literal("runtime_output"),conversation_id:e.string().min(1),agent_id:e.string().min(1),stream:e.enum(["stdout","stderr"]),chunk:e.string(),ts:e.number().int()}),e.object({event:e.literal("runtime_exit"),conversation_id:e.string().min(1),agent_id:e.string().min(1),code:e.number().int().nullable(),intentional:e.boolean(),ts:e.number().int()}),e.object({event:e.literal("runtime_ready_for_drain"),conversation_id:e.string().min(1),agent_id:e.string().min(1),ts:e.number().int()}),e.object({event:e.literal("runtime_startup_delivery_consumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),ts:e.number().int()}),e.object({event:e.literal("runtime_startup_delivery_failed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),reason:e.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_timeout"),conversation_id:e.string().min(1),agent_id:e.string().min(1),timeout_reason:e.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:e.number().int().nonnegative(),timeout_ms:e.number().int().nonnegative(),retrying:e.boolean(),retry_attempt:e.number().int().nonnegative(),max_retries:e.number().int().nonnegative(),cooldown_until:e.number().int().positive().optional(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_retrying"),conversation_id:e.string().min(1),agent_id:e.string().min(1),retry_attempt:e.number().int().positive(),max_retries:e.number().int().nonnegative(),delay_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_cooldown"),conversation_id:e.string().min(1),agent_id:e.string().min(1),cooldown_until:e.number().int().positive(),attempts_exhausted:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_compaction_stale"),conversation_id:e.string().min(1),agent_id:e.string().min(1),elapsed_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_output_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),dropped_count:e.number().int().nonnegative(),bytes_dropped:e.number().int().nonnegative(),since_ts:e.number().int()}),e.object({event:e.literal("runtime_output_paused"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}),e.object({event:e.literal("runtime_output_resumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}),e.object({event:e.literal("runtime_parsed_event"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed:gn,ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_parsed_event_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed_kind:_n,encoded_bytes:e.number().int().nonnegative(),reason:e.literal("frame_too_large"),ts:e.number().int()}).strict()]),ia=e.union([ts,oa,qn]),ns=e.union([ts,aa,qn]),We=1*1024*1024;function Bn(n){let t=JSON.stringify(n);if(Buffer.byteLength(t,"utf8")>We)throw new Error(`host frame exceeds MAX_FRAME_BYTES (${We})`);return`${t}
|
|
13
|
-
`}function ft(n,t){let r=n+t,s=[],
|
|
14
|
-
`,o);if(c===-1)break;let d=r.slice(o,c);if(o=c+1,d.length!==0){if(Buffer.byteLength(d,"utf8")>We)return a=!0,{frames:s,leftover:"",overflow:a};s.push(d)}}let i=r.slice(o);return Buffer.byteLength(i,"utf8")>We?{frames:s,leftover:"",overflow:!0}:{frames:s,leftover:i,overflow:a}}import{Socket as vm}from"node:net";var zt=class{socketPath;socket=null;connected=!1;disconnectFired=!1;buffer="";handlers={frame:new Set,disconnect:new Set,overflow:new Set};constructor(t){this.socketPath=t.socketPath}connect(){if(this.socket)throw new Error("transport already connected or in flight; create a new one");let t=new vm;return this.socket=t,t.setEncoding("utf8"),new Promise((r,s)=>{let o=i=>{t.off("connect",a),this.fireDisconnect(`connect_failed:${i.code??i.message}`),s(i)},a=()=>{t.off("error",o),this.connected=!0,this.attachStreamHandlers(t),r()};t.once("error",o),t.once("connect",a),t.connect(this.socketPath)})}write(t){if(!this.connected||!this.socket)return!1;try{return this.socket.write(t),!0}catch{return!1}}close(){if(!this.socket)return;let t=this.socket;this.socket=null,this.connected=!1;try{t.destroy()}catch{}this.fireDisconnect("local_close")}on(t,r){return this.handlers[t].add(r),()=>{this.handlers[t].delete(r)}}isConnected(){return this.connected}attachStreamHandlers(t){t.on("data",r=>{let s=typeof r=="string"?r:r.toString("utf8"),{frames:o,leftover:a,overflow:i}=ft(this.buffer,s);if(this.buffer=a,i){for(let c of this.handlers.overflow)c();t.destroy();return}for(let c of o)this.deliverFrame(c)}),t.once("end",()=>this.fireDisconnect("peer_end")),t.once("error",r=>{let s=r.code;this.fireDisconnect(`socket_error:${s??r.message}`)}),t.once("close",()=>this.fireDisconnect("socket_close"))}deliverFrame(t){let r;try{r=JSON.parse(t)}catch{return}let s=ns.safeParse(r);if(!s.success||"intent"in s.data)return;let o=s.data;for(let a of this.handlers.frame)a(o)}fireDisconnect(t){if(!this.disconnectFired){this.disconnectFired=!0,this.connected=!1;for(let r of this.handlers.disconnect)r(t)}}};var M=class extends Error{constructor(r,s){super(s);this.code=r;this.name="HostClientError"}code},Be=class extends M{expected;actual;daemonVersion;reason;cause;constructor(t){let r=t.actual===null?"missing":String(t.actual),s=t.daemonVersion??"unknown";super("protocol_mismatch",`daemon speaks host protocol_version=${r}; client expects ${t.expected}. Daemon version=${s}. Recovery: stop the stale silverhand-daemon and restart the app/CLI so client and daemon come from the same checkout/build.`),this.name="ProtocolVersionMismatchError",this.expected=t.expected,this.actual=t.actual,this.daemonVersion=t.daemonVersion,this.reason=t.reason,this.cause=t.cause}},Sm={info:()=>{},warn:()=>{},error:()=>{}},xm=ca([]);function ca(n){let t=new Set(n),r;return r=Object.freeze({get size(){return t.size},has(s){return t.has(s)},entries(){return t.entries()},keys(){return t.keys()},values(){return t.values()},[Symbol.iterator](){return t[Symbol.iterator]()},forEach(s,o){t.forEach(a=>s.call(o,a,a,r))}}),r}var Ve=class{transportFactory;requestTimeoutMs;initialBackoffMs;maxBackoffMs;logger;rng;pending=new Map;reconnectHandlers=new Set;eventHandlers=new Set;transport=null;closed=!1;readyPromise=null;readyResolve=null;readyReject=null;backoffMs;reconnectTimer=null;connectAttempted=!1;negotiatedProtocol=null;suppressNextDisconnect=!1;constructor(t){if(!t.transportFactory&&!t.socketPath)throw new Error("HostClient requires either socketPath or transportFactory");this.transportFactory=t.transportFactory??(()=>new zt({socketPath:t.socketPath})),this.requestTimeoutMs=t.requestTimeoutMs??5e3,this.initialBackoffMs=t.initialBackoffMs??250,this.maxBackoffMs=t.maxBackoffMs??3e4,this.logger=t.logger??Sm,this.rng=t.rng??Math.random,this.backoffMs=this.initialBackoffMs,this.resetReadyPromise()}async connect(){if(this.closed)throw new M("closed","client is closed");if(this.connectAttempted)return this.readyPromise;this.connectAttempted=!0;try{await this.openTransport()}catch(t){throw this.readyReject?.(t),t}}onReconnect(t){return this.reconnectHandlers.add(t),()=>{this.reconnectHandlers.delete(t)}}isConnected(){return this.transport?.isConnected()??!1}get negotiated(){return this.negotiatedProtocol}get capabilities(){return this.negotiatedProtocol?.capabilities??xm}async call(t,r){if(this.closed)throw new M("closed","client is closed");if(!this.transport||!this.transport.isConnected())throw new M("disconnected","host client is not connected");let s=bm(8).toString("base64url"),a=Bn({id:s,intent:t,params:r});return new Promise((i,c)=>{let d=setTimeout(()=>{this.pending.delete(s),c(new M("timeout",`intent ${t} timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);if(d.unref?.(),this.pending.set(s,{intent:t,timer:d,resolve:m=>i(m),reject:c}),!this.transport.write(a)){let m=this.pending.get(s);m&&(clearTimeout(m.timer),this.pending.delete(s)),c(new M("disconnected",`failed to write intent ${t}`))}})}ping(){return this.call("ping",{})}status(){return this.call("status",{})}echo(t){return this.call("echo",{message:t})}setConversationLogDebug(t){return this.call("conversation_log_debug",t)}agentMessageSend(t){return this.call("agent_message_send",t)}agentStaleResolve(t){return this.call("agent_stale_resolve",t)}agentStreamObserved(t){return this.call("agent_stream_observed",t)}runtimeStart(t){return this.call("runtime_start",t)}runtimeStop(t){return this.call("runtime_stop",t)}runtimeWake(t){return this.call("runtime_wake",t)}runtimeStatus(t={}){return this.call("runtime_status",t)}runtimeClearSession(t){return this.call("runtime_clear_session",t)}runtimeStopAll(){return this.call("runtime_stop_all",{})}runtimeCloseActivityLog(){return this.call("runtime_close_activity_log",{})}hostOutboundAttach(t){return this.call("host_outbound_attach",t)}hostOutboundDetach(){return this.call("host_outbound_detach",{})}hostOutboundReload(){return this.call("host_outbound_reload",{})}hostProxyConfigGet(){return this.call("host_proxy_config_get",{})}hostProxyConfigSet(t){return this.call("host_proxy_config_set",t)}subscribe(t){return this.eventHandlers.add(t),()=>{this.eventHandlers.delete(t)}}async close(){this.closed||(this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.rejectAllPending(new M("closed","client closed")),this.transport?.close(),this.transport=null)}async openTransport(){if(this.closed)return;let t=this.transportFactory();this.transport=t,t.on("frame",r=>this.handleFrame(r)),t.on("disconnect",r=>this.handleDisconnect(r)),t.on("overflow",()=>{this.logger.warn({},"daemon sent oversize frame; reconnecting"),t.close()}),await t.connect();try{await this.negotiateProtocol()}catch(r){throw this.negotiatedProtocol=null,this.transport===t&&(this.transport=null),this.suppressNextDisconnect=!0,t.close(),r}this.backoffMs=this.initialBackoffMs,this.readyResolve?.(),this.logger.info({},"host client connected")}async negotiateProtocol(){let t;try{t=await this.call("hello",{})}catch(r){throw r instanceof M&&r.code==="unknown_intent"?new Be({expected:Se,actual:null,daemonVersion:null,reason:"daemon_protocol_missing",cause:r}):r instanceof M&&r.code==="internal_error"?new Be({expected:Se,actual:null,daemonVersion:null,reason:"invalid_hello",cause:r}):r}if(t.protocol_version!==Se)throw new Be({expected:Se,actual:t.protocol_version,daemonVersion:t.daemon_version,reason:"version_mismatch"});this.negotiatedProtocol=Object.freeze({protocolVersion:t.protocol_version,daemonVersion:t.daemon_version,daemonId:t.daemon_id,instanceId:t.instance_id,hostDescriptor:{...t.host_descriptor},capabilities:ca(t.capabilities)})}handleFrame(t){if("event"in t){t.event==="shutting_down"?this.logger.info({reason:t.reason},"daemon notified shutdown"):t.event==="ready"&&this.logger.info({daemon_pid:t.daemon_pid,daemon_version:t.daemon_version,daemon_id:t.daemon_id,instance_id:t.instance_id,started_at:t.started_at},"daemon ready handshake");for(let o of this.eventHandlers)try{o(t)}catch(a){this.logger.error({err:a.message,event:t.event},"event subscriber threw")}return}let r=this.pending.get(t.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(t.id),"error"in t){let a=es(r.intent).safeParse(t.error);if(a.success){r.reject(new M(a.data.code,a.data.message));return}let i=a.error.errors.map(c=>`${c.path.join(".")}: ${c.message}`).join("; ");this.logger.warn({intent:r.intent,received_code:t.error.code,issues:i},"host client received response error code that is not valid for intent"),r.reject(new M("internal_error",`drift: error code "${t.error.code}" for ${r.intent} is not in this intent's error taxonomy (${i})`));return}let s=Wn[r.intent];if(s){let o=s.result.safeParse(t.result);if(!o.success){let a=o.error.errors.map(i=>`${i.path.join(".")}: ${i.message}`).join("; ");this.logger.warn({intent:r.intent,issues:a},"host client received response that does not match intent schema"),r.reject(new M("internal_error",`drift: response for ${r.intent} failed schema validation (${a})`));return}r.resolve(o.data);return}r.resolve(t.result)}handleDisconnect(t){if(this.suppressNextDisconnect){this.suppressNextDisconnect=!1,this.transport=null;return}this.logger.warn({reason:t},"host client transport disconnected"),this.rejectAllPending(new M("disconnected",`transport disconnected: ${t}`)),this.transport=null,this.negotiatedProtocol=null,!this.closed&&(this.resetReadyPromise(),this.scheduleReconnect())}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let t=Math.max(this.initialBackoffMs,Math.floor(this.backoffMs*this.rng()));this.backoffMs=Math.min(this.maxBackoffMs,this.backoffMs*2),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.attemptReconnect()},t),this.reconnectTimer.unref?.(),this.logger.info({delay:t},"host client scheduling reconnect")}async attemptReconnect(){if(!this.closed)try{await this.openTransport();for(let t of this.reconnectHandlers)try{t()}catch(r){this.logger.error({err:r.message},"onReconnect handler threw")}}catch(t){if(t instanceof Be){this.closed=!0,this.readyReject?.(t),this.logger.error({expected:t.expected,actual:t.actual,daemon_version:t.daemonVersion,reason:t.reason},"host client protocol negotiation failed; reconnect disabled");return}this.logger.warn({err:t.message},"host client reconnect attempt failed; will retry"),this.scheduleReconnect()}}rejectAllPending(t){for(let[,r]of this.pending)clearTimeout(r.timer),r.reject(t);this.pending.clear()}resetReadyPromise(){this.readyPromise=new Promise((t,r)=>{this.readyResolve=t,this.readyReject=r}),this.readyPromise.catch(()=>{})}};import{execFile as km}from"node:child_process";import{promisify as wm}from"node:util";var bx=wm(km);var rs=e.string().min(1),os=2,ua=e.object({host_id:e.string().min(1),host_token:e.string().min(1),issued_at:e.number().int().nonnegative(),grace_until:e.number().int().positive()}).strict().superRefine((n,t)=>{n.grace_until<=n.issued_at&&t.addIssue({code:"custom",path:["grace_until"],message:"grace_until must be after issued_at"})}),ma=e.discriminatedUnion("rotated",[e.object({rotated:e.literal(!0),host_id:e.string().min(1),config_refreshed_at:e.number().int().nonnegative()}).strict(),e.object({rotated:e.literal(!1),reason:e.enum(["host_mismatch","invalid_config","write_failed"]),message:e.string().optional()}).strict()]),pa=e.object({code:e.union([T.shape.code,Ft]),message:e.string()}).strict(),Rm=e.object({code:e.union([T.shape.code,An]),message:e.string()}).strict(),Em=e.object({code:e.union([T.shape.code,On]),message:e.string()}).strict(),la=e.object({code:e.union([T.shape.code,Jr]),message:e.string()}).strict(),Cm=e.object({code:e.union([T.shape.code,Dn]),message:e.string()}).strict(),Am=e.object({code:e.union([T.shape.code,Nn]),message:e.string()}).strict(),da=e.object({code:e.union([T.shape.code,Un]),message:e.string()}).strict(),Tm=e.object({code:e.union([T.shape.code,Qr]),message:e.string()}).strict(),ha=e.object({code:e.union([T.shape.code,Rn]),message:e.string()}).strict(),$t={runtime_start:{params:Pr,result:Or,error:ha},runtime_stop:{params:Ir,result:Mr,error:T},runtime_wake:{params:Dr,result:Lr,error:T},runtime_status:{params:jr,result:Nr,error:T},runtime_clear_session:{params:Fr,result:zr,error:T},runtime_stop_all:{params:$r,result:Hr,error:T},runtime_close_activity_log:{params:Ur,result:Wr,error:T},runtime_output_pause:{params:Sn,result:qr,error:T},runtime_output_resume:{params:Br,result:Vr,error:T},rotate_token:{params:ua,result:ma,error:T},agent_materialize:{params:jt,result:Nt,error:pa},workspace_provision:{params:En,result:Cn,error:Rm},agent_workspace_index:{params:Tn,result:Pn,error:Em},agent_workspace_tree:{params:Gr,result:Kr,error:la},agent_workspace_file_read:{params:Zr,result:Yr,error:la},agent_l2_seed:{params:In,result:Mn,error:Cm},agent_files_purge:{params:Ln,result:jn,error:Am},agent_profile_mcp_read:{params:Fn,result:zn,error:da},agent_profile_mcp_write:{params:$n,result:Hn,error:da},mcp_probe:{params:Xr,result:vn,error:Tm},host_status:{params:Cr,result:Ar,error:T},host_proxy_config_get:{params:xn,result:Lt,error:T},host_proxy_config_set:{params:kn,result:wn,error:T}},as=Object.keys($t),Pm=as.map(n=>e.object({direction:e.literal("server_to_daemon"),type:e.literal("command"),id:rs,kind:e.literal(n),params:$t[n].params}).strict()),is=e.discriminatedUnion("kind",Pm),Om=as.flatMap(n=>[e.object({direction:e.literal("daemon_to_server"),type:e.literal("command_response"),id:rs,kind:e.literal(n),result:$t[n].result}).strict(),e.object({direction:e.literal("daemon_to_server"),type:e.literal("command_response"),id:rs,kind:e.literal(n),error:$t[n].error}).strict()]),cs=e.union(Om),ss=e.number().int().nonnegative(),fa=e.object({direction:e.enum(["server_to_daemon","daemon_to_server"]),type:e.literal("heartbeat"),kind:e.literal("ping"),ts:ss}).strict(),ga=e.object({direction:e.enum(["server_to_daemon","daemon_to_server"]),type:e.literal("heartbeat"),kind:e.literal("pong"),ts:ss,echo_ts:ss}).strict(),ls=e.discriminatedUnion("kind",[fa,ga]),_a=qe.extend({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("ready"),protocol_version:e.literal(os),daemon_pid:e.number().int(),started_at:e.number().int()}).strict(),Im=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("shutting_down"),reason:e.string()}).strict(),Mm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_state"),conversation_id:e.string().min(1),agent_id:e.string().min(1),state:dt,ts:e.number().int()}).strict(),Dm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output"),conversation_id:e.string().min(1),agent_id:e.string().min(1),stream:e.enum(["stdout","stderr"]),chunk:e.string(),ts:e.number().int()}).strict(),Lm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_exit"),conversation_id:e.string().min(1),agent_id:e.string().min(1),code:e.number().int().nullable(),intentional:e.boolean(),ts:e.number().int()}).strict(),jm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_ready_for_drain"),conversation_id:e.string().min(1),agent_id:e.string().min(1),ts:e.number().int()}).strict(),Nm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_startup_delivery_consumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),ts:e.number().int()}).strict(),Fm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_startup_delivery_failed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),reason:e.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:e.number().int()}).strict(),zm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_timeout"),conversation_id:e.string().min(1),agent_id:e.string().min(1),timeout_reason:e.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:e.number().int().nonnegative(),timeout_ms:e.number().int().nonnegative(),retrying:e.boolean(),retry_attempt:e.number().int().nonnegative(),max_retries:e.number().int().nonnegative(),cooldown_until:e.number().int().positive().optional(),ts:e.number().int()}).strict(),$m=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_retrying"),conversation_id:e.string().min(1),agent_id:e.string().min(1),retry_attempt:e.number().int().positive(),max_retries:e.number().int().nonnegative(),delay_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Hm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_cooldown"),conversation_id:e.string().min(1),agent_id:e.string().min(1),cooldown_until:e.number().int().positive(),attempts_exhausted:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Um=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_compaction_stale"),conversation_id:e.string().min(1),agent_id:e.string().min(1),elapsed_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Wm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),dropped_count:e.number().int().nonnegative(),bytes_dropped:e.number().int().nonnegative(),since_ts:e.number().int()}).strict(),qm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_paused"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Bm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_resumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Vm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_parsed_event"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed:gn,ts:e.number().int()}).strict(),Gm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_parsed_event_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed_kind:_n,encoded_bytes:e.number().int().nonnegative(),reason:e.literal("frame_too_large"),ts:e.number().int()}).strict(),ds=e.discriminatedUnion("kind",[_a,Im,Mm,Dm,Lm,jm,Nm,Fm,zm,$m,Hm,Um,Wm,qm,Bm,Vm,Gm]),Km=ds.options.map(n=>n.shape.kind.value),ya=e.union([is,cs,ls,ds]);var Ux=qe.pick({daemon_id:!0,host_descriptor:!0}).strict(),Zm=Object.freeze({daemon_id:"local",host_descriptor:Object.freeze({name:"local",kind:"local"})});var gh=fe(pi(),1),_h=fe(er(),1),yh=fe(yt(),1),vh=fe(Ss(),1),bh=fe(ws(),1),Sh=fe(Ps(),1),xh=fe(sr(),1),kh=fe(Si(),1);var wh={maxFrames:1024,maxBytes:4*1024*1024};var Ak=["# 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(`
|
|
15
|
-
`);var
|
|
11
|
+
`);let a=Eu(n.details);if(a&&a.length>0)for(let o of a){let i=o.assignee_name?` @${o.assignee_name}`:"",c=o.title?` \u2014 ${o.title}`:"";r.write(` #task:${o.task_number} (${o.status})${i}${c}
|
|
12
|
+
`)}}function Eu(n){if(!n)return null;let t=n.blocking_tasks;if(!Array.isArray(t))return null;let r=[];for(let s of t){if(!s||typeof s!="object")continue;let a=s,o=typeof a.task_number=="number"?a.task_number:null,i=typeof a.status=="string"?a.status:null;o===null||i===null||r.push({task_number:o,status:i,title:typeof a.title=="string"?a.title:"",assignee_name:typeof a.assignee_name=="string"?a.assignee_name:null})}return r}function Cu(n){return n===400||n===422?"validation_error":n===401?"unauthorized":n===403?"forbidden":n===404?"not_found":n===409?"conflict":n===429?"rate_limited":n>=500&&n<600?"upstream_unavailable":n>=400&&n<500?"validation_error":"internal"}function Va(n){return n==="rate_limited"||n==="upstream_unavailable"}function Ya(n){switch(n){case"not_found":return"resource not found";case"forbidden":return"forbidden";case"capability_denied":return"missing a required workspace capability";case"unauthorized":return"auth token rejected by backend";case"validation_error":return"request rejected: invalid input";case"conflict":return"request conflicts with current state";case"rate_limited":return"rate limited; back off and retry";case"upstream_unavailable":return"silverhand backend is unreachable";case"internal":return"silverhand backend reported an internal error"}}function Au(n,t){return`${Ya(t)} (HTTP ${n})`}function Tu(n){if(!n)return null;try{let t=JSON.parse(n);if(t&&typeof t=="object"){let r=t,s=r.error&&typeof r.error=="object"?r.error:r,a=typeof s.code=="string"?s.code:void 0,o=typeof s.message=="string"?s.message:void 0,i=s.details&&typeof s.details=="object"?s.details:void 0;if(a||o||i)return{code:a,message:o,details:i}}}catch{}return null}function Pu(n){return!!n&&typeof n=="object"&&"name"in n&&n.name==="ZodError"&&Array.isArray(n.errors)}function Ou(n){let t=n.errors[0];return t?`invalid argument \`${t.path.length>0?t.path.join("."):"<root>"}\`: ${t.message}`:"request rejected: invalid input"}function Er(n=process.env){let t=[],r=n[kr],s=n[wr],a=n[yn],o=n[Rr],i=n[Wa],c=n[Ua];if(r||t.push(kr),s||t.push(wr),a||t.push(yn),o||t.push(Rr),t.length>0)throw new u({code:"validation_error",message:`silverhand CLI is missing required env: ${t.join(", ")}`,retriable:!1});try{new URL(a)}catch{throw new u({code:"validation_error",message:`${yn} is not a valid URL: ${a}`,retriable:!1})}return{conversationId:r,agentId:s,serverUrl:a,authToken:o,...i?{daemonSocketPath:i}:{},...c?{lastDeliveredSeqFile:c}:{}}}function Ja(n=process.env){try{return Er(n)}catch{return null}}var Iu=50,Cr=!1;function ht(){Cr=!0}function Xa(){return Cr}async function Qa(n){if(Cr)return;let t=Ja();if(!t)return;let r={...n,...n.error_message?{error_message:Mu(n.error_message)}:{}},s=`${t.serverUrl}${C.agentCliTrace(t.conversationId,t.agentId)}`,a=new AbortController,o=setTimeout(()=>a.abort(),Iu);try{await fetch(s,{method:"POST",headers:{[mt]:`Bearer ${t.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli-trace","Content-Type":"application/json"},body:JSON.stringify(r),signal:a.signal})}catch{}finally{clearTimeout(o)}}function Mu(n){let t=n;return t=t.replace(/(\B\/)(?:[\w.@%+\-]+\/)*[\w.@%+\-]+/g,"<path>"),t=t.replace(/[A-Za-z]:[\\/](?:[^\s:"']+[\\/])*[^\s:"']+/g,"<path>"),t=t.replace(/"[^"]*"/g,'"<value>"'),t=t.replace(/'[^']*'/g,"'<value>'"),t=t.replace(/(--[a-z][a-z0-9-]*)\s+(?!-)[^\s]+/g,"$1 <value>"),t.length>500&&(t=t.slice(0,500)),t}var bn=class{constructor(t){this.env=t}env;headers(){return{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli","Content-Type":"application/json"}}async request(t,r,s,a){ht();let o=a?Nu(a):"",i=`${this.env.serverUrl}${r}${o}`,c;try{c=await fetch(i,{method:t,headers:this.headers(),body:s===void 0?void 0:JSON.stringify(s)})}catch(d){throw pt(d)}if(!c.ok){let d=await Dt(c);throw de(c.status,d)}return await c.json()}sendMessage(t){return this.request("POST",C.agentSendConversationMessage(this.env.conversationId,this.env.agentId),t)}resolveStaleMessage(t){return this.request("POST",C.agentResolveStaleMessage(this.env.conversationId,this.env.agentId),t)}reactToMessage(t){return this.request(t.remove?"DELETE":"POST",C.agentReactMessage(this.env.conversationId,this.env.agentId),{message_id:t.message_id,emoji:t.emoji})}followThread(t){return this.request("POST",C.agentFollowThread(this.env.conversationId,this.env.agentId),t)}unfollowThread(t){return this.request("POST",C.agentUnfollowThread(this.env.conversationId,this.env.agentId),t)}createChannel(t){return this.request("POST",C.agentCreateChannel(this.env.conversationId,this.env.agentId),t)}addConversationMember(t){return this.request("POST",C.agentAddConversationMember(this.env.conversationId,this.env.agentId),t)}readHistory(t){return this.request("POST",C.agentReadHistory(this.env.conversationId,this.env.agentId),t)}listWorkspaces(){return this.request("GET",C.agentListWorkspaces(this.env.conversationId,this.env.agentId))}listChannels(t={}){return this.request("GET",C.agentListChannels(this.env.conversationId,this.env.agentId),void 0,{workspace_id:t.workspace_id})}searchMessages(t){return this.request("POST",C.agentSearchMessages(this.env.conversationId,this.env.agentId),t)}listTasks(t){return this.request("GET",C.agentListConversationTasks(this.env.conversationId,this.env.agentId),void 0,{workspace_id:t.workspace_id,conversation_id:t.conversation_id,status:t.status,task_number:t.task_number,assignee_id:t.assignee_id,limit:t.limit})}createTasks(t){return this.request("POST",C.agentCreateConversationTasks(this.env.conversationId,this.env.agentId),t)}claimTasks(t){return this.request("POST",C.agentClaimConversationTasks(this.env.conversationId,this.env.agentId),t)}unclaimTask(t){return this.request("POST",C.agentUnclaimConversationTask(this.env.conversationId,this.env.agentId),t)}updateTaskStatus(t){return this.request("POST",C.agentUpdateConversationTaskStatus(this.env.conversationId,this.env.agentId),t)}createSchedule(t){return this.request("POST",C.agentScheduleCreate(this.env.conversationId,this.env.agentId),t)}listSchedules(t){return this.request("POST",C.agentScheduleList(this.env.conversationId,this.env.agentId),t)}cancelSchedule(t){return this.request("POST",C.agentScheduleCancel(this.env.conversationId,this.env.agentId),t)}getProfileMcp(){return this.request("GET",C.agentProfileMcpGet(this.env.conversationId,this.env.agentId))}async setProfileMcp(t){ht();let r=this.env.serverUrl+C.agentProfileMcpSet(this.env.conversationId,this.env.agentId),s;try{s=await fetch(r,{method:"POST",headers:this.headers(),body:t})}catch(a){throw pt(a)}if(!s.ok){let a=await Dt(s);throw de(s.status,a)}return await s.json()}probeProfileMcp(t,r){return this.request("POST",C.agentProfileMcpProbe(this.env.conversationId,this.env.agentId),{server_name:t,include_tools:r})}getProfile(){return this.request("GET",C.agentProfileGet(this.env.conversationId,this.env.agentId))}async updateProfile(t){ht();let r=this.env.serverUrl+C.agentProfileUpdate(this.env.conversationId,this.env.agentId),s=new FormData;if(t.display_name!==void 0&&s.append("display_name",t.display_name),t.description!==void 0&&s.append("description",t.description),t.avatar?.action==="set"){s.append("avatar_action","set");let o=new Blob([t.avatar.buffer],{type:t.avatar.contentType});s.append("file",o,t.avatar.filename)}else t.avatar?.action==="clear"&&s.append("avatar_action","clear");let a;try{a=await fetch(r,{method:"POST",headers:{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli"},body:s})}catch(o){throw pt(o)}if(!a.ok){let o=await Dt(a);throw de(a.status,o)}return await a.json()}async uploadAttachment(t){if(!ju(t.path))throw new u({code:"validation_error",message:"file upload --path must be absolute",retriable:!1});let r;try{r=await Du(t.path)}catch(c){throw new u({code:"not_found",message:`cannot read file at ${t.path}: ${c instanceof Error?c.message:String(c)}`,retriable:!1})}let s=this.env.serverUrl+C.agentUploadAttachment(this.env.conversationId,this.env.agentId),a=new FormData,o=new Blob([r],{type:t.contentType??""});a.append("file",o,t.filename??Lu(t.path));let i;ht();try{i=await fetch(s,{method:"POST",headers:{[mt]:`Bearer ${this.env.authToken}`,"X-Agent-Hub-Caller":"silverhand-cli"},body:a})}catch(c){throw pt(c)}if(!i.ok){let c=await Dt(i);throw de(i.status,c)}return await i.json()}locateAttachment(t){return this.request("GET",C.agentLocateAttachment(this.env.conversationId,this.env.agentId,t))}async downloadAttachment(t){ht();let r=this.env.serverUrl+C.agentDownloadAttachment(this.env.conversationId,this.env.agentId,t),s;try{s=await fetch(r,{method:"GET",headers:this.headers()})}catch(o){throw pt(o)}if(!s.ok){let o=await Dt(s);throw de(s.status,o)}return{buffer:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")??"application/octet-stream"}}};async function Dt(n){try{return await n.text()}catch{return""}}function Nu(n){let t=[];for(let[r,s]of Object.entries(n))if(s!==void 0)if(Array.isArray(s)){if(s.length===0)continue;for(let a of s)t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(a))}`)}else t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(s))}`);return t.length===0?"":`?${t.join("&")}`}import{randomBytes as Em}from"node:crypto";var Se=3;var ro=e.object({}).strict(),qe=e.object({protocol_version:e.number().int().positive(),daemon_version:e.string(),daemon_id:e.string().min(1),instance_id:e.string().min(1),host_descriptor:e.object({name:e.string().min(1),kind:rn}).strict(),capabilities:e.array(e.string())}).strict(),Fu=e.object({}).strict(),zu=e.object({pong:e.literal(!0),daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int()}),$u=e.object({}).strict(),Hu=e.object({daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int(),uptime_ms:e.number().int(),intent_count:e.number().int(),runtimes:e.array(e.unknown())}),Uu=e.object({message:e.string()}).strict(),Wu=e.object({echoed:e.string()}).strict(),Tr=e.object({}).strict(),Pr=e.object({os:e.string().min(1),os_arch:e.string().optional(),daemon_pid:e.number().int(),daemon_version:e.string(),started_at:e.number().int(),uptime_ms:e.number().int(),active_agent_ids:e.array(e.string())}).strict(),Sn=e.object({force:e.boolean().optional()}).strict(),xn=Sa,qu=e.discriminatedUnion("enabled",[e.object({conversation_id:e.string().min(1),enabled:e.literal(!0),expires_at:e.number().int().positive()}).strict(),e.object({conversation_id:e.string().min(1),enabled:e.literal(!1)}).strict()]),Bu=e.object({ok:e.literal(!0),enabled:e.boolean(),expires_at:e.number().int().positive().nullable()}).strict(),so=e.object({ok:e.literal(!1),status:e.number().int().positive(),body_text:e.string()}).strict(),Vu=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),content:e.string(),target:yr.optional(),reply_to_message_id:e.string().min(1).optional(),attachment_ids:e.array(e.string().min(1)).optional(),stale_resolution_reason:vr.optional(),freshness_bypass:e.boolean().optional()}).strict(),Gu=e.union([e.object({ok:e.literal(!0),message_id:e.string().min(1),message_seq:e.number().int().nonnegative().optional(),thread_root_id:e.string().min(1).nullable().optional()}).strict(),so]),Ku=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),stale_event_id:e.string().min(1).optional(),resolution_reason:e.literal("obsolete")}).strict(),Zu=e.union([e.object({ok:e.literal(!0),resolved:e.literal(!0)}).strict(),e.object({ok:e.literal(!0),resolved:e.literal(!1),reason:e.literal("no_pending_stale_event")}).strict(),so]),Yu=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),thread_root_id:e.string().min(1),observed_seq:e.number().int().nonnegative(),reply_target_messages:e.array(e.string().min(1)).min(1)}).strict(),Ju=e.object({ok:e.literal(!0)}).strict(),Or=e.string().min(1),Xu=e.object({command:e.string().min(1),args:e.array(e.string()),env_vars:e.record(e.string()).optional()}).strict(),eo=e.object({id:e.string().min(1),name:e.string().min(1),kind:ne}).strict(),Qu=e.object({id:e.string().min(1),name:e.string().min(1)}).strict(),em=e.object({kind:F,cli_session_id:e.string().min(1).nullable(),model:e.string().nullable(),reasoning_effort:lt.nullable(),fast_mode:e.boolean().nullable()}).strict(),tm=e.object({conversation_id:e.string().min(1),kind:V,title:e.string(),spawned_by_agent_id:e.string().min(1).nullable(),members:e.array(gr)}).strict(),nm=e.object({silverhand:e.object({auth_token:e.string().min(1)}).strict(),silverhand_cli:Xu.optional()}).strict(),rm=new Set(["cwd","workspace_path","home_dir","system_prompt_path","spawn_dir","system_prompt","system_prompt_text","memory_text","consensus_text","env"]);function Ar(n,t,r=[]){if(!(n===null||typeof n!="object")){if(Array.isArray(n)){n.forEach((s,a)=>Ar(s,t,[...r,a]));return}for(let[s,a]of Object.entries(n)){let o=[...r,s];rm.has(s)&&t.addIssue({code:"custom",path:o,message:`runtime_start.options.${o.join(".")} is forbidden by the D2.0 path/byte boundary; daemon-host must derive cwd/spawn paths/prompt bytes/env locally.`}),Ar(a,t,o)}}}var sm=e.object({agent:Qu,workspace:eo,workspace_memory_index:e.array(eo),session:tm,driver:em,env_policy:nm}).strict().superRefine((n,t)=>Ar(n,t)),am=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),pid:e.number().int().nullable(),phase:e.enum(["idle","spawning","startup_pending","ready","draining","exited"]),run_state:dt.nullable(),started_at:e.number().int().nullable()}),ao=e.object({delivery_id:e.number().int(),message_id:e.string().min(1),seq:e.number().int().nonnegative(),thread_root_id:e.string().min(1).nullable(),delivery_kind:e.enum(["turn","observe"])}).strict(),Ir=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),options:sm,startup_delivery:e.object({delivery_ids:e.array(e.number().int()).min(1),delivered_up_to_seq:e.number().int().nonnegative().optional(),deliveries:e.array(ao).optional(),text:Or}).strict().optional()}).strict(),Mr=e.discriminatedUnion("started",[e.object({started:e.literal(!0),pid:e.number().int(),started_at:e.number().int(),startup_delivery_accepted:e.boolean().optional()}).strict(),e.object({started:e.literal(!1),reason:e.literal("init_cooldown"),cooldown_until:e.number().int().positive()}).strict()]),Dr=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),mode:e.enum(["soft","hard"]),soft_directive:Or.optional()}).strict().superRefine((n,t)=>{n.mode==="hard"&&n.soft_directive!==void 0&&t.addIssue({code:"custom",path:["soft_directive"],message:"soft_directive is only valid when mode === 'soft'; hard mode kills the process and ignores stdin."}),n.mode==="soft"&&n.soft_directive===void 0&&t.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)."})}),Lr=e.discriminatedUnion("mode",[e.object({mode:e.literal("hard"),stopped:e.boolean(),exit_code:e.number().int().nullable()}).strict(),e.object({mode:e.literal("soft"),directive_delivered:e.boolean(),reason:e.enum(["not_running","write_failed","driver_refused"]).optional()}).strict()]).superRefine((n,t)=>{n.mode==="soft"&&(n.directive_delivered===!1&&n.reason===void 0&&t.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=false must carry a typed reason ('not_running' | 'write_failed' | 'driver_refused')"}),n.directive_delivered===!0&&n.reason!==void 0&&t.addIssue({code:"custom",path:["reason"],message:"soft result with directive_delivered=true must not carry a reason"}))}),jr=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),delivered_up_to_seq:e.number().int().nonnegative().optional(),deliveries:e.array(ao).optional(),kind:e.enum(["message","schedule_fire"]),text:Or}).strict(),om=e.enum(["not_running","not_initialized","startup_pending","draining","driver_not_ready","driver_refused"]),Nr=e.union([e.object({delivered:e.literal(!0),delivery_ids:e.array(e.number().int()).min(1)}).strict(),e.object({delivered:e.literal(!1),reason:om,delivery_ids:e.array(e.number().int()).min(1)}).strict()]),Fr=e.object({conversation_id:e.string().min(1).optional(),agent_id:e.string().min(1).optional()}).strict(),zr=e.object({runtimes:e.array(am)}).strict(),$r=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Hr=e.object({cleared:e.boolean()}).strict(),Ur=e.object({}).strict(),Wr=e.object({stopped_count:e.number().int().nonnegative()}).strict(),qr=e.object({}).strict(),Br=e.object({flushed:e.boolean()}).strict(),kn=e.object({conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Vr=e.object({paused:e.boolean()}).strict(),Gr=kn,Kr=e.object({resumed:e.boolean()}).strict(),im=e.object({config_path:e.string().min(1)}).strict(),cm=e.enum(["path_not_absolute","path_not_found","path_not_a_file","parse_failed","invalid_server_url"]),lm=e.discriminatedUnion("attached",[e.object({attached:e.literal(!0),config_path:e.string().min(1),action:e.enum(["started","switched","noop"])}).strict(),e.object({attached:e.literal(!1),reason:cm,message:e.string().optional()}).strict()]),dm=e.object({}).strict(),um=e.object({detached:e.literal(!0),action:e.enum(["detached","noop"])}).strict(),mm=e.object({}).strict(),pm=e.enum(["not_attached","config_unreadable","parse_failed","invalid_server_url"]),hm=e.discriminatedUnion("reloaded",[e.object({reloaded:e.literal(!0),action:e.enum(["reloaded","unchanged"]),config_path:e.string().min(1),host_id:e.string().min(1)}).strict(),e.object({reloaded:e.literal(!1),reason:pm,message:e.string().optional()}).strict()]),oo=fr,wn=e.object({}).strict(),Lt=e.object({config:oo}).strict(),Rn=oo,En=Lt,jt=e.object({agent_id:e.string().min(1),agent_home_workspace_id:e.string().min(1),name:e.string().min(1).max(64),runtime:F,model:e.string().nullable().optional(),description:e.string().nullable().optional(),template_choice:e.enum(["default","onboarding","minimal"]).default("default")}).strict(),Nt=e.object({ok:e.literal(!0),agent_dir:e.string().min(1),agent_home_workspace_path:e.string().min(1),materialized_at:e.number().int().positive()}).strict().superRefine((n,t)=>{n.agent_home_workspace_path!==n.agent_dir&&t.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)"})}),Ft=e.enum(["fs_quota_exceeded","fs_unavailable","agent_dir_collision","unsupported_template","unsupported_runtime","internal_error"]),se=e.enum(["unknown_intent","invalid_params","internal_error","shutting_down","request_too_large"]),fm=e.object({code:e.union([se,Ft]),message:e.string()}).strict(),Cn=e.enum(["workspace_not_provisioned","workspace_path_missing","registry_unavailable"]),gm=e.object({code:e.union([se,Cn]),message:e.string()}).strict(),An=e.object({workspace_id:e.string().min(1),kind:ne,requested_path:e.string().min(1).optional()}).strict(),Tn=e.object({ok:e.literal(!0),provisioned:e.boolean(),bound_workspace_path:e.string().min(1)}).strict(),Pn=e.enum(["unsupported_kind","invalid_path","path_conflict","fs_quota_exceeded","fs_unavailable","registry_unavailable","internal_error"]),_m=e.object({code:e.union([se,Pn]),message:e.string()}).strict(),On=e.object({agent_id:e.string().min(1),workspace_ids:e.array(e.string().min(1))}).strict(),ym=e.object({workspace_id:e.string().min(1),agent_dir:e.string().min(1)}).strict(),In=e.object({ok:e.literal(!0),entries:e.array(ym),unresolved:e.array(e.string().min(1))}).strict(),Mn=e.enum(["registry_unavailable","internal_error"]),vm=e.object({code:e.union([se,Mn]),message:e.string()}).strict(),Zr=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1).optional()}).strict(),Yr=e.object({ok:e.literal(!0),tree:fa}).strict(),Jr=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1).optional(),path:e.string().min(1)}).strict(),Xr=e.object({ok:e.literal(!0),file:ga}).strict(),Qr=e.enum(["forbidden_path","not_found","workspace_not_provisioned","registry_unavailable","fs_unavailable","internal_error"]),to=e.object({code:e.union([se,Qr]),message:e.string()}).strict(),Dn=e.object({agent_id:e.string().min(1),workspace_id:e.string().min(1),template_choice:e.enum(["default","onboarding","minimal"]).default("default")}).strict(),Ln=e.object({ok:e.literal(!0),seeded:e.boolean(),l2_present:e.boolean()}).strict(),jn=e.enum(["workspace_not_provisioned","registry_unavailable","unsupported_template","fs_unavailable","internal_error"]),bm=e.object({code:e.union([se,jn]),message:e.string()}).strict(),Nn=e.object({agent_id:e.string().min(1),scope:e.enum(["all","l2"]),workspace_ids:e.array(e.string().min(1)).default([])}).strict(),Fn=e.object({ok:e.literal(!0),purged_count:e.number().int().nonnegative(),skipped_unprovisioned:e.number().int().nonnegative()}).strict(),zn=e.enum(["partial_purge","registry_unavailable","internal_error"]),Sm=e.object({code:e.union([se,zn]),message:e.string()}).strict(),$n=e.object({agent_id:e.string().min(1)}).strict(),Hn=e.object({ok:e.literal(!0),raw:e.string().nullable()}).strict(),Un=e.object({agent_id:e.string().min(1),raw:e.string()}).strict(),Wn=e.object({ok:e.literal(!0),bytes_written:e.number().int().nonnegative()}).strict(),qn=e.enum(["invalid_config","fs_unavailable","internal_error"]),no=e.object({code:e.union([se,qn]),message:e.string()}).strict(),xm=e.discriminatedUnion("kind",[e.object({kind:e.literal("profile"),agent_id:e.string().min(1)}).strict()]),es=e.object({source:xm,server_name:e.string().min(1),include_tools:e.boolean().optional()}).strict(),ts=e.enum(["fs_unavailable","internal_error"]),km=e.object({code:e.union([se,ts]),message:e.string()}).strict(),Bn={hello:{params:ro,result:qe},ping:{params:Fu,result:zu},status:{params:$u,result:Hu},echo:{params:Uu,result:Wu},host_status:{params:Tr,result:Pr},host_runtime_catalog:{params:Sn,result:xn},conversation_log_debug:{params:qu,result:Bu},agent_message_send:{params:Vu,result:Gu},agent_stale_resolve:{params:Ku,result:Zu},agent_stream_observed:{params:Yu,result:Ju},runtime_start:{params:Ir,result:Mr,error:gm},runtime_stop:{params:Dr,result:Lr},runtime_wake:{params:jr,result:Nr},runtime_status:{params:Fr,result:zr},runtime_clear_session:{params:$r,result:Hr},runtime_stop_all:{params:Ur,result:Wr},runtime_close_activity_log:{params:qr,result:Br},runtime_output_pause:{params:kn,result:Vr},runtime_output_resume:{params:Gr,result:Kr},host_outbound_attach:{params:im,result:lm},host_outbound_detach:{params:dm,result:um},host_outbound_reload:{params:mm,result:hm},host_proxy_config_get:{params:wn,result:Lt},host_proxy_config_set:{params:Rn,result:En},agent_materialize:{params:jt,result:Nt,error:fm},workspace_provision:{params:An,result:Tn,error:_m},agent_workspace_index:{params:On,result:In,error:vm},agent_workspace_tree:{params:Zr,result:Yr,error:to},agent_workspace_file_read:{params:Jr,result:Xr,error:to},agent_l2_seed:{params:Dn,result:Ln,error:bm},agent_files_purge:{params:Nn,result:Fn,error:Sm},agent_profile_mcp_read:{params:$n,result:Hn,error:no},agent_profile_mcp_write:{params:Un,result:Wn,error:no},mcp_probe:{params:es,result:vn,error:km}};function ns(n){let r=Bn[n]?.error;return r||A}var rs=e.object({id:e.string().min(1),intent:e.string().min(1),params:e.unknown()}),A=e.object({code:se,message:e.string()}),io=e.union([e.object({id:e.string().min(1),result:e.unknown()}).strict(),e.object({id:e.string().min(1),error:A}).strict()]),wm=e.object({code:e.string().min(1),message:e.string()}).strict(),co=e.union([e.object({id:e.string().min(1),result:e.unknown()}).strict(),e.object({id:e.string().min(1),error:wm}).strict()]),Vn=e.discriminatedUnion("event",[qe.extend({event:e.literal("ready"),socket_path:e.string(),daemon_pid:e.number().int(),started_at:e.number().int()}),e.object({event:e.literal("shutting_down"),reason:e.string()}),e.object({event:e.literal("runtime_state"),conversation_id:e.string().min(1),agent_id:e.string().min(1),state:dt,ts:e.number().int()}),e.object({event:e.literal("runtime_output"),conversation_id:e.string().min(1),agent_id:e.string().min(1),stream:e.enum(["stdout","stderr"]),chunk:e.string(),ts:e.number().int()}),e.object({event:e.literal("runtime_exit"),conversation_id:e.string().min(1),agent_id:e.string().min(1),code:e.number().int().nullable(),intentional:e.boolean(),ts:e.number().int()}),e.object({event:e.literal("runtime_ready_for_drain"),conversation_id:e.string().min(1),agent_id:e.string().min(1),ts:e.number().int()}),e.object({event:e.literal("runtime_startup_delivery_consumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),ts:e.number().int()}),e.object({event:e.literal("runtime_startup_delivery_failed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),reason:e.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_timeout"),conversation_id:e.string().min(1),agent_id:e.string().min(1),timeout_reason:e.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:e.number().int().nonnegative(),timeout_ms:e.number().int().nonnegative(),retrying:e.boolean(),retry_attempt:e.number().int().nonnegative(),max_retries:e.number().int().nonnegative(),cooldown_until:e.number().int().positive().optional(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_retrying"),conversation_id:e.string().min(1),agent_id:e.string().min(1),retry_attempt:e.number().int().positive(),max_retries:e.number().int().nonnegative(),delay_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_init_cooldown"),conversation_id:e.string().min(1),agent_id:e.string().min(1),cooldown_until:e.number().int().positive(),attempts_exhausted:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_compaction_stale"),conversation_id:e.string().min(1),agent_id:e.string().min(1),elapsed_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_output_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),dropped_count:e.number().int().nonnegative(),bytes_dropped:e.number().int().nonnegative(),since_ts:e.number().int()}),e.object({event:e.literal("runtime_output_paused"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}),e.object({event:e.literal("runtime_output_resumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}),e.object({event:e.literal("runtime_parsed_event"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed:gn,ts:e.number().int()}).strict(),e.object({event:e.literal("runtime_parsed_event_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed_kind:_n,encoded_bytes:e.number().int().nonnegative(),reason:e.literal("frame_too_large"),ts:e.number().int()}).strict()]),lo=e.union([rs,io,Vn]),ss=e.union([rs,co,Vn]),We=1*1024*1024;function Gn(n){let t=JSON.stringify(n);if(Buffer.byteLength(t,"utf8")>We)throw new Error(`host frame exceeds MAX_FRAME_BYTES (${We})`);return`${t}
|
|
13
|
+
`}function ft(n,t){let r=n+t,s=[],a=0,o=!1;for(;;){let c=r.indexOf(`
|
|
14
|
+
`,a);if(c===-1)break;let d=r.slice(a,c);if(a=c+1,d.length!==0){if(Buffer.byteLength(d,"utf8")>We)return o=!0,{frames:s,leftover:"",overflow:o};s.push(d)}}let i=r.slice(a);return Buffer.byteLength(i,"utf8")>We?{frames:s,leftover:"",overflow:!0}:{frames:s,leftover:i,overflow:o}}import{Socket as Rm}from"node:net";var zt=class{socketPath;socket=null;connected=!1;disconnectFired=!1;buffer="";handlers={frame:new Set,disconnect:new Set,overflow:new Set};constructor(t){this.socketPath=t.socketPath}connect(){if(this.socket)throw new Error("transport already connected or in flight; create a new one");let t=new Rm;return this.socket=t,t.setEncoding("utf8"),new Promise((r,s)=>{let a=i=>{t.off("connect",o),this.fireDisconnect(`connect_failed:${i.code??i.message}`),s(i)},o=()=>{t.off("error",a),this.connected=!0,this.attachStreamHandlers(t),r()};t.once("error",a),t.once("connect",o),t.connect(this.socketPath)})}write(t){if(!this.connected||!this.socket)return!1;try{return this.socket.write(t),!0}catch{return!1}}close(){if(!this.socket)return;let t=this.socket;this.socket=null,this.connected=!1;try{t.destroy()}catch{}this.fireDisconnect("local_close")}on(t,r){return this.handlers[t].add(r),()=>{this.handlers[t].delete(r)}}isConnected(){return this.connected}attachStreamHandlers(t){t.on("data",r=>{let s=typeof r=="string"?r:r.toString("utf8"),{frames:a,leftover:o,overflow:i}=ft(this.buffer,s);if(this.buffer=o,i){for(let c of this.handlers.overflow)c();t.destroy();return}for(let c of a)this.deliverFrame(c)}),t.once("end",()=>this.fireDisconnect("peer_end")),t.once("error",r=>{let s=r.code;this.fireDisconnect(`socket_error:${s??r.message}`)}),t.once("close",()=>this.fireDisconnect("socket_close"))}deliverFrame(t){let r;try{r=JSON.parse(t)}catch{return}let s=ss.safeParse(r);if(!s.success||"intent"in s.data)return;let a=s.data;for(let o of this.handlers.frame)o(a)}fireDisconnect(t){if(!this.disconnectFired){this.disconnectFired=!0,this.connected=!1;for(let r of this.handlers.disconnect)r(t)}}};var M=class extends Error{constructor(r,s){super(s);this.code=r;this.name="HostClientError"}code},Be=class extends M{expected;actual;daemonVersion;reason;cause;constructor(t){let r=t.actual===null?"missing":String(t.actual),s=t.daemonVersion??"unknown";super("protocol_mismatch",`daemon speaks host protocol_version=${r}; client expects ${t.expected}. Daemon version=${s}. Recovery: stop the stale silverhand-daemon and restart the app/CLI so client and daemon come from the same checkout/build.`),this.name="ProtocolVersionMismatchError",this.expected=t.expected,this.actual=t.actual,this.daemonVersion=t.daemonVersion,this.reason=t.reason,this.cause=t.cause}},Cm={info:()=>{},warn:()=>{},error:()=>{}},Am=uo([]);function uo(n){let t=new Set(n),r;return r=Object.freeze({get size(){return t.size},has(s){return t.has(s)},entries(){return t.entries()},keys(){return t.keys()},values(){return t.values()},[Symbol.iterator](){return t[Symbol.iterator]()},forEach(s,a){t.forEach(o=>s.call(a,o,o,r))}}),r}var Ve=class{transportFactory;requestTimeoutMs;initialBackoffMs;maxBackoffMs;logger;rng;pending=new Map;reconnectHandlers=new Set;eventHandlers=new Set;transport=null;closed=!1;readyPromise=null;readyResolve=null;readyReject=null;backoffMs;reconnectTimer=null;connectAttempted=!1;negotiatedProtocol=null;suppressNextDisconnect=!1;constructor(t){if(!t.transportFactory&&!t.socketPath)throw new Error("HostClient requires either socketPath or transportFactory");this.transportFactory=t.transportFactory??(()=>new zt({socketPath:t.socketPath})),this.requestTimeoutMs=t.requestTimeoutMs??5e3,this.initialBackoffMs=t.initialBackoffMs??250,this.maxBackoffMs=t.maxBackoffMs??3e4,this.logger=t.logger??Cm,this.rng=t.rng??Math.random,this.backoffMs=this.initialBackoffMs,this.resetReadyPromise()}async connect(){if(this.closed)throw new M("closed","client is closed");if(this.connectAttempted)return this.readyPromise;this.connectAttempted=!0;try{await this.openTransport()}catch(t){throw this.readyReject?.(t),t}}onReconnect(t){return this.reconnectHandlers.add(t),()=>{this.reconnectHandlers.delete(t)}}isConnected(){return this.transport?.isConnected()??!1}get negotiated(){return this.negotiatedProtocol}get capabilities(){return this.negotiatedProtocol?.capabilities??Am}async call(t,r){if(this.closed)throw new M("closed","client is closed");if(!this.transport||!this.transport.isConnected())throw new M("disconnected","host client is not connected");let s=Em(8).toString("base64url"),o=Gn({id:s,intent:t,params:r});return new Promise((i,c)=>{let d=setTimeout(()=>{this.pending.delete(s),c(new M("timeout",`intent ${t} timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);if(d.unref?.(),this.pending.set(s,{intent:t,timer:d,resolve:m=>i(m),reject:c}),!this.transport.write(o)){let m=this.pending.get(s);m&&(clearTimeout(m.timer),this.pending.delete(s)),c(new M("disconnected",`failed to write intent ${t}`))}})}ping(){return this.call("ping",{})}status(){return this.call("status",{})}echo(t){return this.call("echo",{message:t})}setConversationLogDebug(t){return this.call("conversation_log_debug",t)}agentMessageSend(t){return this.call("agent_message_send",t)}agentStaleResolve(t){return this.call("agent_stale_resolve",t)}agentStreamObserved(t){return this.call("agent_stream_observed",t)}runtimeStart(t){return this.call("runtime_start",t)}runtimeStop(t){return this.call("runtime_stop",t)}runtimeWake(t){return this.call("runtime_wake",t)}runtimeStatus(t={}){return this.call("runtime_status",t)}runtimeClearSession(t){return this.call("runtime_clear_session",t)}runtimeStopAll(){return this.call("runtime_stop_all",{})}runtimeCloseActivityLog(){return this.call("runtime_close_activity_log",{})}hostOutboundAttach(t){return this.call("host_outbound_attach",t)}hostOutboundDetach(){return this.call("host_outbound_detach",{})}hostOutboundReload(){return this.call("host_outbound_reload",{})}hostProxyConfigGet(){return this.call("host_proxy_config_get",{})}hostProxyConfigSet(t){return this.call("host_proxy_config_set",t)}hostRuntimeCatalog(t={}){return this.call("host_runtime_catalog",t)}subscribe(t){return this.eventHandlers.add(t),()=>{this.eventHandlers.delete(t)}}async close(){this.closed||(this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.rejectAllPending(new M("closed","client closed")),this.transport?.close(),this.transport=null)}async openTransport(){if(this.closed)return;let t=this.transportFactory();this.transport=t,t.on("frame",r=>this.handleFrame(r)),t.on("disconnect",r=>this.handleDisconnect(r)),t.on("overflow",()=>{this.logger.warn({},"daemon sent oversize frame; reconnecting"),t.close()}),await t.connect();try{await this.negotiateProtocol()}catch(r){throw this.negotiatedProtocol=null,this.transport===t&&(this.transport=null),this.suppressNextDisconnect=!0,t.close(),r}this.backoffMs=this.initialBackoffMs,this.readyResolve?.(),this.logger.info({},"host client connected")}async negotiateProtocol(){let t;try{t=await this.call("hello",{})}catch(r){throw r instanceof M&&r.code==="unknown_intent"?new Be({expected:Se,actual:null,daemonVersion:null,reason:"daemon_protocol_missing",cause:r}):r instanceof M&&r.code==="internal_error"?new Be({expected:Se,actual:null,daemonVersion:null,reason:"invalid_hello",cause:r}):r}if(t.protocol_version!==Se)throw new Be({expected:Se,actual:t.protocol_version,daemonVersion:t.daemon_version,reason:"version_mismatch"});this.negotiatedProtocol=Object.freeze({protocolVersion:t.protocol_version,daemonVersion:t.daemon_version,daemonId:t.daemon_id,instanceId:t.instance_id,hostDescriptor:{...t.host_descriptor},capabilities:uo(t.capabilities)})}handleFrame(t){if("event"in t){t.event==="shutting_down"?this.logger.info({reason:t.reason},"daemon notified shutdown"):t.event==="ready"&&this.logger.info({daemon_pid:t.daemon_pid,daemon_version:t.daemon_version,daemon_id:t.daemon_id,instance_id:t.instance_id,started_at:t.started_at},"daemon ready handshake");for(let a of this.eventHandlers)try{a(t)}catch(o){this.logger.error({err:o.message,event:t.event},"event subscriber threw")}return}let r=this.pending.get(t.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(t.id),"error"in t){let o=ns(r.intent).safeParse(t.error);if(o.success){r.reject(new M(o.data.code,o.data.message));return}let i=o.error.errors.map(c=>`${c.path.join(".")}: ${c.message}`).join("; ");this.logger.warn({intent:r.intent,received_code:t.error.code,issues:i},"host client received response error code that is not valid for intent"),r.reject(new M("internal_error",`drift: error code "${t.error.code}" for ${r.intent} is not in this intent's error taxonomy (${i})`));return}let s=Bn[r.intent];if(s){let a=s.result.safeParse(t.result);if(!a.success){let o=a.error.errors.map(i=>`${i.path.join(".")}: ${i.message}`).join("; ");this.logger.warn({intent:r.intent,issues:o},"host client received response that does not match intent schema"),r.reject(new M("internal_error",`drift: response for ${r.intent} failed schema validation (${o})`));return}r.resolve(a.data);return}r.resolve(t.result)}handleDisconnect(t){if(this.suppressNextDisconnect){this.suppressNextDisconnect=!1,this.transport=null;return}this.logger.warn({reason:t},"host client transport disconnected"),this.rejectAllPending(new M("disconnected",`transport disconnected: ${t}`)),this.transport=null,this.negotiatedProtocol=null,!this.closed&&(this.resetReadyPromise(),this.scheduleReconnect())}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let t=Math.max(this.initialBackoffMs,Math.floor(this.backoffMs*this.rng()));this.backoffMs=Math.min(this.maxBackoffMs,this.backoffMs*2),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.attemptReconnect()},t),this.reconnectTimer.unref?.(),this.logger.info({delay:t},"host client scheduling reconnect")}async attemptReconnect(){if(!this.closed)try{await this.openTransport();for(let t of this.reconnectHandlers)try{t()}catch(r){this.logger.error({err:r.message},"onReconnect handler threw")}}catch(t){if(t instanceof Be){this.closed=!0,this.readyReject?.(t),this.logger.error({expected:t.expected,actual:t.actual,daemon_version:t.daemonVersion,reason:t.reason},"host client protocol negotiation failed; reconnect disabled");return}this.logger.warn({err:t.message},"host client reconnect attempt failed; will retry"),this.scheduleReconnect()}}rejectAllPending(t){for(let[,r]of this.pending)clearTimeout(r.timer),r.reject(t);this.pending.clear()}resetReadyPromise(){this.readyPromise=new Promise((t,r)=>{this.readyResolve=t,this.readyReject=r}),this.readyPromise.catch(()=>{})}};import{execFile as Tm}from"node:child_process";import{promisify as Pm}from"node:util";var Rx=Pm(Tm);var as=e.string().min(1),is=2,ho=e.object({host_id:e.string().min(1),host_token:e.string().min(1),issued_at:e.number().int().nonnegative(),grace_until:e.number().int().positive()}).strict().superRefine((n,t)=>{n.grace_until<=n.issued_at&&t.addIssue({code:"custom",path:["grace_until"],message:"grace_until must be after issued_at"})}),fo=e.discriminatedUnion("rotated",[e.object({rotated:e.literal(!0),host_id:e.string().min(1),config_refreshed_at:e.number().int().nonnegative()}).strict(),e.object({rotated:e.literal(!1),reason:e.enum(["host_mismatch","invalid_config","write_failed"]),message:e.string().optional()}).strict()]),go=e.object({code:e.union([A.shape.code,Ft]),message:e.string()}).strict(),Om=e.object({code:e.union([A.shape.code,Pn]),message:e.string()}).strict(),Im=e.object({code:e.union([A.shape.code,Mn]),message:e.string()}).strict(),mo=e.object({code:e.union([A.shape.code,Qr]),message:e.string()}).strict(),Mm=e.object({code:e.union([A.shape.code,jn]),message:e.string()}).strict(),Dm=e.object({code:e.union([A.shape.code,zn]),message:e.string()}).strict(),po=e.object({code:e.union([A.shape.code,qn]),message:e.string()}).strict(),Lm=e.object({code:e.union([A.shape.code,ts]),message:e.string()}).strict(),_o=e.object({code:e.union([A.shape.code,Cn]),message:e.string()}).strict(),$t={runtime_start:{params:Ir,result:Mr,error:_o},runtime_stop:{params:Dr,result:Lr,error:A},runtime_wake:{params:jr,result:Nr,error:A},runtime_status:{params:Fr,result:zr,error:A},runtime_clear_session:{params:$r,result:Hr,error:A},runtime_stop_all:{params:Ur,result:Wr,error:A},runtime_close_activity_log:{params:qr,result:Br,error:A},runtime_output_pause:{params:kn,result:Vr,error:A},runtime_output_resume:{params:Gr,result:Kr,error:A},rotate_token:{params:ho,result:fo,error:A},agent_materialize:{params:jt,result:Nt,error:go},workspace_provision:{params:An,result:Tn,error:Om},agent_workspace_index:{params:On,result:In,error:Im},agent_workspace_tree:{params:Zr,result:Yr,error:mo},agent_workspace_file_read:{params:Jr,result:Xr,error:mo},agent_l2_seed:{params:Dn,result:Ln,error:Mm},agent_files_purge:{params:Nn,result:Fn,error:Dm},agent_profile_mcp_read:{params:$n,result:Hn,error:po},agent_profile_mcp_write:{params:Un,result:Wn,error:po},mcp_probe:{params:es,result:vn,error:Lm},host_status:{params:Tr,result:Pr,error:A},host_runtime_catalog:{params:Sn,result:xn,error:A},host_proxy_config_get:{params:wn,result:Lt,error:A},host_proxy_config_set:{params:Rn,result:En,error:A}},cs=Object.keys($t),jm=cs.map(n=>e.object({direction:e.literal("server_to_daemon"),type:e.literal("command"),id:as,kind:e.literal(n),params:$t[n].params}).strict()),ls=e.discriminatedUnion("kind",jm),Nm=cs.flatMap(n=>[e.object({direction:e.literal("daemon_to_server"),type:e.literal("command_response"),id:as,kind:e.literal(n),result:$t[n].result}).strict(),e.object({direction:e.literal("daemon_to_server"),type:e.literal("command_response"),id:as,kind:e.literal(n),error:$t[n].error}).strict()]),ds=e.union(Nm),os=e.number().int().nonnegative(),yo=e.object({direction:e.enum(["server_to_daemon","daemon_to_server"]),type:e.literal("heartbeat"),kind:e.literal("ping"),ts:os}).strict(),vo=e.object({direction:e.enum(["server_to_daemon","daemon_to_server"]),type:e.literal("heartbeat"),kind:e.literal("pong"),ts:os,echo_ts:os}).strict(),us=e.discriminatedUnion("kind",[yo,vo]),bo=qe.extend({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("ready"),protocol_version:e.literal(is),daemon_pid:e.number().int(),started_at:e.number().int()}).strict(),Fm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("shutting_down"),reason:e.string()}).strict(),zm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_state"),conversation_id:e.string().min(1),agent_id:e.string().min(1),state:dt,ts:e.number().int()}).strict(),$m=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output"),conversation_id:e.string().min(1),agent_id:e.string().min(1),stream:e.enum(["stdout","stderr"]),chunk:e.string(),ts:e.number().int()}).strict(),Hm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_exit"),conversation_id:e.string().min(1),agent_id:e.string().min(1),code:e.number().int().nullable(),intentional:e.boolean(),ts:e.number().int()}).strict(),Um=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_ready_for_drain"),conversation_id:e.string().min(1),agent_id:e.string().min(1),ts:e.number().int()}).strict(),Wm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_startup_delivery_consumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),ts:e.number().int()}).strict(),qm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_startup_delivery_failed"),conversation_id:e.string().min(1),agent_id:e.string().min(1),delivery_ids:e.array(e.number().int()).min(1),reason:e.enum(["child_exit","init_watchdog","write_failed","driver_refused"]),ts:e.number().int()}).strict(),Bm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_timeout"),conversation_id:e.string().min(1),agent_id:e.string().min(1),timeout_reason:e.enum(["silence","pre_protocol_cap","post_protocol"]),elapsed_ms:e.number().int().nonnegative(),timeout_ms:e.number().int().nonnegative(),retrying:e.boolean(),retry_attempt:e.number().int().nonnegative(),max_retries:e.number().int().nonnegative(),cooldown_until:e.number().int().positive().optional(),ts:e.number().int()}).strict(),Vm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_retrying"),conversation_id:e.string().min(1),agent_id:e.string().min(1),retry_attempt:e.number().int().positive(),max_retries:e.number().int().nonnegative(),delay_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Gm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_init_cooldown"),conversation_id:e.string().min(1),agent_id:e.string().min(1),cooldown_until:e.number().int().positive(),attempts_exhausted:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Km=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_compaction_stale"),conversation_id:e.string().min(1),agent_id:e.string().min(1),elapsed_ms:e.number().int().nonnegative(),ts:e.number().int()}).strict(),Zm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),dropped_count:e.number().int().nonnegative(),bytes_dropped:e.number().int().nonnegative(),since_ts:e.number().int()}).strict(),Ym=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_paused"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Jm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_output_resumed"),conversation_id:e.string().min(1),agent_id:e.string().min(1)}).strict(),Xm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_parsed_event"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed:gn,ts:e.number().int()}).strict(),Qm=e.object({direction:e.literal("daemon_to_server"),type:e.literal("event"),kind:e.literal("runtime_parsed_event_dropped"),conversation_id:e.string().min(1),agent_id:e.string().min(1),parsed_kind:_n,encoded_bytes:e.number().int().nonnegative(),reason:e.literal("frame_too_large"),ts:e.number().int()}).strict(),ms=e.discriminatedUnion("kind",[bo,Fm,zm,$m,Hm,Um,Wm,qm,Bm,Vm,Gm,Km,Zm,Ym,Jm,Xm,Qm]),ep=ms.options.map(n=>n.shape.kind.value),So=e.union([ls,ds,us,ms]);var Gx=qe.pick({daemon_id:!0,host_descriptor:!0}).strict(),tp=Object.freeze({daemon_id:"local",host_descriptor:Object.freeze({name:"local",kind:"local"})});var xh=fe(gi(),1),kh=fe(nr(),1),wh=fe(yt(),1),Rh=fe(ks(),1),Eh=fe(Es(),1),Ch=fe(Is(),1),Ah=fe(or(),1),Th=fe(wi(),1);var Ph={maxFrames:1024,maxBytes:4*1024*1024};var Mk=["# 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(`
|
|
15
|
+
`);var Oh=e.object({version:e.number().int().positive(),agent_id:e.string().min(1),template_choice:e.string().min(1),runtime:e.string().min(1),materialized_at:e.number().int().positive()}).strict();function Ai(n,t={}){let r=[],s={},a=[],o=new Set(t.booleanFlags??[]),i=0;for(;i<n.length;){let c=n[i];if(c==="--"){a.push(...n.slice(i+1));break}if(c.startsWith("--")){let d=c.slice(2),l,m=d.indexOf("=");if(m>=0&&(l=d.slice(m+1),d=d.slice(0,m)),d.startsWith("no-")&&l===void 0){s[d.slice(3)]=!1,i+=1;continue}if(l===void 0){let v=n[i+1];if(!o.has(d)&&v!==void 0&&!v.startsWith("--"))l=v,i+=2;else{s[d]=!0,i+=1;continue}}else i+=1;let h=s[d];Array.isArray(h)?h.push(l):typeof h=="string"?s[d]=[h,l]:s[d]=l;continue}r.push(c),i+=1}return{positional:r,flags:s,rest:a}}function y(n,t){let r=n.flags[t];if(r!==void 0){if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1];throw new Error(`flag --${t} expects a value`)}}function Z(n,t){let r=n.flags[t];if(r!==void 0){if(typeof r=="boolean")return r;if(r==="true")return!0;if(r==="false")return!1;throw new Error(`flag --${t} expects no value (use --${t} or --no-${t})`)}}function j(n,t){let r=y(n,t);if(r===void 0)return;let s=Number(r);if(!Number.isFinite(s))throw new Error(`flag --${t} expects a number, got ${JSON.stringify(r)}`);return s}function we(n,t){let r=n.flags[t];if(r!==void 0){if(Array.isArray(r))return r.slice();if(typeof r=="string")return[r];throw new Error(`flag --${t} expects a value`)}}function Ds(n,t){let r=we(n,t);if(r!==void 0)return r.map(s=>{let a=Number(s);if(!Number.isFinite(a))throw new Error(`flag --${t} expects numbers, got ${JSON.stringify(s)}`);return a})}var Nh={verb:"send",summary:"Send a message to the current channel/thread.",help:`silverhand message send [--target channel|thread:<message_id>]
|
|
16
16
|
[--attachment <id> ...]
|
|
17
17
|
[--stale-resolution unaffected|revised]
|
|
18
18
|
[--anyway]
|
|
@@ -77,7 +77,7 @@ Pre-flight failures (exit 1):
|
|
|
77
77
|
stdin is empty and no attachment \u2192 empty_stdin
|
|
78
78
|
stdin is not UTF-8 \u2192 invalid_utf8 (re-encode upstream)
|
|
79
79
|
|
|
80
|
-
stdout: { "message_id": "<id>", "message_seq": <seq>, "thread_root_id": <id|null> }`,flags:["target","reply-to","attachment","stale-resolution"],booleanFlags:["anyway"],removedFlags:{content:{replacement:"stdin",hint:'pipe the body via stdin instead \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'},text:{replacement:"stdin",hint:'silverhand message send only accepts the body on stdin. Use a heredoc \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'},message:{replacement:"stdin",hint:'silverhand message send only accepts the body on stdin. Use a heredoc \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'}},async run({env:n,client:t,args:r}){let s=we(r,"attachment"),
|
|
80
|
+
stdout: { "message_id": "<id>", "message_seq": <seq>, "thread_root_id": <id|null> }`,flags:["target","reply-to","attachment","stale-resolution"],booleanFlags:["anyway"],removedFlags:{content:{replacement:"stdin",hint:'pipe the body via stdin instead \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'},text:{replacement:"stdin",hint:'silverhand message send only accepts the body on stdin. Use a heredoc \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'},message:{replacement:"stdin",hint:'silverhand message send only accepts the body on stdin. Use a heredoc \u2014 e.g. `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF` or `printf "%s" "..." | silverhand message send`'}},async run({env:n,client:t,args:r}){let s=we(r,"attachment"),a=(s?.length??0)>0,o="";if(process.stdin.isTTY&&!a)throw new u({code:"validation_error",subkind:"stdin_is_tty",message:'silverhand message send reads the body from stdin, but stdin is a TTY. Pipe the body \u2014 e.g. `printf "%s" "hello" | silverhand message send` or `silverhand message send <<\'SILVERHAND_EOF\' ... SILVERHAND_EOF`.',retriable:!1});if(!process.stdin.isTTY){let m=await Kh();if(m.byteLength===0&&!a)throw new u({code:"validation_error",subkind:"empty_stdin",message:"silverhand message send received 0 bytes on stdin. Pipe a non-empty body, or attach at least one file.",retriable:!1});if(o=m.toString("utf8"),!Buffer.from(o,"utf8").equals(m))throw new u({code:"validation_error",subkind:"invalid_utf8",message:"message body must be valid UTF-8 (stdin contained byte sequences that are not a UTF-8 string). Re-encode your input as UTF-8 before piping.",retriable:!1,details:{encoding:"utf8"}})}let i=Wh(y(r,"target"),y(r,"reply-to")),c=Z(r,"anyway")??!1,d=Bh(y(r,"stale-resolution"));if(c&&d!==void 0)throw new u({code:"validation_error",message:"--anyway already records stale resolution as force_send; do not also pass --stale-resolution",retriable:!1});let l={conversation_id:n.conversationId,agent_id:n.agentId,content:o,...i.target?{target:i.target}:{},...s&&s.length>0?{attachment_ids:s}:{},...c?{freshness_bypass:!0}:{},...d?{stale_resolution_reason:d}:{}};return n.daemonSocketPath?await Vh(n.daemonSocketPath,l):await t.sendMessage({content:o,...i.target?{target:i.target}:{},...c?{freshness_bypass:!0}:{},...s&&s.length>0?{attachment_ids:s}:{}})}},Fh={verb:"stale-resolve",summary:"Report that a stale draft no longer needs to be sent.",help:`silverhand message stale-resolve --resolution obsolete [--event-id <id>]
|
|
81
81
|
|
|
82
82
|
Reports an observability-only resolution for the most recent message_stale
|
|
83
83
|
conflict without sending a message. This is for the "no need to send anymore"
|
|
@@ -88,7 +88,7 @@ Flags:
|
|
|
88
88
|
--event-id <id> Optional. Defaults to the pending stale event recorded
|
|
89
89
|
from the latest message_stale response.
|
|
90
90
|
|
|
91
|
-
stdout: { "resolved": true } or { "resolved": false, "reason": "no_pending_stale_event" }`,flags:["resolution","event-id"],async run({env:n,client:t,args:r}){if(y(r,"resolution")!=="obsolete")throw new u({code:"validation_error",message:"--resolution must be obsolete",retriable:!1});let
|
|
91
|
+
stdout: { "resolved": true } or { "resolved": false, "reason": "no_pending_stale_event" }`,flags:["resolution","event-id"],async run({env:n,client:t,args:r}){if(y(r,"resolution")!=="obsolete")throw new u({code:"validation_error",message:"--resolution must be obsolete",retriable:!1});let a=y(r,"event-id");if(n.daemonSocketPath)return await Gh(n.daemonSocketPath,{conversation_id:n.conversationId,agent_id:n.agentId,...a?{stale_event_id:a}:{},resolution_reason:"obsolete"});let o=a;return o?(await t.resolveStaleMessage({stale_event_id:o,resolution_reason:"obsolete"}),{resolved:!0}):{resolved:!1,reason:"no_pending_stale_event"}}},zh={verb:"react",summary:"Add or remove your emoji reaction on a message.",help:`silverhand message react --message-id <id> --emoji <emoji> [--remove]
|
|
92
92
|
|
|
93
93
|
Add or remove your reaction on a message. Use sparingly: prefer
|
|
94
94
|
acknowledgement/follow-up signals like \u{1F440}, and do not auto-react to every
|
|
@@ -107,7 +107,7 @@ Flags:
|
|
|
107
107
|
--emoji <emoji> Required. A single emoji (max 16 chars, no whitespace).
|
|
108
108
|
--remove Remove your reaction instead of adding it.
|
|
109
109
|
|
|
110
|
-
stdout: { "changed": <bool>, "emoji": "<emoji>", "count": <n> }`,flags:["message-id","emoji"],booleanFlags:["remove"],async run({client:n,args:t}){let r=y(t,"message-id");if(!r)throw new u({code:"validation_error",message:"--message-id is required",retriable:!1});let s=y(t,"emoji");if(!s)throw new u({code:"validation_error",message:"--emoji is required",retriable:!1});let
|
|
110
|
+
stdout: { "changed": <bool>, "emoji": "<emoji>", "count": <n> }`,flags:["message-id","emoji"],booleanFlags:["remove"],async run({client:n,args:t}){let r=y(t,"message-id");if(!r)throw new u({code:"validation_error",message:"--message-id is required",retriable:!1});let s=y(t,"emoji");if(!s)throw new u({code:"validation_error",message:"--emoji is required",retriable:!1});let a=Z(t,"remove")??!1;return await n.reactToMessage({message_id:r,emoji:s,...a?{remove:!0}:{}})}},$h={verb:"history",summary:"Read message history; omit the anchor for the latest window.",help:`silverhand message history [--before-seq N | --after-seq N | --around <id>]
|
|
111
111
|
[--target self|conversation:<id>|thread:<id>]
|
|
112
112
|
[--include-content] [--no-include-system]
|
|
113
113
|
[--limit N]
|
|
@@ -134,7 +134,7 @@ gated by parent-channel visibility, it does NOT make you a follower, but
|
|
|
134
134
|
it advances your observed boundary for that thread so a later
|
|
135
135
|
\`message send --target thread:<message_id>\` is judged fresh against what you just read.
|
|
136
136
|
|
|
137
|
-
stdout: full AgentReadHistoryDto JSON.`,flags:["before-seq","after-seq","around","target","limit"],booleanFlags:["include-content","include-system"],async run({env:n,client:t,args:r}){let s=j(r,"before-seq"),
|
|
137
|
+
stdout: full AgentReadHistoryDto JSON.`,flags:["before-seq","after-seq","around","target","limit"],booleanFlags:["include-content","include-system"],async run({env:n,client:t,args:r}){let s=j(r,"before-seq"),a=j(r,"after-seq"),o=y(r,"around");if([s,a,o].filter(R=>R!==void 0).length>1)throw new u({code:"validation_error",message:"message history accepts at most one of --before-seq, --after-seq, or --around; omit all to read the latest window",retriable:!1});let c=Z(r,"include-content")??!1,d=Z(r,"include-system")??!0,l=j(r,"limit")??50,m=Zh(y(r,"target")),h=await t.readHistory({...s!==void 0?{before_seq:s}:{},...a!==void 0?{after_seq:a}:{},...o!==void 0?{around_message_id:o}:{},...m?{target:m}:{},include_content:c,include_system:d,limit:l}),v=h.target.thread_root_id;if(v&&n.daemonSocketPath){let R=h.messages.filter(T=>T.message_ref.id!==v).map(T=>T.message_ref.seq),O=R.length>0?Math.max(...R):0,E=[v,...h.messages.map(T=>T.message_ref.id).filter(T=>T!==v)];await Yh(n.daemonSocketPath,{conversation_id:n.conversationId,agent_id:n.agentId,thread_root_id:v,observed_seq:O,reply_target_messages:E})}return h}},Hh={verb:"search",summary:"Search visible message text.",help:`silverhand message search <query>
|
|
138
138
|
silverhand message search (--q <text> | --query <text>)
|
|
139
139
|
[--scope current|workspace|channel]
|
|
140
140
|
[--workspace-id <id>] [--channel-id <id>]
|
|
@@ -161,7 +161,7 @@ Flags:
|
|
|
161
161
|
--no-include-system Skip system messages.
|
|
162
162
|
--limit N Max hits. Default 50, max 100.
|
|
163
163
|
|
|
164
|
-
stdout: AgentSearchMessagesDto JSON.`,flags:["q","query","scope","workspace-id","channel-id","limit"],booleanFlags:["include-system"],allowPositional:!0,async run({client:n,args:t}){let r=y(t,"q"),s=y(t,"query"),
|
|
164
|
+
stdout: AgentSearchMessagesDto JSON.`,flags:["q","query","scope","workspace-id","channel-id","limit"],booleanFlags:["include-system"],allowPositional:!0,async run({client:n,args:t}){let r=y(t,"q"),s=y(t,"query"),a=Uh(t.positional),o=[r!==void 0?"--q":null,s!==void 0?"--query":null,a!==void 0?"<query>":null].filter(v=>v!==null);if(o.length>1)throw new u({code:"validation_error",subkind:"mutually_exclusive",message:"--q, --query, and positional <query> are mutually exclusive (they are aliases). Pass exactly one.",retriable:!1,details:{query_forms:o}});let i=r??s??a;if(!i)throw new u({code:"validation_error",message:"search query is required: pass positional <query>, --q, or --query",retriable:!1});let c=y(t,"scope")??"current";if(!["current","workspace","channel"].includes(c))throw new u({code:"validation_error",subkind:"enum_invalid",message:`--scope must be current|workspace|channel; got "${c}"`,retriable:!1,details:{flag:"scope",value:c,allowed:["current","workspace","channel"]}});let d=y(t,"workspace-id"),l=y(t,"channel-id");if(c==="channel"!=!!l)throw new u({code:"validation_error",message:"--channel-id is required only when --scope is channel",retriable:!1});if(d&&c!=="workspace")throw new u({code:"validation_error",message:"--workspace-id is only valid with --scope workspace",retriable:!1});let m=Z(t,"include-system")??!0,h=j(t,"limit")??50;return n.searchMessages({q:i,scope:c,include_system:m,limit:h,...d?{workspace_id:d}:{},...l?{channel_id:l}:{}})}};function Uh(n){if(n.length!==0){if(n.length===1)return n[0];throw new u({code:"validation_error",subkind:"unexpected_arguments",message:'message search accepts at most one positional <query>. Quote multi-word queries, e.g. `silverhand message search "hello world"`.',retriable:!1,details:{positional:n}})}}var Ti=[Nh,Fh,zh,$h,Hh];function Wh(n,t){let r=qh(n);if(t!==void 0&&r!==void 0)throw new u({code:"validation_error",subkind:"mutually_exclusive",message:"--reply-to and --target are mutually exclusive: use `--target thread:<message_id>` for thread sends.",retriable:!1,details:{flags:["reply-to","target"]}});return t!==void 0?{target:{kind:"thread",message_id:t}}:r?{target:r}:{}}function qh(n){if(n!==void 0){if(n.length===0)throw new u({code:"validation_error",subkind:"enum_invalid",message:"--target must be channel or thread:<message_id>",retriable:!1,details:{flag:"target",value:n}});if(n==="channel")return{kind:"channel"};if(n==="self")return{kind:"channel"};if(n.startsWith("thread:")){let t=n.slice(7);if(!t)throw new u({code:"validation_error",subkind:"enum_invalid",message:"--target thread:<message_id> requires a message id after thread:",retriable:!1,details:{flag:"target",value:n}});return{kind:"thread",message_id:t}}throw new u({code:"validation_error",subkind:"enum_invalid",message:"--target must be channel or thread:<message_id>",retriable:!1,details:{flag:"target",value:n}})}}function Bh(n){if(n!==void 0){if(n==="unaffected"||n==="revised")return n;throw new u({code:"validation_error",message:"--stale-resolution must be unaffected or revised",retriable:!1})}}async function Vh(n,t){let r=new Ve({socketPath:n});try{await r.connect(),Pi(r);let s=await r.agentMessageSend(t);if(!s.ok)throw de(s.status,s.body_text);return{message_id:s.message_id,...s.message_seq!==void 0?{message_seq:s.message_seq}:{},...s.thread_root_id!==void 0?{thread_root_id:s.thread_root_id}:{}}}catch(s){throw s instanceof M?new u({code:s.code==="disconnected"||s.code==="timeout"?"upstream_unavailable":"internal",message:`silverhand daemon send failed: ${s.message}`,retriable:s.code==="disconnected"||s.code==="timeout"}):s}finally{await r.close().catch(()=>{})}}async function Gh(n,t){let r=new Ve({socketPath:n});try{await r.connect(),Pi(r);let s=await r.agentStaleResolve(t);if(!s.ok)throw de(s.status,s.body_text);return s.resolved?{resolved:!0}:{resolved:!1,reason:s.reason}}catch(s){throw s instanceof M?new u({code:s.code==="disconnected"||s.code==="timeout"?"upstream_unavailable":"internal",message:`silverhand daemon stale-resolve failed: ${s.message}`,retriable:s.code==="disconnected"||s.code==="timeout"}):s}finally{await r.close().catch(()=>{})}}function Pi(n){if(!n.capabilities.has("agent.freshness_authority"))throw new u({code:"internal",message:"silverhand daemon does not advertise agent.freshness_authority; restart the app/daemon from the same build as this CLI",retriable:!1})}async function Kh(){let n=[];for await(let t of process.stdin)n.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(n)}function Zh(n){if(n!==void 0){if(n==="self")return n;if(n.startsWith("thread:"))return{thread_root_id:n.slice(7)};if(n.startsWith("conversation:"))return{conversation_id:n.slice(13)};throw new u({code:"validation_error",message:"--target must be self | thread:<root_msg_id> | conversation:<id>",retriable:!1})}}async function Yh(n,t){let r=new Ve({socketPath:n});try{await r.connect(),await r.agentStreamObserved(t)}catch{}finally{await r.close().catch(()=>{})}}var Ls=["todo","in_progress","in_review","done","closed"],Kt=["todo","in_progress","in_review","done","closed"],Oi={active:["todo","in_progress","in_review"],open:["todo","in_progress","in_review"],pending:["todo"]},Ii="all",js=new Set([...Object.keys(Oi),Ii]);function Jh(n){let t=new Set;for(let r of n)for(let s of r.split(",").map(a=>a.trim()).filter(a=>a.length>0)){if(s===Ii)return null;let a=Oi[s];if(a){for(let o of a)t.add(o);continue}if(!Ls.includes(s))throw new u({code:"validation_error",subkind:"enum_invalid",message:`--status must be one of ${Ls.join("|")} or a list-only filter macro (${[...js].join("|")}); got "${s}"`,retriable:!1,details:{flag:"status",value:s,allowed:[...Ls,...js]}});t.add(s)}return[...t]}var Xh={verb:"list",summary:"View the workspace task board.",help:`silverhand task list [--task-number N [--task-number N ...]]
|
|
165
165
|
[--status STATUS [--status STATUS ...]]
|
|
166
166
|
[--assignee <agent_id>] [--mine]
|
|
167
167
|
[--workspace-id <id>] [--conversation-id <id>]
|
|
@@ -198,7 +198,7 @@ Flags:
|
|
|
198
198
|
--limit N Cap rows returned (max 500). Useful with status
|
|
199
199
|
filters to peek the board.
|
|
200
200
|
|
|
201
|
-
stdout: { "tasks": [TaskSummaryDto, ...] }`,flags:["task-number","status","assignee","workspace-id","conversation-id","limit"],booleanFlags:["mine"],async run({client:n,env:t,args:r}){let s=
|
|
201
|
+
stdout: { "tasks": [TaskSummaryDto, ...] }`,flags:["task-number","status","assignee","workspace-id","conversation-id","limit"],booleanFlags:["mine"],async run({client:n,env:t,args:r}){let s=Ds(r,"task-number"),a=we(r,"status"),o=a?Jh(a):void 0,i=y(r,"assignee"),c=Z(r,"mine");if(c&&i)throw new u({code:"validation_error",message:"--mine and --assignee are mutually exclusive",retriable:!1});let d=c?t.agentId:i,l=j(r,"limit");if(l!==void 0&&(l<1||l>500))throw new u({code:"validation_error",message:"--limit must be between 1 and 500",retriable:!1});return n.listTasks({...s?{task_number:s}:{},...o&&o.length>0?{status:o}:{},...d?{assignee_id:d}:{},...y(r,"workspace-id")?{workspace_id:y(r,"workspace-id")}:{},...y(r,"conversation-id")?{conversation_id:y(r,"conversation-id")}:{},...l!==void 0?{limit:l}:{}})}},Qh={verb:"create",summary:"Create one or more tasks (no auto-claim).",help:`silverhand task create --title <title> [--body <body>]
|
|
202
202
|
[--title <title> [--body <body>]] ...
|
|
203
203
|
[--target channel|thread:<message_id>]
|
|
204
204
|
|
|
@@ -221,7 +221,7 @@ Pre-flight failures (exit 1):
|
|
|
221
221
|
to promote an existing message)
|
|
222
222
|
--message was supplied \u2192 flag_removed (use --title / --body)
|
|
223
223
|
|
|
224
|
-
stdout: CreateTasksResult JSON.`,flags:["title","body","target","reply-to"],removedFlags:{message:{replacement:"title+body",hint:'silverhand task create takes --title (required) and --body (optional). For one task use `silverhand task create --title "..." --body "..."`. Repeat --title to create multiple in a single call.'}},async run({client:n,args:t}){let r=we(t,"title");if(!r||r.length===0)throw new u({code:"validation_error",subkind:"missing_required_flag",message:'silverhand task create requires at least one --title. Minimal call: `silverhand task create --title "..." --body "..."`. If you meant to turn an existing message into a task, use `silverhand task claim --message-id <id>` instead \u2014 it promotes-and-claims in one call without a fresh title.',retriable:!1,details:{command:"task create",flag:"title"}});let s=we(t,"body")??[],
|
|
224
|
+
stdout: CreateTasksResult JSON.`,flags:["title","body","target","reply-to"],removedFlags:{message:{replacement:"title+body",hint:'silverhand task create takes --title (required) and --body (optional). For one task use `silverhand task create --title "..." --body "..."`. Repeat --title to create multiple in a single call.'}},async run({client:n,args:t}){let r=we(t,"title");if(!r||r.length===0)throw new u({code:"validation_error",subkind:"missing_required_flag",message:'silverhand task create requires at least one --title. Minimal call: `silverhand task create --title "..." --body "..."`. If you meant to turn an existing message into a task, use `silverhand task claim --message-id <id>` instead \u2014 it promotes-and-claims in one call without a fresh title.',retriable:!1,details:{command:"task create",flag:"title"}});let s=we(t,"body")??[],a=r.map((i,c)=>{let d=s[c];return d?{title:i,body:d}:{title:i}}),o=ef(y(t,"target"),y(t,"reply-to"));return n.createTasks({tasks:a,...o?{target:o}:{}})}};function ef(n,t){if(n!==void 0&&t!==void 0)throw new u({code:"validation_error",subkind:"mutually_exclusive",message:"--reply-to and --target are mutually exclusive: use `--target thread:<message_id>` for threaded task creation.",retriable:!1,details:{flags:["reply-to","target"]}});if(t!==void 0)return{kind:"thread",message_id:t};if(n===void 0||n==="channel"||n==="self")return n===void 0?void 0:{kind:"channel"};if(n.startsWith("thread:")){let r=n.slice(7);if(!r)throw new u({code:"validation_error",subkind:"enum_invalid",message:"--target thread:<message_id> requires a message id after thread:",retriable:!1,details:{flag:"target",value:n}});return{kind:"thread",message_id:r}}throw new u({code:"validation_error",subkind:"enum_invalid",message:"--target must be channel or thread:<message_id>",retriable:!1,details:{flag:"target",value:n}})}function Ns(n){let t=y(n,"workspace-id"),r=y(n,"workspace");if(t&&r)throw new u({code:"validation_error",subkind:"mutually_exclusive",message:"--workspace-id and --workspace are mutually exclusive",retriable:!1,details:{flags:["workspace-id","workspace"]}});return{...t?{workspace_id:t}:{},...r?{workspace_name:r}:{}}}var tf={verb:"claim",summary:"Claim tasks by task number, or promote-and-claim by message id.",help:`silverhand task claim (--task-number N [--task-number N ...] |
|
|
225
225
|
--message-id <id> [--message-id <id> ...])
|
|
226
226
|
[--workspace-id <id> | --workspace <name>]
|
|
227
227
|
|
|
@@ -244,7 +244,7 @@ of a not-yet-task message) always targets the current conversation
|
|
|
244
244
|
regardless of the selector \u2014 a message can only become a task in its
|
|
245
245
|
own conversation.
|
|
246
246
|
|
|
247
|
-
stdout: ClaimTasksResult JSON.`,flags:["task-number","message-id","workspace-id","workspace"],async run({client:n,args:t}){let r=
|
|
247
|
+
stdout: ClaimTasksResult JSON.`,flags:["task-number","message-id","workspace-id","workspace"],async run({client:n,args:t}){let r=Ds(t,"task-number"),s=we(t,"message-id");if(!r&&!s)throw new u({code:"validation_error",message:"task claim requires --task-number or --message-id (or both)",retriable:!1});let a=Ns(t);return n.claimTasks({...r?{task_numbers:r}:{},...s?{message_ids:s}:{},...a})}},nf={verb:"unclaim",summary:"Release your claim on a task.",help:`silverhand task unclaim --task-number N
|
|
248
248
|
[--workspace-id <id> | --workspace <name>]
|
|
249
249
|
|
|
250
250
|
Use only when you can no longer work on the task. To signal completion,
|
|
@@ -254,7 +254,7 @@ done if explicitly approved) instead.
|
|
|
254
254
|
Workspace selector \u2014 see \`silverhand task claim --help\`. You must be
|
|
255
255
|
the task's assignee.
|
|
256
256
|
|
|
257
|
-
stdout: TaskMutationResult JSON.`,flags:["task-number","workspace-id","workspace"],async run({client:n,args:t}){let r=j(t,"task-number");if(r===void 0)throw new u({code:"validation_error",message:"--task-number is required",retriable:!1});let s=
|
|
257
|
+
stdout: TaskMutationResult JSON.`,flags:["task-number","workspace-id","workspace"],async run({client:n,args:t}){let r=j(t,"task-number");if(r===void 0)throw new u({code:"validation_error",message:"--task-number is required",retriable:!1});let s=Ns(t);return n.unclaimTask({task_number:r,...s})}},rf={verb:"status",summary:"Move a task through its status workflow.",help:`silverhand task status --task-number N --status todo|in_progress|in_review|done|closed
|
|
258
258
|
[--workspace-id <id> | --workspace <name>]
|
|
259
259
|
|
|
260
260
|
Allowed transitions (you must be the assignee, or the creator of an
|
|
@@ -277,7 +277,7 @@ to \`task list\`.
|
|
|
277
277
|
Workspace selector \u2014 see \`silverhand task claim --help\`. Cross-workspace
|
|
278
278
|
status updates require you to be a member of the resolved workspace.
|
|
279
279
|
|
|
280
|
-
stdout: TaskMutationResult JSON.`,flags:["task-number","status","workspace-id","workspace"],async run({client:n,args:t}){let r=j(t,"task-number"),s=y(t,"status");if(r===void 0||!s)throw new u({code:"validation_error",message:"task status requires --task-number and --status",retriable:!1});if(
|
|
280
|
+
stdout: TaskMutationResult JSON.`,flags:["task-number","status","workspace-id","workspace"],async run({client:n,args:t}){let r=j(t,"task-number"),s=y(t,"status");if(r===void 0||!s)throw new u({code:"validation_error",message:"task status requires --task-number and --status",retriable:!1});if(js.has(s))throw new u({code:"validation_error",subkind:"enum_invalid",message:`--status "${s}" is a list-only filter macro for \`silverhand task list\`, not a writable task status. task status takes a single concrete state: ${Kt.join("|")}.`,retriable:!1,details:{flag:"status",value:s,allowed:Kt,reason:"list_only_macro"}});if(!Kt.includes(s))throw new u({code:"validation_error",subkind:"enum_invalid",message:`--status must be one of ${Kt.join("|")}; got "${s}"`,retriable:!1,details:{flag:"status",value:s,allowed:Kt}});let a=Ns(t);return n.updateTaskStatus({task_number:r,status:s,...a})}},Mi=[Xh,Qh,tf,nf,rf];var sf={verb:"follow",summary:"Follow a reply cluster to receive its replies in your inbox.",help:`silverhand thread follow --root <message_id>
|
|
281
281
|
|
|
282
282
|
Voluntarily follow a reply cluster (the thread under a message). A
|
|
283
283
|
cluster is identified by its root message id \u2014 you may pass the root
|
|
@@ -293,7 +293,7 @@ Flags:
|
|
|
293
293
|
--root <message_id> Required. The cluster root, or any reply in it.
|
|
294
294
|
|
|
295
295
|
stdout: { "thread_root_id": "<root_id>", "changed": <bool> }
|
|
296
|
-
changed=false means you were already following (no re-backfill).`,flags:["root"],async run({client:n,args:t}){let r=y(t,"root");if(!r)throw new u({code:"validation_error",message:"thread follow requires --root <message_id>",retriable:!1});return n.followThread({root_message_id:r})}},
|
|
296
|
+
changed=false means you were already following (no re-backfill).`,flags:["root"],async run({client:n,args:t}){let r=y(t,"root");if(!r)throw new u({code:"validation_error",message:"thread follow requires --root <message_id>",retriable:!1});return n.followThread({root_message_id:r})}},af={verb:"unfollow",summary:"Stop following a reply cluster.",help:`silverhand thread unfollow --root <message_id>
|
|
297
297
|
|
|
298
298
|
Stop following a reply cluster (the thread under a message). Identified
|
|
299
299
|
by the cluster root or any reply in it (normalized server-side).
|
|
@@ -305,7 +305,7 @@ Flags:
|
|
|
305
305
|
--root <message_id> Required. The cluster root, or any reply in it.
|
|
306
306
|
|
|
307
307
|
stdout: { "thread_root_id": "<root_id>", "changed": <bool> }
|
|
308
|
-
changed=false means you were not following.`,flags:["root"],async run({client:n,args:t}){let r=y(t,"root");if(!r)throw new u({code:"validation_error",message:"thread unfollow requires --root <message_id>",retriable:!1});return n.unfollowThread({root_message_id:r})}},
|
|
308
|
+
changed=false means you were not following.`,flags:["root"],async run({client:n,args:t}){let r=y(t,"root");if(!r)throw new u({code:"validation_error",message:"thread unfollow requires --root <message_id>",retriable:!1});return n.unfollowThread({root_message_id:r})}},Di=[sf,af];var of={verb:"create",summary:"Create a new top-level channel in the current workspace.",help:`silverhand channel create --title <title> --context-summary <text>
|
|
309
309
|
--initial-prompt <text>
|
|
310
310
|
|
|
311
311
|
ONLY use this when the user has explicitly requested a new top-level
|
|
@@ -322,7 +322,7 @@ Flags:
|
|
|
322
322
|
intent it serves. Stored for audit and recovery.
|
|
323
323
|
--initial-prompt Required. First message posted into the new channel.
|
|
324
324
|
|
|
325
|
-
stdout: { "channel_id": "<id>" }`,flags:["title","context-summary","initial-prompt"],async run({client:n,args:t}){let r=y(t,"title"),s=y(t,"context-summary"),
|
|
325
|
+
stdout: { "channel_id": "<id>" }`,flags:["title","context-summary","initial-prompt"],async run({client:n,args:t}){let r=y(t,"title"),s=y(t,"context-summary"),a=y(t,"initial-prompt");if(!r||!s||!a)throw new u({code:"validation_error",message:"channel create requires --title, --context-summary, and --initial-prompt",retriable:!1});return n.createChannel({title:r,context_summary:s,initial_prompt:a})}},cf={verb:"list",summary:"List top-level channels of a workspace.",help:`silverhand channel list [--workspace-id <id>]
|
|
326
326
|
|
|
327
327
|
Lists channels of a workspace where this agent is currently a member.
|
|
328
328
|
Defaults to the current workspace.
|
|
@@ -330,7 +330,7 @@ Defaults to the current workspace.
|
|
|
330
330
|
Flags:
|
|
331
331
|
--workspace-id Optional. From \`silverhand workspace list\`.
|
|
332
332
|
|
|
333
|
-
stdout: AgentListChannelsDto JSON.`,flags:["workspace-id"],async run({client:n,args:t}){let r=y(t,"workspace-id");return n.listChannels({...r?{workspace_id:r}:{}})}},
|
|
333
|
+
stdout: AgentListChannelsDto JSON.`,flags:["workspace-id"],async run({client:n,args:t}){let r=y(t,"workspace-id");return n.listChannels({...r?{workspace_id:r}:{}})}},Li=[of,cf];var lf={verb:"add",summary:"Add an existing workspace member to the current conversation.",help:`silverhand member add --handle <handle>
|
|
334
334
|
|
|
335
335
|
Adds an existing workspace member (agent or human) to the current
|
|
336
336
|
conversation (channel or thread). The handle is resolved server-side
|
|
@@ -368,7 +368,7 @@ Errors:
|
|
|
368
368
|
(422) (channel + thread are both OK)
|
|
369
369
|
conversation_closed (409) conversation is archived/closed
|
|
370
370
|
duplicate 200 no-op, returns current
|
|
371
|
-
members unchanged`,flags:["handle"],async run({client:n,args:t}){let r=y(t,"handle");if(!r)throw new u({code:"validation_error",message:"member add requires --handle <handle>",retriable:!1});return n.addConversationMember({handle:r})}},
|
|
371
|
+
members unchanged`,flags:["handle"],async run({client:n,args:t}){let r=y(t,"handle");if(!r)throw new u({code:"validation_error",message:"member add requires --handle <handle>",retriable:!1});return n.addConversationMember({handle:r})}},ji=[lf];var df={verb:"list",summary:"List workspaces this agent can reach.",help:`silverhand workspace list
|
|
372
372
|
|
|
373
373
|
Lists every workspace this agent currently has member access to:
|
|
374
374
|
regular workspaces it has been added to, plus its own personal home
|
|
@@ -378,7 +378,7 @@ the agent's working directory inside that workspace.
|
|
|
378
378
|
Use the returned ids with --workspace-id on \`silverhand channel list\`
|
|
379
379
|
or \`silverhand message search --scope workspace\`.
|
|
380
380
|
|
|
381
|
-
stdout: AgentListWorkspacesDto JSON.`,flags:[],async run({client:n}){return n.listWorkspaces()}},
|
|
381
|
+
stdout: AgentListWorkspacesDto JSON.`,flags:[],async run({client:n}){return n.listWorkspaces()}},Ni=[df];var uf={verb:"create",summary:"Create a self-wake schedule for this agent.",help:`silverhand schedule create --title <text> --message <text> --kind once|interval|cron
|
|
382
382
|
[--target-conversation-id <id>]
|
|
383
383
|
[<kind-specific flags>]
|
|
384
384
|
[--until-at <epoch_ms>] [--max-occurrences N]
|
|
@@ -424,7 +424,7 @@ Repeat-only options (rejected on once):
|
|
|
424
424
|
--allow-unbounded Required true for repeat schedules with neither
|
|
425
425
|
--until-at nor --max-occurrences set.
|
|
426
426
|
|
|
427
|
-
stdout: { "schedule": ScheduleDto }`,flags:["title","message","kind","target-conversation-id","fire-at","delay-seconds","every-seconds","start-at","expression","timezone","until-at","max-occurrences"],booleanFlags:["allow-unbounded"],async run({client:n,args:t}){let r=y(t,"title"),s=y(t,"message"),
|
|
427
|
+
stdout: { "schedule": ScheduleDto }`,flags:["title","message","kind","target-conversation-id","fire-at","delay-seconds","every-seconds","start-at","expression","timezone","until-at","max-occurrences"],booleanFlags:["allow-unbounded"],async run({client:n,args:t}){let r=y(t,"title"),s=y(t,"message"),a=y(t,"kind");if(!r)throw new u({code:"validation_error",subkind:"missing_required_flag",message:"schedule create requires --title <text>; use a short label for the schedules UI",retriable:!1,details:{command:"schedule create",flag:"title"}});if(!s)throw new u({code:"validation_error",subkind:"missing_required_flag",message:"schedule create requires --message <text>; write the actual instruction for your future self",retriable:!1,details:{command:"schedule create",flag:"message"}});if(!a)throw new u({code:"validation_error",subkind:"missing_required_flag",message:"schedule create requires --kind once|interval|cron",retriable:!1,details:{command:"schedule create",flag:"kind"}});let o=j(t,"until-at"),i=j(t,"max-occurrences"),c=Z(t,"allow-unbounded"),d=y(t,"target-conversation-id"),l=d!==void 0?{target_conversation_id:d}:{},m;if(a==="once"){let h=j(t,"fire-at"),v=j(t,"delay-seconds");m={title:r,message:s,...l,spec:{kind:"once",...h!==void 0?{fire_at:h}:{},...v!==void 0?{delay_seconds:v}:{}}}}else if(a==="interval"){let h=j(t,"every-seconds"),v=j(t,"start-at");if(h===void 0)throw new u({code:"validation_error",message:"interval schedule requires --every-seconds",retriable:!1});m={title:r,message:s,...l,spec:{kind:"interval",every_seconds:h,...v!==void 0?{start_at:v}:{}},...o!==void 0?{until_at:o}:{},...i!==void 0?{max_occurrences:i}:{},...c!==void 0?{allow_unbounded:c}:{}}}else if(a==="cron"){let h=y(t,"expression"),v=y(t,"timezone");if(!h||!v)throw new u({code:"validation_error",message:"cron schedule requires --expression and --timezone",retriable:!1});m={title:r,message:s,...l,spec:{kind:"cron",expression:h,timezone:v},...o!==void 0?{until_at:o}:{},...i!==void 0?{max_occurrences:i}:{},...c!==void 0?{allow_unbounded:c}:{}}}else throw new u({code:"validation_error",message:`--kind must be one of once|interval|cron; got ${a}`,retriable:!1});return n.createSchedule(m)}},mf={verb:"list",summary:"List your active/historical schedules.",help:`silverhand schedule list [--status pending|firing|active|done|cancelled|failed|all]
|
|
428
428
|
[--limit N]
|
|
429
429
|
|
|
430
430
|
Lists this agent's schedules ordered by next_fire_at ASC. No cross-agent
|
|
@@ -434,13 +434,13 @@ Flags:
|
|
|
434
434
|
--status Default "all". "active" = pending OR firing.
|
|
435
435
|
--limit N Default 100, max 200.
|
|
436
436
|
|
|
437
|
-
stdout: ScheduleListOutput JSON.`,flags:["status","limit"],async run({client:n,args:t}){let r=y(t,"status");if(r&&!["pending","firing","active","done","cancelled","failed","all"].includes(r))throw new u({code:"validation_error",message:`--status must be one of pending|firing|active|done|cancelled|failed|all; got ${r}`,retriable:!1});let s=j(t,"limit"),
|
|
437
|
+
stdout: ScheduleListOutput JSON.`,flags:["status","limit"],async run({client:n,args:t}){let r=y(t,"status");if(r&&!["pending","firing","active","done","cancelled","failed","all"].includes(r))throw new u({code:"validation_error",message:`--status must be one of pending|firing|active|done|cancelled|failed|all; got ${r}`,retriable:!1});let s=j(t,"limit"),a={...r?{status:r}:{},...s!==void 0?{limit:s}:{}};return n.listSchedules(a)}},pf={verb:"cancel",summary:"Cancel one of your schedules.",help:`silverhand schedule cancel --schedule-id <id>
|
|
438
438
|
|
|
439
439
|
Cancels a pending or firing schedule. Terminal states (done, cancelled,
|
|
440
440
|
failed) are not cancellable. Cancel races with an in-flight fire are
|
|
441
441
|
accepted: the wake may still be delivered, but no further fires occur.
|
|
442
442
|
|
|
443
|
-
stdout: { "schedule": ScheduleDto }`,flags:["schedule-id"],async run({client:n,args:t}){let r=y(t,"schedule-id");if(!r)throw new u({code:"validation_error",message:"--schedule-id is required",retriable:!1});return n.cancelSchedule({schedule_id:r})}},
|
|
443
|
+
stdout: { "schedule": ScheduleDto }`,flags:["schedule-id"],async run({client:n,args:t}){let r=y(t,"schedule-id");if(!r)throw new u({code:"validation_error",message:"--schedule-id is required",retriable:!1});return n.cancelSchedule({schedule_id:r})}},Fi=[uf,mf,pf];import{constants as hf}from"node:fs";import{access as ff,mkdir as gf,rename as _f,stat as yf,writeFile as vf}from"node:fs/promises";import{homedir as bf}from"node:os";import{basename as Sf,join as Zt}from"node:path";var xf="SILVERHAND_DIR",kf={verb:"upload",summary:"Upload a local file as a chat attachment.",help:`silverhand file upload --path <abs_path> [--filename <name>]
|
|
444
444
|
[--content-type <mime>]
|
|
445
445
|
|
|
446
446
|
Reads the file at --path (must be absolute) and uploads it as an
|
|
@@ -454,20 +454,20 @@ Flags:
|
|
|
454
454
|
--content-type Optional MIME hint. Backend sniffs magic bytes and
|
|
455
455
|
falls back to file extension when omitted.
|
|
456
456
|
|
|
457
|
-
stdout: AttachmentDto JSON.`,flags:["path","filename","content-type"],async run({client:n,args:t}){let r=y(t,"path");if(!r)throw new u({code:"validation_error",message:"--path is required",retriable:!1});let s=y(t,"filename"),
|
|
457
|
+
stdout: AttachmentDto JSON.`,flags:["path","filename","content-type"],async run({client:n,args:t}){let r=y(t,"path");if(!r)throw new u({code:"validation_error",message:"--path is required",retriable:!1});let s=y(t,"filename"),a=y(t,"content-type");return n.uploadAttachment({path:r,...s?{filename:s}:{},...a?{contentType:a}:{}})}},wf={verb:"view",summary:"Resolve an attachment id to a readable local path.",help:`silverhand file view --attachment-id <id>
|
|
458
458
|
|
|
459
459
|
Resolve an attachment id to a local file path readable by this agent.
|
|
460
460
|
Cross-channel ids are rejected.
|
|
461
461
|
|
|
462
462
|
stdout: AttachmentLocateDto JSON:
|
|
463
|
-
{ storage: "local", local_path, filename, content_type }`,flags:["attachment-id"],async run({env:n,client:t,args:r}){let s=y(r,"attachment-id");if(!s)throw new u({code:"validation_error",message:"--attachment-id is required",retriable:!1});let
|
|
463
|
+
{ storage: "local", local_path, filename, content_type }`,flags:["attachment-id"],async run({env:n,client:t,args:r}){let s=y(r,"attachment-id");if(!s)throw new u({code:"validation_error",message:"--attachment-id is required",retriable:!1});let a=await t.locateAttachment(s);if(a.storage==="local"&&Ef(n.serverUrl)&&await Rf(a.local_path))return a;let o=await t.downloadAttachment(s);return{storage:"local",local_path:await Cf({conversationId:n.conversationId,attachmentId:s,filename:a.filename,buffer:o.buffer}),filename:a.filename,content_type:a.content_type||o.contentType}}},zi=[kf,wf];async function Rf(n){try{return(await yf(n)).isFile()?(await ff(n,hf.R_OK),!0):!1}catch{return!1}}function Ef(n){try{let{hostname:t}=new URL(n),r=t.toLowerCase();return r==="localhost"||r==="::1"||r==="[::1]"||r==="0:0:0:0:0:0:0:1"||r.startsWith("127.")}catch{return!1}}async function Cf(n){let t=Zt(Af(),Fs(n.conversationId),Fs(n.attachmentId));await gf(t,{recursive:!0});let r=Zt(t,Tf(n.filename)),s=Zt(t,`.${Fs(n.attachmentId)}.${process.pid}.${Date.now()}.tmp`);return await vf(s,n.buffer,{mode:384}),await _f(s,r),r}function Af(){let n=process.env[xf]?.trim();return n?Zt(n,"attachments-cache"):Zt(bf(),".silverhand","attachments-cache")}function Fs(n){return n.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Tf(n){return Sf(n.trim()||"attachment.bin").replace(/[\x00-\x1F\x7F]/g,"_").replace(/[\\/]/g,"_")||"attachment.bin"}import{readFile as Pf}from"node:fs/promises";import{basename as Wi,isAbsolute as Of}from"node:path";var If={verb:"get",summary:"Print the executing agent's profile MCP config (raw mcp.json).",help:`silverhand profile mcp get
|
|
464
464
|
|
|
465
465
|
Print the executing agent's profile MCP config \u2014 the raw \`mcp.json\`
|
|
466
466
|
that lives in the agent's global (L1) home and is loaded into every
|
|
467
467
|
spawn additively.
|
|
468
468
|
|
|
469
469
|
stdout: { "raw": <string|null> }. \`raw\` is the file's verbatim text,
|
|
470
|
-
or null when the agent has no profile MCP config yet.`,flags:[],async run({client:n}){return n.getProfileMcp()}},
|
|
470
|
+
or null when the agent has no profile MCP config yet.`,flags:[],async run({client:n}){return n.getProfileMcp()}},Mf={verb:"set",summary:"Replace the executing agent's profile MCP config (raw JSON on stdin).",help:`silverhand profile mcp set
|
|
471
471
|
|
|
472
472
|
Replace the executing agent's profile MCP config. Pipe the full
|
|
473
473
|
\`mcp.json\` text on stdin \u2014 it is validated and written VERBATIM
|
|
@@ -494,7 +494,7 @@ until it is respawned.
|
|
|
494
494
|
|
|
495
495
|
stdin: the raw mcp.json text (validated; invalid JSON / schema is
|
|
496
496
|
rejected with validation_error and nothing is written).
|
|
497
|
-
stdout: { "ok": true, "bytes_written": <n> }.`,flags:[],async run({client:n}){let t=await
|
|
497
|
+
stdout: { "ok": true, "bytes_written": <n> }.`,flags:[],async run({client:n}){let t=await zs("silverhand profile mcp set");return n.setProfileMcp(t)}},Df={verb:"validate",summary:"Validate profile MCP JSON from stdin without writing it.",help:`silverhand profile mcp validate
|
|
498
498
|
|
|
499
499
|
Validate \`mcp.json\` text from stdin against the canonical schema
|
|
500
500
|
WITHOUT writing it. A cheap local pre-check before \`set\` \u2014 it makes
|
|
@@ -502,7 +502,7 @@ no backend call.
|
|
|
502
502
|
|
|
503
503
|
stdin: the raw mcp.json text.
|
|
504
504
|
stdout: { "ok": true, "server_count": <n> } on success; a
|
|
505
|
-
validation_error (exit 1) describing the first problem otherwise.`,flags:[],async run(){let n=await
|
|
505
|
+
validation_error (exit 1) describing the first problem otherwise.`,flags:[],async run(){let n=await zs("silverhand profile mcp validate"),t=Mt(n);if(!t.ok)throw new u({code:"validation_error",message:t.error,retriable:!1});return{ok:!0,server_count:Object.keys(t.config.mcpServers).length}}},Lf={verb:"probe",summary:"Live-test one of this agent's profile MCP servers (connect + initialize).",help:`silverhand profile mcp probe --server <name> [--tools]
|
|
506
506
|
|
|
507
507
|
Open a ONE-SHOT live connection to a configured profile MCP server,
|
|
508
508
|
run the MCP \`initialize\` handshake, and close it immediately. Unlike
|
|
@@ -518,7 +518,7 @@ stdout: a McpProbeResult \u2014
|
|
|
518
518
|
{ "ok": false, "phase": "parse|not_found|connect|initialize|tools",
|
|
519
519
|
"message": "<redacted reason>" }
|
|
520
520
|
Connection failures are reported in the body (not an error). Secrets
|
|
521
|
-
(header/env values, URL query) never appear in \`message\`.`,flags:["server"],booleanFlags:["tools"],async run({client:n,args:t}){let r=t.flags.server;if(typeof r!="string"||r.length===0)throw new u({code:"validation_error",message:"`--server <name>` is required: the raw MCP server name to probe.",retriable:!1});return n.probeProfileMcp(r,t.flags.tools===!0)}},
|
|
521
|
+
(header/env values, URL query) never appear in \`message\`.`,flags:["server"],booleanFlags:["tools"],async run({client:n,args:t}){let r=t.flags.server;if(typeof r!="string"||r.length===0)throw new u({code:"validation_error",message:"`--server <name>` is required: the raw MCP server name to probe.",retriable:!1});return n.probeProfileMcp(r,t.flags.tools===!0)}},jf={verb:"add",summary:"Add servers to the executing agent's profile MCP config (merges; never clobbers existing).",help:`silverhand profile mcp add [--replace]
|
|
522
522
|
|
|
523
523
|
Add one or more MCP servers to the executing agent's profile config,
|
|
524
524
|
MERGING into what is already there \u2014 existing servers are always kept.
|
|
@@ -539,8 +539,8 @@ respawned.
|
|
|
539
539
|
|
|
540
540
|
stdin: a standard mcp.json ({ "mcpServers": { ... } }); validated
|
|
541
541
|
(invalid JSON / schema \u2192 validation_error, nothing written).
|
|
542
|
-
stdout: { "ok": true, "added": [<names>], "total": <n> }.`,flags:[],booleanFlags:["replace"],async run({client:n,args:t}){let r=await
|
|
543
|
-
`),{ok:!0,added:
|
|
542
|
+
stdout: { "ok": true, "added": [<names>], "total": <n> }.`,flags:[],booleanFlags:["replace"],async run({client:n,args:t}){let r=await zs("silverhand profile mcp add"),s=Mt(r);if(!s.ok)throw new u({code:"validation_error",message:s.error,retriable:!1});let a=s.config.mcpServers,o=Object.keys(a);if(o.length===0)throw new u({code:"validation_error",message:"nothing to add: the piped mcpServers is empty.",retriable:!1});let{raw:i}=await n.getProfileMcp(),c={};if(i!=null){let l=Mt(i);if(!l.ok)throw new u({code:"validation_error",message:`current mcp.json is not valid (${l.error}); fix it with \`set\` first.`,retriable:!1});c=l.config.mcpServers}if(t.flags.replace!==!0){let l=o.filter(m=>m in c);if(l.length>0)throw new u({code:"conflict",message:`server(s) already exist: ${l.join(", ")}. Use --replace to overwrite them, or \`remove\` them first. Other servers are never touched.`,retriable:!1})}let d={...c,...a};return await n.setProfileMcp(`${JSON.stringify({mcpServers:d},null,2)}
|
|
543
|
+
`),{ok:!0,added:o,total:Object.keys(d).length}}},Nf={verb:"remove",summary:"Remove one server from the executing agent's profile MCP config.",help:`silverhand profile mcp remove --server <name>
|
|
544
544
|
|
|
545
545
|
Remove a single server from the executing agent's profile MCP config,
|
|
546
546
|
leaving the others untouched. Reads the current \`mcp.json\`, deletes
|
|
@@ -554,8 +554,8 @@ written). To wipe the whole config instead, use \`clear\`.
|
|
|
554
554
|
Effect is NEXT SPAWN \u2014 a running agent keeps the old config until it
|
|
555
555
|
is respawned.
|
|
556
556
|
|
|
557
|
-
stdout: { "ok": true, "removed": <name>, "remaining": <n> }.`,flags:["server"],async run({client:n,args:t}){let r=t.flags.server;if(typeof r!="string"||r.length===0)throw new u({code:"validation_error",message:"`--server <name>` is required: the MCP server name to remove.",retriable:!1});let{raw:s}=await n.getProfileMcp();if(s==null)throw new u({code:"not_found",message:"no profile MCP config to remove from (it is unset).",retriable:!1});let
|
|
558
|
-
`),{ok:!0,removed:r,remaining:Object.keys(
|
|
557
|
+
stdout: { "ok": true, "removed": <name>, "remaining": <n> }.`,flags:["server"],async run({client:n,args:t}){let r=t.flags.server;if(typeof r!="string"||r.length===0)throw new u({code:"validation_error",message:"`--server <name>` is required: the MCP server name to remove.",retriable:!1});let{raw:s}=await n.getProfileMcp();if(s==null)throw new u({code:"not_found",message:"no profile MCP config to remove from (it is unset).",retriable:!1});let a=Mt(s);if(!a.ok)throw new u({code:"validation_error",message:`current mcp.json is not valid (${a.error}); fix it with \`set\` first.`,retriable:!1});let o=a.config.mcpServers;if(!(r in o))throw new u({code:"not_found",message:`server '${r}' is not in the profile MCP config.`,retriable:!1});return delete o[r],await n.setProfileMcp(`${JSON.stringify({mcpServers:o},null,2)}
|
|
558
|
+
`),{ok:!0,removed:r,remaining:Object.keys(o).length}}},Ff={verb:"clear",summary:"Remove ALL servers from the executing agent's profile MCP config.",help:`silverhand profile mcp clear
|
|
559
559
|
|
|
560
560
|
Clear the executing agent's profile MCP config \u2014 removes ALL servers
|
|
561
561
|
(writes \`{ "mcpServers": {} }\`). \`get\` then returns an empty config,
|
|
@@ -567,7 +567,7 @@ is respawned.
|
|
|
567
567
|
stdout: { "ok": true, "cleared": true }.`,flags:[],async run({client:n}){return await n.setProfileMcp(`{
|
|
568
568
|
"mcpServers": {}
|
|
569
569
|
}
|
|
570
|
-
`),{ok:!0,cleared:!0}}},
|
|
570
|
+
`),{ok:!0,cleared:!0}}},qi=[{facet:"mcp",summary:"Manage this agent's custom MCP servers.",commands:[If,Mf,jf,Nf,Ff,Df,Lf]}];function zf(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[7]===10?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=6&&n.toString("ascii",0,4)==="GIF8"?"image/gif":n.length>=12&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"?"image/webp":null}function Bi(n,t){if(n.byteLength===0)throw new u({code:"validation_error",message:"avatar source is empty (0 bytes).",retriable:!1});if(n.byteLength>5242880)throw new u({code:"validation_error",message:`avatar must be ${Et} or smaller.`,retriable:!1});let r=zf(n);if(!r)throw new u({code:"validation_error",message:"avatar must be a PNG, JPEG, GIF, or WEBP image (checked from the bytes).",retriable:!1});return{buffer:n,filename:t,contentType:r}}async function $f(n){if(!Of(n))throw new u({code:"validation_error",message:"--avatar-file must be an absolute path.",retriable:!1});let t;try{t=await Pf(n)}catch(r){throw new u({code:"not_found",message:`cannot read avatar file at ${n}: ${r instanceof Error?r.message:String(r)}`,retriable:!1})}return Bi(t,Wi(n))}var $i=5,Hi=2e4;async function Hf(n){let t;try{t=new URL(n)}catch{throw new u({code:"validation_error",message:`--avatar-url is not a valid URL: ${n}`,retriable:!1})}let r=new AbortController,s=setTimeout(()=>r.abort(),Hi);try{let a=t,o=0,i;for(;;){if(a.protocol!=="http:"&&a.protocol!=="https:")throw new u({code:"validation_error",message:`--avatar-url must be http(s); got ${a.protocol}`,retriable:!1});if(i=await fetch(a,{redirect:"manual",signal:r.signal}),i.status>=300&&i.status<400){let l=i.headers.get("location");if(!l)break;if(++o>$i)throw new u({code:"validation_error",message:`--avatar-url exceeded ${$i} redirects.`,retriable:!1});a=new URL(l,a);continue}break}if(!i.ok)throw new u({code:"validation_error",message:`--avatar-url download failed: HTTP ${i.status}.`,retriable:!1});let c=await Uf(i,5242880),d=Wi(a.pathname)||"avatar";return Bi(c,d)}catch(a){throw a instanceof u?a:a instanceof Error&&a.name==="AbortError"?new u({code:"validation_error",message:`--avatar-url download timed out after ${Hi}ms.`,retriable:!1}):new u({code:"validation_error",message:`--avatar-url download failed: ${a instanceof Error?a.message:String(a)}`,retriable:!1})}finally{clearTimeout(s)}}async function Uf(n,t){let r=n.body;if(!r){let i=Buffer.from(await n.arrayBuffer());if(i.byteLength>t)throw new u({code:"validation_error",message:`avatar must be ${Et} or smaller.`,retriable:!1});return i}let s=[],a=0,o=r.getReader();for(;;){let{done:i,value:c}=await o.read();if(i)break;if(c){if(a+=c.byteLength,a>t)throw await o.cancel(),new u({code:"validation_error",message:`avatar exceeds ${Et}; download aborted.`,retriable:!1});s.push(Buffer.from(c))}}return Buffer.concat(s)}var Wf={verb:"get",summary:"Print the executing agent's own profile (display name, description, avatar).",help:`silverhand profile get
|
|
571
571
|
|
|
572
572
|
Print the executing agent's own profile metadata \u2014 the identity and the
|
|
573
573
|
fields it can change with \`profile update\`. This is the SELF view (always
|
|
@@ -579,7 +579,7 @@ stdout: an AgentProfileDto \u2014
|
|
|
579
579
|
"description": <string|null>, "avatar_url": <string|null> }
|
|
580
580
|
\`avatar_url\` is a derived, read-only Silverhand URL (or null) \u2014 set the
|
|
581
581
|
avatar via \`profile update --avatar-file|--avatar-url\`, never by writing
|
|
582
|
-
this field.`,flags:[],async run({client:n}){let{profile:t}=await n.getProfile();return t}},
|
|
582
|
+
this field.`,flags:[],async run({client:n}){let{profile:t}=await n.getProfile();return t}},qf={verb:"update",summary:"Update the executing agent's own profile (display name, description, avatar).",help:`silverhand profile update [--display-name <name>] [--description <text>]
|
|
583
583
|
[--avatar-file <path> | --avatar-url <url> | --clear-avatar]
|
|
584
584
|
|
|
585
585
|
Update the executing agent's OWN profile (self only \u2014 there is no target
|
|
@@ -603,15 +603,15 @@ are mutually exclusive.
|
|
|
603
603
|
Order: the URL is downloaded (and the file read) BEFORE any write, so a bad
|
|
604
604
|
source leaves your profile untouched; the avatar is applied before the text.
|
|
605
605
|
|
|
606
|
-
stdout: the updated AgentProfileDto (same shape as \`profile get\`).`,flags:["display-name","description","avatar-file","avatar-url"],booleanFlags:["clear-avatar"],async run({client:n,args:t}){let r=y(t,"display-name"),s=y(t,"description"),
|
|
607
|
-
`)}function
|
|
606
|
+
stdout: the updated AgentProfileDto (same shape as \`profile get\`).`,flags:["display-name","description","avatar-file","avatar-url"],booleanFlags:["clear-avatar"],async run({client:n,args:t}){let r=y(t,"display-name"),s=y(t,"description"),a=y(t,"avatar-file"),o=y(t,"avatar-url"),i=Z(t,"clear-avatar")===!0,c=[a!==void 0,o!==void 0,i].filter(Boolean).length;if(c>1)throw new u({code:"validation_error",message:"choose at most one of --avatar-file, --avatar-url, --clear-avatar.",retriable:!1});let d=r!==void 0||s!==void 0;if(!d&&c===0)throw new u({code:"validation_error",message:"nothing to update: pass at least one of --display-name, --description, --avatar-file, --avatar-url, --clear-avatar.",retriable:!1});let l=null;if(d){let v={};r!==void 0&&(v.display_name=r),s!==void 0&&(v.description=s);let R=ha.safeParse(v);if(!R.success)throw new u({code:"validation_error",message:R.error.issues[0]?.message??"invalid profile fields",retriable:!1});l=R.data}let m=null;a!==void 0?m=await $f(a):o!==void 0&&(m=await Hf(o));let{profile:h}=await n.updateProfile({...l?.display_name!==void 0?{display_name:l.display_name}:{},...l&&"description"in l?{description:l.description??""}:{},...m?{avatar:{action:"set",buffer:m.buffer,filename:m.filename,contentType:m.contentType}}:i?{avatar:{action:"clear"}}:{}});return h}},Vi=[Wf,qf];async function zs(n){if(process.stdin.isTTY)throw new u({code:"validation_error",subkind:"stdin_is_tty",message:`${n} reads the mcp.json text from stdin, but stdin is a TTY. Pipe it \u2014 e.g. \`cat mcp.json | ${n}\` or \`${n} <<'SILVERHAND_EOF' ... SILVERHAND_EOF\`.`,retriable:!1});let t=[];for await(let s of process.stdin)t.push(Buffer.isBuffer(s)?s:Buffer.from(s));let r=Buffer.concat(t);if(r.byteLength===0)throw new u({code:"validation_error",subkind:"empty_stdin",message:`${n} received 0 bytes on stdin. Pipe the mcp.json text.`,retriable:!1});return r.toString("utf8")}var $s=[{noun:"message",summary:"Send messages, read history, search visible text.",commands:Ti,removedVerbs:{read:{replacement:"history",hint:"use `silverhand message history` to read recent messages (or pass --before-seq | --after-seq | --around for an anchor). For full-text lookup across the workspace use `silverhand message search`."}}},{noun:"task",summary:"View, create, claim, release, and update task board entries.",commands:Mi},{noun:"thread",summary:"Follow or unfollow reply clusters under messages.",commands:Di,removedVerbs:{create:{replacement:"follow",hint:"isolated thread creation has been removed. Reply to a message with `silverhand message send --target thread:<message_id>`; use `silverhand channel create` only when the user explicitly asks for an isolated channel."},close:{replacement:"unfollow",hint:"reply clusters have no close operation. Use `silverhand thread unfollow --root <message_id>` to stop receiving a cluster, or read a legacy isolated thread via `message history --target conversation:<conversation_id>`."}}},{noun:"channel",summary:"Create or list top-level channels in a workspace.",commands:Li},{noun:"member",summary:"Add an existing workspace member to the current conversation (channel or thread).",commands:ji},{noun:"workspace",summary:"List the workspaces this agent can reach.",commands:Ni},{noun:"schedule",summary:"Create, list, or cancel self-wake schedules.",commands:Fi},{noun:"file",summary:"Upload a local file or resolve an attachment id.",commands:zi},{noun:"profile",summary:"Manage the executing subject's global (L1) config \u2014 e.g. custom MCP servers.",commands:Vi,facets:qi}];function Xe(n){return $s.find(t=>t.noun===n)}function cr(n,t){return Xe(n)?.commands.find(r=>r.verb===t)}function Yt(n,t){return Xe(n)?.facets?.find(r=>r.facet===t)}function Gi(n,t,r){return Yt(n,t)?.commands.find(s=>s.verb===r)}var Bf="0.0.0";function Ki(){let n=[];n.push(`silverhand ${Bf}`),n.push(""),n.push("Usage: silverhand <noun> <verb> [flags...]"),n.push(""),n.push("All chat, task, schedule, history, thread, channel, workspace,"),n.push("and file actions for spawned Silverhand agents. The CLI is already"),n.push("configured for the current session; do not pass connection details"),n.push("as flags."),n.push(""),n.push("Output: machine-readable JSON on stdout. (--json is the default and"),n.push("is accepted as a no-op on every subcommand.)"),n.push('Errors: one-line JSON on stderr ({ "error": { code, message,'),n.push(" retriable } }) plus a non-zero exit code:"),n.push(" 1 = user/input error (do not retry)"),n.push(" 2 = transient (may retry with backoff)"),n.push(" 3 = fatal (stop and report)"),n.push(""),n.push("Nouns:");for(let t of $s)n.push(` ${t.noun.padEnd(10)} ${t.summary}`);return n.push(""),n.push("Run `silverhand <noun> --help` to list verbs."),n.push("Run `silverhand <noun> <verb> --help` for flag-level usage."),n.join(`
|
|
607
|
+
`)}function Zi(n){let t=Xe(n);if(!t)return null;let r=[];if(r.push(`silverhand ${n} \u2014 ${t.summary}`),r.push(""),t.facets&&t.facets.length>0){r.push("Facets:");for(let s of t.facets)r.push(` ${s.facet.padEnd(10)} ${s.summary}`);if(r.push(""),t.commands.length>0){r.push("Verbs:");for(let s of t.commands)r.push(` ${s.verb.padEnd(10)} ${s.summary}`);r.push(""),r.push(`Run \`silverhand ${n} <facet> --help\` to list a facet's verbs, or \`silverhand ${n} <verb> --help\` for a flat verb.`)}else r.push(`Run \`silverhand ${n} <facet> --help\` to list verbs.`);return r.join(`
|
|
608
608
|
`)}r.push("Verbs:");for(let s of t.commands)r.push(` ${s.verb.padEnd(10)} ${s.summary}`);return r.push(""),r.push(`Run \`silverhand ${n} <verb> --help\` for flag-level usage.`),r.join(`
|
|
609
|
-
`)}function
|
|
610
|
-
`)}function
|
|
611
|
-
`)}var
|
|
609
|
+
`)}function Yi(n,t){let r=Xe(n),s=Yt(n,t);if(!r||!s)return null;let a=[];a.push(`silverhand ${n} ${t} \u2014 ${s.summary}`),a.push(""),a.push("Verbs:");for(let o of s.commands)a.push(` ${o.verb.padEnd(10)} ${o.summary}`);return a.push(""),a.push(`Run \`silverhand ${n} ${t} <verb> --help\` for flag-level usage.`),a.join(`
|
|
610
|
+
`)}function Ji(n,t){let r=cr(n,t);return r?r.help:null}function Xi(n,t,r){let s=Gi(n,t,r);return s?s.help:null}function Qi(n,t=process.stdout){t.write(JSON.stringify(n)+`
|
|
611
|
+
`)}var Vf=new Set(["json"]);function ec(n,t){if(t.removedFlags)for(let d of Object.keys(n)){let l=t.removedFlags[d];if(l)throw new u({code:"validation_error",subkind:"flag_removed",message:`--${d} was removed; ${l.hint}`,retriable:!1,details:{flag:d,replacement:l.replacement}})}let r=new Set([...t.flags??[],...t.booleanFlags??[],...Object.keys(t.removedFlags??{}),...Vf]),s=Object.keys(n).filter(d=>!r.has(d));if(s.length===0)return;let a=s[0],o=Gf(a,r),i=o?`did you mean --${o}?`:`run \`silverhand ${t.noun} ${t.verb} --help\` for accepted flags`,c=s.length>1?` (also unrecognized: ${s.slice(1).map(d=>`--${d}`).join(", ")})`:"";throw new u({code:"validation_error",subkind:"unknown_flag",message:`unknown flag --${a}; ${i}${c}`,retriable:!1,details:{flag:a,...o?{suggestion:o}:{},...s.length>1?{other_unknown:s.slice(1)}:{}}})}function Gf(n,t){let r=null;for(let s of t){let a=Kf(n,s);a<=2&&(!r||a<r.distance)&&(r={name:s,distance:a})}return r?.name??null}function Kf(n,t){if(n===t)return 0;if(n.length===0)return t.length;if(t.length===0)return n.length;let r=new Array(t.length+1);for(let s=0;s<=t.length;s+=1)r[s]=s;for(let s=1;s<=n.length;s+=1){let a=new Array(t.length+1);a[0]=s;for(let o=1;o<=t.length;o+=1){let i=n.charCodeAt(s-1)===t.charCodeAt(o-1)?0:1;a[o]=Math.min(a[o-1]+1,r[o]+1,r[o-1]+i)}r=a}return r[t.length]}var Re={};async function Zf(n){if(n.length===0||n[0]==="--help"||n[0]==="-h")return process.stdout.write(Ki()+`
|
|
612
612
|
`),0;if(n[0]==="--version"||n[0]==="-V")return process.stdout.write(`silverhand 0.0.0
|
|
613
|
-
`),0;let t=n[0];Re.noun=t;let r=Xe(t);if(!r)throw new u({code:"validation_error",message:`unknown noun "${t}"; run \`silverhand --help\` for available nouns`,retriable:!1});if(n.length===1||n[1]==="--help"||n[1]==="-h"){let
|
|
614
|
-
`),0}if(r.facets&&r.facets.length>0){let
|
|
615
|
-
`),0}let c=n[2];Re.verb=`${
|
|
616
|
-
`),0;let
|
|
617
|
-
`,1)[0]?.slice(0,500),duration_ms:Math.round((
|
|
613
|
+
`),0;let t=n[0];Re.noun=t;let r=Xe(t);if(!r)throw new u({code:"validation_error",message:`unknown noun "${t}"; run \`silverhand --help\` for available nouns`,retriable:!1});if(n.length===1||n[1]==="--help"||n[1]==="-h"){let o=Zi(t);if(!o)throw new u({code:"validation_error",message:`no help for noun "${t}"`,retriable:!1});return process.stdout.write(o+`
|
|
614
|
+
`),0}if(r.facets&&r.facets.length>0){let o=n[1],i=Yt(t,o);if(i){if(Re.verb=o,n.length===2||n[2]==="--help"||n[2]==="-h"){let l=Yi(t,o);return l&&process.stdout.write(l+`
|
|
615
|
+
`),0}let c=n[2];Re.verb=`${o} ${c}`;let d=i.commands.find(l=>l.verb===c);if(!d)throw new u({code:"validation_error",message:`unknown verb "${c}" under "${t} ${o}"; run \`silverhand ${t} ${o} --help\``,retriable:!1});return tc(d,n.slice(3),{noun:t,verb:`${o} ${c}`,helpText:Xi(t,o,c)})}}let s=n[1];Re.verb=s;let a=cr(t,s);if(!a){let o=r.removedVerbs?.[s];throw o?new u({code:"validation_error",subkind:"verb_removed",message:`silverhand ${t} ${s} is not a verb; ${o.hint}`,retriable:!1,details:{noun:t,verb:s,replacement:o.replacement}}):new u({code:"validation_error",message:`unknown verb "${s}" under noun "${t}"; run \`silverhand ${t} --help\``,retriable:!1})}return tc(a,n.slice(2),{noun:t,verb:s,helpText:Ji(t,s)})}async function tc(n,t,r){let{noun:s,verb:a}=r;if(t.includes("--help")||t.includes("-h"))return r.helpText&&process.stdout.write(r.helpText+`
|
|
616
|
+
`),0;let o=Ai(t,{booleanFlags:n.booleanFlags});if(Re.flagsSeen=Object.keys(o.flags).sort(),ec(o.flags,{noun:s,verb:a,flags:n.flags,booleanFlags:n.booleanFlags,removedFlags:n.removedFlags}),!n.allowPositional&&o.positional.length>0||o.rest.length>0){let l=[];throw!n.allowPositional&&o.positional.length>0&&l.push(`positional ${JSON.stringify(o.positional)}`),o.rest.length>0&&l.push(`after-\`--\` ${JSON.stringify(o.rest)}`),new u({code:"validation_error",subkind:"unexpected_arguments",message:`silverhand ${s} ${a} ${n.allowPositional?"does not accept tokens after `--`":"accepts flags only"}; got unexpected ${l.join(" and ")}. `+(n.allowPositional?"If the positional value contains spaces, quote it as one shell argument.":"If a value contains spaces or quotes, pipe it via stdin or use a quoted heredoc."),retriable:!1,details:{positional:n.allowPositional?[]:o.positional,rest:o.rest}})}let i=Er(),c=new bn(i),d=await n.run({env:i,client:c,args:o});return d!=null&&Qi(d),0}var Yf=nc.now();Zf(process.argv.slice(2)).then(n=>{process.exit(n)},async n=>{let t=Ga(n);Za(t,{json:!0}),Xa()||await Qa({noun:Re.noun,verb:Re.verb,flags_seen:Re.flagsSeen,error_code:t.code,...t.subkind?{error_subkind:t.subkind}:{},error_message:t.message.split(`
|
|
617
|
+
`,1)[0]?.slice(0,500),duration_ms:Math.round((nc.now()-Yf)*1e3)/1e3}),process.exit(Ka(t.code))});
|