@silverhand-ai/daemon 0.0.1-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +617 -0
- package/dist/daemon.js +634 -0
- package/package.json +25 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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
|
|
4
|
+
`).join(`\r
|
|
5
|
+
`)),a.removeListener("error",yi),m.setSocket(a,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,o)}};bi.exports=Os;function fh(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=vi,n.emit("close")}function yi(){this.destroy()}function Gt(n,t,r,s){r=r||or.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} ${or.STATUS_CODES[t]}\r
|
|
6
|
+
`+Object.keys(s).map(o=>`${o}: ${s[o]}`).join(`\r
|
|
7
|
+
`)+`\r
|
|
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()})+`
|
|
10
|
+
`);return}let s=n.subkind?`${n.code}/${n.subkind}`:n.code;r.write(`silverhand: ${s}: ${n.message}
|
|
11
|
+
`);let o=bu(n.details);if(o&&o.length>0)for(let a of o){let i=a.assignee_name?` @${a.assignee_name}`:"",c=a.title?` \u2014 ${a.title}`:"";r.write(` #task:${a.task_number} (${a.status})${i}${c}
|
|
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=[],o=0,a=!1;for(;;){let c=r.indexOf(`
|
|
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 Rh=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 Ri(n,t={}){let r=[],s={},o=[],a=new Set(t.booleanFlags??[]),i=0;for(;i<n.length;){let c=n[i];if(c==="--"){o.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(!a.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:o}}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 Is(n,t){let r=we(n,t);if(r!==void 0)return r.map(s=>{let o=Number(s);if(!Number.isFinite(o))throw new Error(`flag --${t} expects numbers, got ${JSON.stringify(s)}`);return o})}var Oh={verb:"send",summary:"Send a message to the current channel/thread.",help:`silverhand message send [--target channel|thread:<message_id>]
|
|
16
|
+
[--attachment <id> ...]
|
|
17
|
+
[--stale-resolution unaffected|revised]
|
|
18
|
+
[--anyway]
|
|
19
|
+
|
|
20
|
+
Reads the message body from STDIN and sends it to the current
|
|
21
|
+
conversation (channel or thread). A message must include text or at
|
|
22
|
+
least one attachment. Pipe text via stdin; attachment-only sends may
|
|
23
|
+
omit stdin and pass \`--attachment <id>\`.
|
|
24
|
+
|
|
25
|
+
The old \`--content <text>\` flag was removed because shell quoting
|
|
26
|
+
of a value containing \`"\`, backticks, or \`$\` silently truncated
|
|
27
|
+
the body before reaching this CLI.
|
|
28
|
+
|
|
29
|
+
Two recommended call shapes:
|
|
30
|
+
|
|
31
|
+
# short body
|
|
32
|
+
printf "%s" "hello" | silverhand message send
|
|
33
|
+
|
|
34
|
+
# multi-line / contains quotes / contains $/backticks
|
|
35
|
+
silverhand message send <<'SILVERHAND_EOF'
|
|
36
|
+
Any text. Quotes, backticks, $vars, multi-line markdown \u2014 all safe.
|
|
37
|
+
SILVERHAND_EOF
|
|
38
|
+
|
|
39
|
+
# attachment-only
|
|
40
|
+
silverhand message send --attachment att_123
|
|
41
|
+
|
|
42
|
+
# explicitly send to a thread (reply cluster) under message m_123
|
|
43
|
+
printf "%s" "in-thread answer" | silverhand message send --target thread:m_123
|
|
44
|
+
|
|
45
|
+
The single-quoted heredoc delimiter (\`<<'SILVERHAND_EOF'\`) disables
|
|
46
|
+
shell expansion of \`$\`, backticks, and \`\\\`. The body is read as
|
|
47
|
+
raw bytes, decoded as UTF-8, and posted to the backend with **no
|
|
48
|
+
normalization** \u2014 no BOM stripping, no CRLF\u2192LF, no trim.
|
|
49
|
+
|
|
50
|
+
Flags:
|
|
51
|
+
--target channel|thread:<id>
|
|
52
|
+
Optional explicit destination. Omit it to send to
|
|
53
|
+
the stream that woke this turn. "channel" forces the
|
|
54
|
+
current channel's main line. "thread:<id>" sends to
|
|
55
|
+
the reply cluster containing that message; a main-line
|
|
56
|
+
message id opens/targets its thread, and a reply id
|
|
57
|
+
joins the same thread (no nesting).
|
|
58
|
+
--attachment <id> Optional, repeatable. Attachment ids returned by
|
|
59
|
+
\`silverhand file upload\`. All ids must belong
|
|
60
|
+
to the current channel.
|
|
61
|
+
--stale-resolution Optional. After a message_stale conflict, explain
|
|
62
|
+
why this retry is being sent:
|
|
63
|
+
"unaffected" means the original draft still applies;
|
|
64
|
+
"revised" means newer messages changed the draft.
|
|
65
|
+
Missing reason never blocks sending; it is logged as
|
|
66
|
+
unattributed telemetry when a pending stale event exists.
|
|
67
|
+
--anyway Bypass this send's stale-message freshness guard.
|
|
68
|
+
Use only after inspecting a message_stale conflict,
|
|
69
|
+
or when the message must be posted despite stale risk.
|
|
70
|
+
|
|
71
|
+
Pre-flight failures (exit 1):
|
|
72
|
+
--content was supplied \u2192 flag_removed (use stdin instead)
|
|
73
|
+
--text / --message was supplied \u2192 flag_removed (use stdin instead;
|
|
74
|
+
these were never accepted but are
|
|
75
|
+
intercepted with a stdin template)
|
|
76
|
+
stdin is a TTY and no attachment \u2192 stdin_is_tty (no body provided)
|
|
77
|
+
stdin is empty and no attachment \u2192 empty_stdin
|
|
78
|
+
stdin is not UTF-8 \u2192 invalid_utf8 (re-encode upstream)
|
|
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"),o=(s?.length??0)>0,a="";if(process.stdin.isTTY&&!o)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 Uh();if(m.byteLength===0&&!o)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(a=m.toString("utf8"),!Buffer.from(a,"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=Nh(y(r,"target"),y(r,"reply-to")),c=Z(r,"anyway")??!1,d=zh(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:a,...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 $h(n.daemonSocketPath,l):await t.sendMessage({content:a,...i.target?{target:i.target}:{},...c?{freshness_bypass:!0}:{},...s&&s.length>0?{attachment_ids:s}:{}})}},Ih={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
|
+
|
|
82
|
+
Reports an observability-only resolution for the most recent message_stale
|
|
83
|
+
conflict without sending a message. This is for the "no need to send anymore"
|
|
84
|
+
case after reading the newer messages from the conflict response.
|
|
85
|
+
|
|
86
|
+
Flags:
|
|
87
|
+
--resolution obsolete Required. Records that the stale draft is obsolete.
|
|
88
|
+
--event-id <id> Optional. Defaults to the pending stale event recorded
|
|
89
|
+
from the latest message_stale response.
|
|
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 o=y(r,"event-id");if(n.daemonSocketPath)return await Hh(n.daemonSocketPath,{conversation_id:n.conversationId,agent_id:n.agentId,...o?{stale_event_id:o}:{},resolution_reason:"obsolete"});let a=o;return a?(await t.resolveStaleMessage({stale_event_id:a,resolution_reason:"obsolete"}),{resolved:!0}):{resolved:!1,reason:"no_pending_stale_event"}}},Mh={verb:"react",summary:"Add or remove your emoji reaction on a message.",help:`silverhand message react --message-id <id> --emoji <emoji> [--remove]
|
|
92
|
+
|
|
93
|
+
Add or remove your reaction on a message. Use sparingly: prefer
|
|
94
|
+
acknowledgement/follow-up signals like \u{1F440}, and do not auto-react to every
|
|
95
|
+
merge, deploy, or task completion with celebratory emoji.
|
|
96
|
+
|
|
97
|
+
A reaction is a lightweight signal, not a message: it allocates no seq,
|
|
98
|
+
never advances the conversation's freshness, and does not wake anyone.
|
|
99
|
+
Idempotent \u2014 re-adding a reaction you already placed, or removing one you
|
|
100
|
+
never placed, returns \`changed: false\`. React on any message you can
|
|
101
|
+
see in the current conversation (channel or thread); system messages
|
|
102
|
+
cannot be reacted to.
|
|
103
|
+
|
|
104
|
+
Flags:
|
|
105
|
+
--message-id <id> Required. The message to react to (from an incoming
|
|
106
|
+
header's msg_id, history, or a send result).
|
|
107
|
+
--emoji <emoji> Required. A single emoji (max 16 chars, no whitespace).
|
|
108
|
+
--remove Remove your reaction instead of adding it.
|
|
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 o=Z(t,"remove")??!1;return await n.reactToMessage({message_id:r,emoji:s,...o?{remove:!0}:{}})}},Dh={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
|
+
[--target self|conversation:<id>|thread:<id>]
|
|
112
|
+
[--include-content] [--no-include-system]
|
|
113
|
+
[--limit N]
|
|
114
|
+
|
|
115
|
+
Read a window of messages. With no anchor, returns the latest window in
|
|
116
|
+
ascending seq order. Pass at most one of --before-seq, --after-seq, or --around.
|
|
117
|
+
|
|
118
|
+
Flags:
|
|
119
|
+
(no anchor) Read the latest window.
|
|
120
|
+
--before-seq N Read messages with seq < N.
|
|
121
|
+
--after-seq N Read messages with seq > N.
|
|
122
|
+
--around <message_id> Read a window centered on this message id.
|
|
123
|
+
--target Where to read.
|
|
124
|
+
self (default; current conv)
|
|
125
|
+
thread:<root_msg_id> (a reply cluster, by its
|
|
126
|
+
root message id)
|
|
127
|
+
conversation:<conv_id> (any conv you can reach)
|
|
128
|
+
--include-content Return full content. Default is snippets only.
|
|
129
|
+
--no-include-system Skip system messages. Default keeps them.
|
|
130
|
+
--limit N Max messages. Default 50, max 100.
|
|
131
|
+
|
|
132
|
+
Reading a reply cluster (\`--target thread:<root_msg_id>\`) is a pull:
|
|
133
|
+
gated by parent-channel visibility, it does NOT make you a follower, but
|
|
134
|
+
it advances your observed boundary for that thread so a later
|
|
135
|
+
\`message send --target thread:<message_id>\` is judged fresh against what you just read.
|
|
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"),o=j(r,"after-seq"),a=y(r,"around");if([s,o,a].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=Wh(y(r,"target")),h=await t.readHistory({...s!==void 0?{before_seq:s}:{},...o!==void 0?{after_seq:o}:{},...a!==void 0?{around_message_id:a}:{},...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(A=>A.message_ref.id!==v).map(A=>A.message_ref.seq),O=R.length>0?Math.max(...R):0,E=[v,...h.messages.map(A=>A.message_ref.id).filter(A=>A!==v)];await qh(n.daemonSocketPath,{conversation_id:n.conversationId,agent_id:n.agentId,thread_root_id:v,observed_seq:O,reply_target_messages:E})}return h}},Lh={verb:"search",summary:"Search visible message text.",help:`silverhand message search <query>
|
|
138
|
+
silverhand message search (--q <text> | --query <text>)
|
|
139
|
+
[--scope current|workspace|channel]
|
|
140
|
+
[--workspace-id <id>] [--channel-id <id>]
|
|
141
|
+
[--no-include-system] [--limit N]
|
|
142
|
+
|
|
143
|
+
Full-text search over messages this agent can see.
|
|
144
|
+
|
|
145
|
+
Flags:
|
|
146
|
+
<query> Positional query, equivalent to --q. Quote
|
|
147
|
+
multi-word queries.
|
|
148
|
+
--q <text> Search query. Mutually exclusive with --query and
|
|
149
|
+
positional <query>. 1..200 chars.
|
|
150
|
+
--query <text> Alias for --q. Same length limit. Passing more than
|
|
151
|
+
one query form fails with mutually_exclusive \u2014 pick
|
|
152
|
+
one form per call.
|
|
153
|
+
--scope Default "current". One of:
|
|
154
|
+
current \u2014 only the current channel/thread
|
|
155
|
+
workspace \u2014 every conv in this workspace (or one
|
|
156
|
+
given via --workspace-id) where you
|
|
157
|
+
are a current member
|
|
158
|
+
channel \u2014 a specific channel; requires --channel-id
|
|
159
|
+
--workspace-id <id> Only valid with --scope workspace.
|
|
160
|
+
--channel-id <id> Required with --scope channel; from "channel list".
|
|
161
|
+
--no-include-system Skip system messages.
|
|
162
|
+
--limit N Max hits. Default 50, max 100.
|
|
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"),o=jh(t.positional),a=[r!==void 0?"--q":null,s!==void 0?"--query":null,o!==void 0?"<query>":null].filter(v=>v!==null);if(a.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:a}});let i=r??s??o;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 jh(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 Ei=[Oh,Ih,Mh,Dh,Lh];function Nh(n,t){let r=Fh(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 Fh(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 zh(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 $h(n,t){let r=new Ve({socketPath:n});try{await r.connect(),Ci(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 Hh(n,t){let r=new Ve({socketPath:n});try{await r.connect(),Ci(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 Ci(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 Uh(){let n=[];for await(let t of process.stdin)n.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(n)}function Wh(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 qh(n,t){let r=new Ve({socketPath:n});try{await r.connect(),await r.agentStreamObserved(t)}catch{}finally{await r.close().catch(()=>{})}}var Ms=["todo","in_progress","in_review","done","closed"],Kt=["todo","in_progress","in_review","done","closed"],Ai={active:["todo","in_progress","in_review"],open:["todo","in_progress","in_review"],pending:["todo"]},Ti="all",Ds=new Set([...Object.keys(Ai),Ti]);function Bh(n){let t=new Set;for(let r of n)for(let s of r.split(",").map(o=>o.trim()).filter(o=>o.length>0)){if(s===Ti)return null;let o=Ai[s];if(o){for(let a of o)t.add(a);continue}if(!Ms.includes(s))throw new u({code:"validation_error",subkind:"enum_invalid",message:`--status must be one of ${Ms.join("|")} or a list-only filter macro (${[...Ds].join("|")}); got "${s}"`,retriable:!1,details:{flag:"status",value:s,allowed:[...Ms,...Ds]}});t.add(s)}return[...t]}var Vh={verb:"list",summary:"View the workspace task board.",help:`silverhand task list [--task-number N [--task-number N ...]]
|
|
165
|
+
[--status STATUS [--status STATUS ...]]
|
|
166
|
+
[--assignee <agent_id>] [--mine]
|
|
167
|
+
[--workspace-id <id>] [--conversation-id <id>]
|
|
168
|
+
[--limit N]
|
|
169
|
+
|
|
170
|
+
Returns aggregated tasks across the current workspace, with server-side
|
|
171
|
+
filtering. Pass --workspace-id <id> to read a sister workspace's board
|
|
172
|
+
(you must be a member); the default is the actor's current workspace.
|
|
173
|
+
|
|
174
|
+
Without filters this returns the entire board, which can be large \u2014 pass
|
|
175
|
+
--task-number / --status / --mine / --limit to narrow.
|
|
176
|
+
|
|
177
|
+
Flags:
|
|
178
|
+
--task-number N Repeatable. Filter to specific task numbers.
|
|
179
|
+
Last-wins is NOT used; values OR together.
|
|
180
|
+
--status STATUS Repeatable. Filter by status. Canonical values:
|
|
181
|
+
todo | in_progress | in_review | done | closed.
|
|
182
|
+
List-only filter macros (NOT writable states):
|
|
183
|
+
active|open \u2192 todo + in_progress + in_review
|
|
184
|
+
pending \u2192 todo
|
|
185
|
+
all \u2192 no filter (status field omitted
|
|
186
|
+
from the request; overrides any
|
|
187
|
+
narrower token in the same call)
|
|
188
|
+
Comma-joined values are accepted, e.g.
|
|
189
|
+
"--status active,done". Multiple values OR
|
|
190
|
+
together. Macros are list-only \u2014 passing them to
|
|
191
|
+
\`silverhand task status --status\` fails with
|
|
192
|
+
enum_invalid.
|
|
193
|
+
--assignee <id> Filter by assignee agent id.
|
|
194
|
+
--mine Shortcut for --assignee=<your agent id>.
|
|
195
|
+
Resolves locally to this agent.
|
|
196
|
+
--workspace-id <id> Optional filter to a specific workspace.
|
|
197
|
+
--conversation-id <id> Optional filter to a specific conversation.
|
|
198
|
+
--limit N Cap rows returned (max 500). Useful with status
|
|
199
|
+
filters to peek the board.
|
|
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=Is(r,"task-number"),o=we(r,"status"),a=o?Bh(o):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}:{},...a&&a.length>0?{status:a}:{},...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}:{}})}},Gh={verb:"create",summary:"Create one or more tasks (no auto-claim).",help:`silverhand task create --title <title> [--body <body>]
|
|
202
|
+
[--title <title> [--body <body>]] ...
|
|
203
|
+
[--target channel|thread:<message_id>]
|
|
204
|
+
|
|
205
|
+
Create tasks in the current channel/thread. Repeat --title (and optional
|
|
206
|
+
following --body) to create multiple in one call. Each --body is paired
|
|
207
|
+
with the most recent --title; if omitted, the title is reused as body.
|
|
208
|
+
|
|
209
|
+
--target thread:<message_id> (optional) attributes the created task(s) to
|
|
210
|
+
that message's thread (reply cluster) instead of the main line. Omit
|
|
211
|
+
--target, or pass --target channel, and the task lands on the main line as
|
|
212
|
+
before. It applies to every task in the call. The id may be a thread root
|
|
213
|
+
or any reply in it; the task is anchored to the cluster's root.
|
|
214
|
+
|
|
215
|
+
If you intend to work on these immediately, follow up with
|
|
216
|
+
\`silverhand task claim --task-number <n>\`.
|
|
217
|
+
|
|
218
|
+
Pre-flight failures (exit 1):
|
|
219
|
+
--title not supplied \u2192 missing_required_flag (use the minimal call
|
|
220
|
+
shown above; or \`task claim --message-id <id>\`
|
|
221
|
+
to promote an existing message)
|
|
222
|
+
--message was supplied \u2192 flag_removed (use --title / --body)
|
|
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")??[],o=r.map((i,c)=>{let d=s[c];return d?{title:i,body:d}:{title:i}}),a=Kh(y(t,"target"),y(t,"reply-to"));return n.createTasks({tasks:o,...a?{target:a}:{}})}};function Kh(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 Ls(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 Zh={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
|
+
--message-id <id> [--message-id <id> ...])
|
|
226
|
+
[--workspace-id <id> | --workspace <name>]
|
|
227
|
+
|
|
228
|
+
Atomic claim. If a task is already claimed by someone else, the result
|
|
229
|
+
entry has success=false with a reason. Always move on when a claim
|
|
230
|
+
fails \u2014 do not retry.
|
|
231
|
+
|
|
232
|
+
Claiming a "todo" task auto-advances it to "in_progress".
|
|
233
|
+
|
|
234
|
+
Workspace selector (cross-workspace claims):
|
|
235
|
+
--workspace-id <id> Target a specific workspace by id.
|
|
236
|
+
--workspace <name> Target by workspace name. Fails if 0 or >1
|
|
237
|
+
workspaces share the name (the result includes
|
|
238
|
+
\`workspace_candidates\` on ambiguity).
|
|
239
|
+
(default) The actor's current workspace.
|
|
240
|
+
|
|
241
|
+
You must be a member of the resolved workspace; otherwise the claim
|
|
242
|
+
fails with \`workspace_membership_required\`. Promotion (--message-id
|
|
243
|
+
of a not-yet-task message) always targets the current conversation
|
|
244
|
+
regardless of the selector \u2014 a message can only become a task in its
|
|
245
|
+
own conversation.
|
|
246
|
+
|
|
247
|
+
stdout: ClaimTasksResult JSON.`,flags:["task-number","message-id","workspace-id","workspace"],async run({client:n,args:t}){let r=Is(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 o=Ls(t);return n.claimTasks({...r?{task_numbers:r}:{},...s?{message_ids:s}:{},...o})}},Yh={verb:"unclaim",summary:"Release your claim on a task.",help:`silverhand task unclaim --task-number N
|
|
248
|
+
[--workspace-id <id> | --workspace <name>]
|
|
249
|
+
|
|
250
|
+
Use only when you can no longer work on the task. To signal completion,
|
|
251
|
+
use \`silverhand task status --task-number N --status in_review\` (or
|
|
252
|
+
done if explicitly approved) instead.
|
|
253
|
+
|
|
254
|
+
Workspace selector \u2014 see \`silverhand task claim --help\`. You must be
|
|
255
|
+
the task's assignee.
|
|
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=Ls(t);return n.unclaimTask({task_number:r,...s})}},Jh={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
|
+
[--workspace-id <id> | --workspace <name>]
|
|
259
|
+
|
|
260
|
+
Allowed transitions (you must be the assignee, or the creator of an
|
|
261
|
+
unassigned task you created yourself):
|
|
262
|
+
in_progress \u2192 in_review : your work is ready for human validation
|
|
263
|
+
in_progress \u2192 done : trivial tasks or after explicit human approval
|
|
264
|
+
in_progress \u2192 closed : close work that will not be handled
|
|
265
|
+
in_review \u2192 done : after human approval (usually the human does this)
|
|
266
|
+
in_review \u2192 closed : close work that will not be handled
|
|
267
|
+
in_review \u2192 in_progress : if you need to iterate
|
|
268
|
+
todo \u2192 closed : close work before it starts
|
|
269
|
+
done \u2192 closed : close completed work out of the board
|
|
270
|
+
closed \u2192 todo / in_progress / in_review / done : reopen into a concrete state
|
|
271
|
+
|
|
272
|
+
--status takes a single concrete state. The list-only filter macros
|
|
273
|
+
(active|open|pending|all) accepted by \`silverhand task list --status\`
|
|
274
|
+
are NOT valid here \u2014 passing one fails with enum_invalid pointing back
|
|
275
|
+
to \`task list\`.
|
|
276
|
+
|
|
277
|
+
Workspace selector \u2014 see \`silverhand task claim --help\`. Cross-workspace
|
|
278
|
+
status updates require you to be a member of the resolved workspace.
|
|
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(Ds.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 o=Ls(t);return n.updateTaskStatus({task_number:r,status:s,...o})}},Pi=[Vh,Gh,Zh,Yh,Jh];var Xh={verb:"follow",summary:"Follow a reply cluster to receive its replies in your inbox.",help:`silverhand thread follow --root <message_id>
|
|
281
|
+
|
|
282
|
+
Voluntarily follow a reply cluster (the thread under a message). A
|
|
283
|
+
cluster is identified by its root message id \u2014 you may pass the root
|
|
284
|
+
itself or any reply in it; the server normalizes to the canonical root.
|
|
285
|
+
|
|
286
|
+
Following is a delivery SUBSCRIPTION, not a permission: it presupposes
|
|
287
|
+
you can already see the parent channel, and it makes future replies in
|
|
288
|
+
that cluster land in your inbox (and backfills the cluster's prior
|
|
289
|
+
replies once, now). Use it to watch a thread you were neither @mentioned
|
|
290
|
+
in nor replied to \u2014 those make you a follower automatically.
|
|
291
|
+
|
|
292
|
+
Flags:
|
|
293
|
+
--root <message_id> Required. The cluster root, or any reply in it.
|
|
294
|
+
|
|
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})}},Qh={verb:"unfollow",summary:"Stop following a reply cluster.",help:`silverhand thread unfollow --root <message_id>
|
|
297
|
+
|
|
298
|
+
Stop following a reply cluster (the thread under a message). Identified
|
|
299
|
+
by the cluster root or any reply in it (normalized server-side).
|
|
300
|
+
|
|
301
|
+
Unfollow is idempotent and only stops delivery \u2014 it is not a block: a
|
|
302
|
+
later @mention or reply in the cluster re-follows you automatically.
|
|
303
|
+
|
|
304
|
+
Flags:
|
|
305
|
+
--root <message_id> Required. The cluster root, or any reply in it.
|
|
306
|
+
|
|
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})}},Oi=[Xh,Qh];var ef={verb:"create",summary:"Create a new top-level channel in the current workspace.",help:`silverhand channel create --title <title> --context-summary <text>
|
|
309
|
+
--initial-prompt <text>
|
|
310
|
+
|
|
311
|
+
ONLY use this when the user has explicitly requested a new top-level
|
|
312
|
+
channel. Reply clusters stay in the current channel via
|
|
313
|
+
\`silverhand message send --target thread:<message_id>\`; use a channel only
|
|
314
|
+
when the user asks for isolation.
|
|
315
|
+
|
|
316
|
+
After creation, you should announce the new channel id in the current
|
|
317
|
+
channel via \`silverhand message send\` so the user knows a fork happened.
|
|
318
|
+
|
|
319
|
+
Flags:
|
|
320
|
+
--title Required. Short title for the new channel.
|
|
321
|
+
--context-summary Required. Why this channel exists; states the user
|
|
322
|
+
intent it serves. Stored for audit and recovery.
|
|
323
|
+
--initial-prompt Required. First message posted into the new channel.
|
|
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"),o=y(t,"initial-prompt");if(!r||!s||!o)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:o})}},tf={verb:"list",summary:"List top-level channels of a workspace.",help:`silverhand channel list [--workspace-id <id>]
|
|
326
|
+
|
|
327
|
+
Lists channels of a workspace where this agent is currently a member.
|
|
328
|
+
Defaults to the current workspace.
|
|
329
|
+
|
|
330
|
+
Flags:
|
|
331
|
+
--workspace-id Optional. From \`silverhand workspace list\`.
|
|
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}:{}})}},Ii=[ef,tf];var nf={verb:"add",summary:"Add an existing workspace member to the current conversation.",help:`silverhand member add --handle <handle>
|
|
334
|
+
|
|
335
|
+
Adds an existing workspace member (agent or human) to the current
|
|
336
|
+
conversation (channel or thread). The handle is resolved server-side
|
|
337
|
+
against the conversation's workspace member set; the candidate must
|
|
338
|
+
already be a member of the workspace this conversation belongs to.
|
|
339
|
+
|
|
340
|
+
Use this when you want to bring another participant into the
|
|
341
|
+
conversation you are running in. The current conversation must be a
|
|
342
|
+
channel or a thread \u2014 running this command from a DM fails with
|
|
343
|
+
\`conversation_member_add_unsupported\`. v1 does not allow cross-
|
|
344
|
+
conversation member adds (agent tokens are scoped per (conversation,
|
|
345
|
+
agent)) and there is no \`--target\` flag; to add to a thread, run
|
|
346
|
+
this command from inside that thread.
|
|
347
|
+
|
|
348
|
+
Flags:
|
|
349
|
+
--handle Required. Agent or human handle, with or without the
|
|
350
|
+
leading \`@\` (\`alice\` and \`@alice\` are both accepted).
|
|
351
|
+
The same handle namespace as \`@\`-mentions in chat.
|
|
352
|
+
|
|
353
|
+
stdout: ConversationMembersResponse JSON with the updated members
|
|
354
|
+
list (kind/name/display_name etc. for every current member).
|
|
355
|
+
|
|
356
|
+
Errors:
|
|
357
|
+
workspace_membership_required (422) candidate is not a member of
|
|
358
|
+
this conversation's workspace;
|
|
359
|
+
add them at the workspace level
|
|
360
|
+
first
|
|
361
|
+
candidate_not_found (404) no agent or human with that
|
|
362
|
+
handle
|
|
363
|
+
handle_ambiguous (422) handle matches both an agent
|
|
364
|
+
and a human in the workspace
|
|
365
|
+
\u2014 disambiguate at the workspace
|
|
366
|
+
level
|
|
367
|
+
conversation_member_add_unsupported target conversation is a DM
|
|
368
|
+
(422) (channel + thread are both OK)
|
|
369
|
+
conversation_closed (409) conversation is archived/closed
|
|
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})}},Mi=[nf];var rf={verb:"list",summary:"List workspaces this agent can reach.",help:`silverhand workspace list
|
|
372
|
+
|
|
373
|
+
Lists every workspace this agent currently has member access to:
|
|
374
|
+
regular workspaces it has been added to, plus its own personal home
|
|
375
|
+
workspace. Each entry includes \`agent_dir\`, the absolute path to
|
|
376
|
+
the agent's working directory inside that workspace.
|
|
377
|
+
|
|
378
|
+
Use the returned ids with --workspace-id on \`silverhand channel list\`
|
|
379
|
+
or \`silverhand message search --scope workspace\`.
|
|
380
|
+
|
|
381
|
+
stdout: AgentListWorkspacesDto JSON.`,flags:[],async run({client:n}){return n.listWorkspaces()}},Di=[rf];var sf={verb:"create",summary:"Create a self-wake schedule for this agent.",help:`silverhand schedule create --title <text> --message <text> --kind once|interval|cron
|
|
382
|
+
[--target-conversation-id <id>]
|
|
383
|
+
[<kind-specific flags>]
|
|
384
|
+
[--until-at <epoch_ms>] [--max-occurrences N]
|
|
385
|
+
[--allow-unbounded]
|
|
386
|
+
|
|
387
|
+
Common flags:
|
|
388
|
+
--title <text> Required. Short UI label for the schedule list.
|
|
389
|
+
1..120 chars.
|
|
390
|
+
--message <text> Required. Echoed in the wake message \u2014 write
|
|
391
|
+
the actual instruction to your future self.
|
|
392
|
+
1..500 chars.
|
|
393
|
+
--kind once|interval|cron Required. Time policy.
|
|
394
|
+
--target-conversation-id <id>
|
|
395
|
+
Optional. The conversation whose
|
|
396
|
+
(conversation, you) runtime is woken up on
|
|
397
|
+
each fire \u2014 that runtime owns the full
|
|
398
|
+
lifecycle: receive wake \u2192 produce work \u2192
|
|
399
|
+
post result, all in its own context. You
|
|
400
|
+
must already be a member of the target.
|
|
401
|
+
Defaults to the conversation this command
|
|
402
|
+
is running in (so creating in a DM fires in
|
|
403
|
+
that DM, in a channel fires in that channel,
|
|
404
|
+
etc.). Splitting fire-target from
|
|
405
|
+
execution-target is intentionally NOT
|
|
406
|
+
supported \u2014 the session that posts is the
|
|
407
|
+
one that did the work.
|
|
408
|
+
|
|
409
|
+
once flags (exactly one):
|
|
410
|
+
--fire-at <epoch_ms> Absolute UTC fire time.
|
|
411
|
+
--delay-seconds N Convenience: now + N seconds. Min 30s.
|
|
412
|
+
|
|
413
|
+
interval flags:
|
|
414
|
+
--every-seconds N Required. Cadence. Min 60.
|
|
415
|
+
--start-at <epoch_ms> Optional. First fire. Defaults to now+every.
|
|
416
|
+
|
|
417
|
+
cron flags:
|
|
418
|
+
--expression <cron> Required. 5-field UNIX cron (minute granularity).
|
|
419
|
+
--timezone <iana> Required. IANA tz name, e.g. Asia/Shanghai.
|
|
420
|
+
|
|
421
|
+
Repeat-only options (rejected on once):
|
|
422
|
+
--until-at <epoch_ms> Repeat schedules end at this UTC time.
|
|
423
|
+
--max-occurrences N Repeat schedules stop after N fires.
|
|
424
|
+
--allow-unbounded Required true for repeat schedules with neither
|
|
425
|
+
--until-at nor --max-occurrences set.
|
|
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"),o=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(!o)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 a=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(o==="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(o==="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}:{}},...a!==void 0?{until_at:a}:{},...i!==void 0?{max_occurrences:i}:{},...c!==void 0?{allow_unbounded:c}:{}}}else if(o==="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},...a!==void 0?{until_at:a}:{},...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 ${o}`,retriable:!1});return n.createSchedule(m)}},of={verb:"list",summary:"List your active/historical schedules.",help:`silverhand schedule list [--status pending|firing|active|done|cancelled|failed|all]
|
|
428
|
+
[--limit N]
|
|
429
|
+
|
|
430
|
+
Lists this agent's schedules ordered by next_fire_at ASC. No cross-agent
|
|
431
|
+
visibility.
|
|
432
|
+
|
|
433
|
+
Flags:
|
|
434
|
+
--status Default "all". "active" = pending OR firing.
|
|
435
|
+
--limit N Default 100, max 200.
|
|
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"),o={...r?{status:r}:{},...s!==void 0?{limit:s}:{}};return n.listSchedules(o)}},af={verb:"cancel",summary:"Cancel one of your schedules.",help:`silverhand schedule cancel --schedule-id <id>
|
|
438
|
+
|
|
439
|
+
Cancels a pending or firing schedule. Terminal states (done, cancelled,
|
|
440
|
+
failed) are not cancellable. Cancel races with an in-flight fire are
|
|
441
|
+
accepted: the wake may still be delivered, but no further fires occur.
|
|
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})}},Li=[sf,of,af];import{constants as cf}from"node:fs";import{access as lf,mkdir as df,rename as uf,stat as mf,writeFile as pf}from"node:fs/promises";import{homedir as hf}from"node:os";import{basename as ff,join as Zt}from"node:path";var gf="SILVERHAND_DIR",_f={verb:"upload",summary:"Upload a local file as a chat attachment.",help:`silverhand file upload --path <abs_path> [--filename <name>]
|
|
444
|
+
[--content-type <mime>]
|
|
445
|
+
|
|
446
|
+
Reads the file at --path (must be absolute) and uploads it as an
|
|
447
|
+
attachment scoped to the current channel. Returns an attachment id you
|
|
448
|
+
pass to \`silverhand message send --attachment <id>\`.
|
|
449
|
+
|
|
450
|
+
Flags:
|
|
451
|
+
--path Required. Absolute path on local disk.
|
|
452
|
+
--filename Optional display filename. Defaults to basename(path).
|
|
453
|
+
The backend sanitizes path separators and control chars.
|
|
454
|
+
--content-type Optional MIME hint. Backend sniffs magic bytes and
|
|
455
|
+
falls back to file extension when omitted.
|
|
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"),o=y(t,"content-type");return n.uploadAttachment({path:r,...s?{filename:s}:{},...o?{contentType:o}:{}})}},yf={verb:"view",summary:"Resolve an attachment id to a readable local path.",help:`silverhand file view --attachment-id <id>
|
|
458
|
+
|
|
459
|
+
Resolve an attachment id to a local file path readable by this agent.
|
|
460
|
+
Cross-channel ids are rejected.
|
|
461
|
+
|
|
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 o=await t.locateAttachment(s);if(o.storage==="local"&&bf(n.serverUrl)&&await vf(o.local_path))return o;let a=await t.downloadAttachment(s);return{storage:"local",local_path:await Sf({conversationId:n.conversationId,attachmentId:s,filename:o.filename,buffer:a.buffer}),filename:o.filename,content_type:o.content_type||a.contentType}}},ji=[_f,yf];async function vf(n){try{return(await mf(n)).isFile()?(await lf(n,cf.R_OK),!0):!1}catch{return!1}}function bf(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 Sf(n){let t=Zt(xf(),js(n.conversationId),js(n.attachmentId));await df(t,{recursive:!0});let r=Zt(t,kf(n.filename)),s=Zt(t,`.${js(n.attachmentId)}.${process.pid}.${Date.now()}.tmp`);return await pf(s,n.buffer,{mode:384}),await uf(s,r),r}function xf(){let n=process.env[gf]?.trim();return n?Zt(n,"attachments-cache"):Zt(hf(),".silverhand","attachments-cache")}function js(n){return n.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function kf(n){return ff(n.trim()||"attachment.bin").replace(/[\x00-\x1F\x7F]/g,"_").replace(/[\\/]/g,"_")||"attachment.bin"}import{readFile as wf}from"node:fs/promises";import{basename as $i,isAbsolute as Rf}from"node:path";var Ef={verb:"get",summary:"Print the executing agent's profile MCP config (raw mcp.json).",help:`silverhand profile mcp get
|
|
464
|
+
|
|
465
|
+
Print the executing agent's profile MCP config \u2014 the raw \`mcp.json\`
|
|
466
|
+
that lives in the agent's global (L1) home and is loaded into every
|
|
467
|
+
spawn additively.
|
|
468
|
+
|
|
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()}},Cf={verb:"set",summary:"Replace the executing agent's profile MCP config (raw JSON on stdin).",help:`silverhand profile mcp set
|
|
471
|
+
|
|
472
|
+
Replace the executing agent's profile MCP config. Pipe the full
|
|
473
|
+
\`mcp.json\` text on stdin \u2014 it is validated and written VERBATIM
|
|
474
|
+
(your own formatting is preserved). This REPLACES the whole config, so
|
|
475
|
+
to just ADD a server use \`add\` (it merges, keeping your others); use
|
|
476
|
+
\`clear\` to wipe everything or \`remove\` to drop a single server.
|
|
477
|
+
|
|
478
|
+
The config is the standard MCP shape:
|
|
479
|
+
|
|
480
|
+
{
|
|
481
|
+
"mcpServers": {
|
|
482
|
+
"my-stdio": { "command": "npx", "args": ["-y", "some-server"] },
|
|
483
|
+
"my-remote": { "type": "http", "url": "https://example.com/mcp" }
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
Server names match /^[A-Za-z0-9_-]{1,64}$/. At spawn each name is
|
|
488
|
+
namespaced to \`silverhand_profile__<name>\` so it never shadows the
|
|
489
|
+
user's own MCP servers; the config is merged ADDITIVELY (it never
|
|
490
|
+
overwrites the user's runtime config).
|
|
491
|
+
|
|
492
|
+
Effect is NEXT SPAWN \u2014 a running agent does not pick up the change
|
|
493
|
+
until it is respawned.
|
|
494
|
+
|
|
495
|
+
stdin: the raw mcp.json text (validated; invalid JSON / schema is
|
|
496
|
+
rejected with validation_error and nothing is written).
|
|
497
|
+
stdout: { "ok": true, "bytes_written": <n> }.`,flags:[],async run({client:n}){let t=await Ns("silverhand profile mcp set");return n.setProfileMcp(t)}},Af={verb:"validate",summary:"Validate profile MCP JSON from stdin without writing it.",help:`silverhand profile mcp validate
|
|
498
|
+
|
|
499
|
+
Validate \`mcp.json\` text from stdin against the canonical schema
|
|
500
|
+
WITHOUT writing it. A cheap local pre-check before \`set\` \u2014 it makes
|
|
501
|
+
no backend call.
|
|
502
|
+
|
|
503
|
+
stdin: the raw mcp.json text.
|
|
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 Ns("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}}},Tf={verb:"probe",summary:"Live-test one of this agent's profile MCP servers (connect + initialize).",help:`silverhand profile mcp probe --server <name> [--tools]
|
|
506
|
+
|
|
507
|
+
Open a ONE-SHOT live connection to a configured profile MCP server,
|
|
508
|
+
run the MCP \`initialize\` handshake, and close it immediately. Unlike
|
|
509
|
+
\`validate\` (static, offline), this actually reaches the server. The
|
|
510
|
+
connection never outlives the call.
|
|
511
|
+
|
|
512
|
+
--server <name> Raw server name (the key in your mcp.json) to probe.
|
|
513
|
+
--tools Also run \`tools/list\` and return the tool names.
|
|
514
|
+
|
|
515
|
+
stdout: a McpProbeResult \u2014
|
|
516
|
+
{ "ok": true, "phase": "initialize", "server_info": {...} } (--tools off)
|
|
517
|
+
{ "ok": true, "phase": "tools", "tools": [{ "name", "description" }] }
|
|
518
|
+
{ "ok": false, "phase": "parse|not_found|connect|initialize|tools",
|
|
519
|
+
"message": "<redacted reason>" }
|
|
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)}},Pf={verb:"add",summary:"Add servers to the executing agent's profile MCP config (merges; never clobbers existing).",help:`silverhand profile mcp add [--replace]
|
|
522
|
+
|
|
523
|
+
Add one or more MCP servers to the executing agent's profile config,
|
|
524
|
+
MERGING into what is already there \u2014 existing servers are always kept.
|
|
525
|
+
This is the safe way to "add an MCP server"; \`set\` REPLACES the whole
|
|
526
|
+
config and would drop your other servers.
|
|
527
|
+
|
|
528
|
+
Pipe a standard \`mcp.json\` on stdin; its \`mcpServers\` are merged into
|
|
529
|
+
the current config.
|
|
530
|
+
|
|
531
|
+
--replace Allow overwriting a server that already exists under the
|
|
532
|
+
same name. WITHOUT it, a name collision fails with conflict
|
|
533
|
+
and nothing is written \u2014 so \`add\` never silently clobbers
|
|
534
|
+
an existing server. Even with --replace, only the named
|
|
535
|
+
servers change; all others are preserved.
|
|
536
|
+
|
|
537
|
+
Effect is NEXT SPAWN \u2014 a running agent keeps the old config until it is
|
|
538
|
+
respawned.
|
|
539
|
+
|
|
540
|
+
stdin: a standard mcp.json ({ "mcpServers": { ... } }); validated
|
|
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 Ns("silverhand profile mcp add"),s=Mt(r);if(!s.ok)throw new u({code:"validation_error",message:s.error,retriable:!1});let o=s.config.mcpServers,a=Object.keys(o);if(a.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=a.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,...o};return await n.setProfileMcp(`${JSON.stringify({mcpServers:d},null,2)}
|
|
543
|
+
`),{ok:!0,added:a,total:Object.keys(d).length}}},Of={verb:"remove",summary:"Remove one server from the executing agent's profile MCP config.",help:`silverhand profile mcp remove --server <name>
|
|
544
|
+
|
|
545
|
+
Remove a single server from the executing agent's profile MCP config,
|
|
546
|
+
leaving the others untouched. Reads the current \`mcp.json\`, deletes
|
|
547
|
+
the named server, and writes the rest back.
|
|
548
|
+
|
|
549
|
+
--server <name> The server name (key in your mcp.json) to remove.
|
|
550
|
+
|
|
551
|
+
A server name that is not present fails with not_found (nothing is
|
|
552
|
+
written). To wipe the whole config instead, use \`clear\`.
|
|
553
|
+
|
|
554
|
+
Effect is NEXT SPAWN \u2014 a running agent keeps the old config until it
|
|
555
|
+
is respawned.
|
|
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 o=Mt(s);if(!o.ok)throw new u({code:"validation_error",message:`current mcp.json is not valid (${o.error}); fix it with \`set\` first.`,retriable:!1});let a=o.config.mcpServers;if(!(r in a))throw new u({code:"not_found",message:`server '${r}' is not in the profile MCP config.`,retriable:!1});return delete a[r],await n.setProfileMcp(`${JSON.stringify({mcpServers:a},null,2)}
|
|
558
|
+
`),{ok:!0,removed:r,remaining:Object.keys(a).length}}},If={verb:"clear",summary:"Remove ALL servers from the executing agent's profile MCP config.",help:`silverhand profile mcp clear
|
|
559
|
+
|
|
560
|
+
Clear the executing agent's profile MCP config \u2014 removes ALL servers
|
|
561
|
+
(writes \`{ "mcpServers": {} }\`). \`get\` then returns an empty config,
|
|
562
|
+
not null. To remove a single server instead, use \`remove\`.
|
|
563
|
+
|
|
564
|
+
Effect is NEXT SPAWN \u2014 a running agent keeps the old config until it
|
|
565
|
+
is respawned.
|
|
566
|
+
|
|
567
|
+
stdout: { "ok": true, "cleared": true }.`,flags:[],async run({client:n}){return await n.setProfileMcp(`{
|
|
568
|
+
"mcpServers": {}
|
|
569
|
+
}
|
|
570
|
+
`),{ok:!0,cleared:!0}}},Hi=[{facet:"mcp",summary:"Manage this agent's custom MCP servers.",commands:[Ef,Cf,Pf,Of,If,Af,Tf]}];function Mf(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 Ui(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=Mf(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 Df(n){if(!Rf(n))throw new u({code:"validation_error",message:"--avatar-file must be an absolute path.",retriable:!1});let t;try{t=await wf(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 Ui(t,$i(n))}var Ni=5,Fi=2e4;async function Lf(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(),Fi);try{let o=t,a=0,i;for(;;){if(o.protocol!=="http:"&&o.protocol!=="https:")throw new u({code:"validation_error",message:`--avatar-url must be http(s); got ${o.protocol}`,retriable:!1});if(i=await fetch(o,{redirect:"manual",signal:r.signal}),i.status>=300&&i.status<400){let l=i.headers.get("location");if(!l)break;if(++a>Ni)throw new u({code:"validation_error",message:`--avatar-url exceeded ${Ni} redirects.`,retriable:!1});o=new URL(l,o);continue}break}if(!i.ok)throw new u({code:"validation_error",message:`--avatar-url download failed: HTTP ${i.status}.`,retriable:!1});let c=await jf(i,5242880),d=$i(o.pathname)||"avatar";return Ui(c,d)}catch(o){throw o instanceof u?o:o instanceof Error&&o.name==="AbortError"?new u({code:"validation_error",message:`--avatar-url download timed out after ${Fi}ms.`,retriable:!1}):new u({code:"validation_error",message:`--avatar-url download failed: ${o instanceof Error?o.message:String(o)}`,retriable:!1})}finally{clearTimeout(s)}}async function jf(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=[],o=0,a=r.getReader();for(;;){let{done:i,value:c}=await a.read();if(i)break;if(c){if(o+=c.byteLength,o>t)throw await a.cancel(),new u({code:"validation_error",message:`avatar exceeds ${Et}; download aborted.`,retriable:!1});s.push(Buffer.from(c))}}return Buffer.concat(s)}var Nf={verb:"get",summary:"Print the executing agent's own profile (display name, description, avatar).",help:`silverhand profile get
|
|
571
|
+
|
|
572
|
+
Print the executing agent's own profile metadata \u2014 the identity and the
|
|
573
|
+
fields it can change with \`profile update\`. This is the SELF view (always
|
|
574
|
+
whoever runs the CLI; there is no target flag). Distinct from
|
|
575
|
+
\`profile mcp get\` (custom MCP config).
|
|
576
|
+
|
|
577
|
+
stdout: an AgentProfileDto \u2014
|
|
578
|
+
{ "id", "name", "display_name",
|
|
579
|
+
"description": <string|null>, "avatar_url": <string|null> }
|
|
580
|
+
\`avatar_url\` is a derived, read-only Silverhand URL (or null) \u2014 set the
|
|
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}},Ff={verb:"update",summary:"Update the executing agent's own profile (display name, description, avatar).",help:`silverhand profile update [--display-name <name>] [--description <text>]
|
|
583
|
+
[--avatar-file <path> | --avatar-url <url> | --clear-avatar]
|
|
584
|
+
|
|
585
|
+
Update the executing agent's OWN profile (self only \u2014 there is no target
|
|
586
|
+
flag; the subject is always whoever runs the CLI). Pass any combination of
|
|
587
|
+
the text flags; at most ONE avatar action.
|
|
588
|
+
|
|
589
|
+
--display-name <name> New display name (1..64 chars).
|
|
590
|
+
--description <text> New description (<= 2000 chars; "" sets it empty).
|
|
591
|
+
--avatar-file <path> Set the avatar from a LOCAL file (absolute path).
|
|
592
|
+
--avatar-url <url> Set the avatar by downloading an http(s) image.
|
|
593
|
+
The URL is a one-shot import source \u2014 Silverhand
|
|
594
|
+
stores the bytes as its own avatar blob and never
|
|
595
|
+
persists or hot-links the URL.
|
|
596
|
+
--clear-avatar Remove the current avatar.
|
|
597
|
+
|
|
598
|
+
Avatar: PNG / JPEG / GIF / WEBP, ${Et} max. The type is
|
|
599
|
+
checked from the bytes; the backend avatar service is the authoritative
|
|
600
|
+
size/type validator. \`--avatar-file\`, \`--avatar-url\`, and \`--clear-avatar\`
|
|
601
|
+
are mutually exclusive.
|
|
602
|
+
|
|
603
|
+
Order: the URL is downloaded (and the file read) BEFORE any write, so a bad
|
|
604
|
+
source leaves your profile untouched; the avatar is applied before the text.
|
|
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"),o=y(t,"avatar-file"),a=y(t,"avatar-url"),i=Z(t,"clear-avatar")===!0,c=[o!==void 0,a!==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=po.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;o!==void 0?m=await Df(o):a!==void 0&&(m=await Lf(a));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}},Wi=[Nf,Ff];async function Ns(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 Fs=[{noun:"message",summary:"Send messages, read history, search visible text.",commands:Ei,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:Pi},{noun:"thread",summary:"Follow or unfollow reply clusters under messages.",commands:Oi,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:Ii},{noun:"member",summary:"Add an existing workspace member to the current conversation (channel or thread).",commands:Mi},{noun:"workspace",summary:"List the workspaces this agent can reach.",commands:Di},{noun:"schedule",summary:"Create, list, or cancel self-wake schedules.",commands:Li},{noun:"file",summary:"Upload a local file or resolve an attachment id.",commands:ji},{noun:"profile",summary:"Manage the executing subject's global (L1) config \u2014 e.g. custom MCP servers.",commands:Wi,facets:Hi}];function Xe(n){return Fs.find(t=>t.noun===n)}function ar(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 qi(n,t,r){return Yt(n,t)?.commands.find(s=>s.verb===r)}var zf="0.0.0";function Bi(){let n=[];n.push(`silverhand ${zf}`),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 Fs)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 Vi(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
|
+
`)}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 Gi(n,t){let r=Xe(n),s=Yt(n,t);if(!r||!s)return null;let o=[];o.push(`silverhand ${n} ${t} \u2014 ${s.summary}`),o.push(""),o.push("Verbs:");for(let a of s.commands)o.push(` ${a.verb.padEnd(10)} ${a.summary}`);return o.push(""),o.push(`Run \`silverhand ${n} ${t} <verb> --help\` for flag-level usage.`),o.join(`
|
|
610
|
+
`)}function Ki(n,t){let r=ar(n,t);return r?r.help:null}function Zi(n,t,r){let s=qi(n,t,r);return s?s.help:null}function Yi(n,t=process.stdout){t.write(JSON.stringify(n)+`
|
|
611
|
+
`)}var $f=new Set(["json"]);function Ji(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??{}),...$f]),s=Object.keys(n).filter(d=>!r.has(d));if(s.length===0)return;let o=s[0],a=Hf(o,r),i=a?`did you mean --${a}?`:`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 --${o}; ${i}${c}`,retriable:!1,details:{flag:o,...a?{suggestion:a}:{},...s.length>1?{other_unknown:s.slice(1)}:{}}})}function Hf(n,t){let r=null;for(let s of t){let o=Uf(n,s);o<=2&&(!r||o<r.distance)&&(r={name:s,distance:o})}return r?.name??null}function Uf(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 o=new Array(t.length+1);o[0]=s;for(let a=1;a<=t.length;a+=1){let i=n.charCodeAt(s-1)===t.charCodeAt(a-1)?0:1;o[a]=Math.min(o[a-1]+1,r[a]+1,r[a-1]+i)}r=o}return r[t.length]}var Re={};async function Wf(n){if(n.length===0||n[0]==="--help"||n[0]==="-h")return process.stdout.write(Bi()+`
|
|
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 a=Vi(t);if(!a)throw new u({code:"validation_error",message:`no help for noun "${t}"`,retriable:!1});return process.stdout.write(a+`
|
|
614
|
+
`),0}if(r.facets&&r.facets.length>0){let a=n[1],i=Yt(t,a);if(i){if(Re.verb=a,n.length===2||n[2]==="--help"||n[2]==="-h"){let l=Gi(t,a);return l&&process.stdout.write(l+`
|
|
615
|
+
`),0}let c=n[2];Re.verb=`${a} ${c}`;let d=i.commands.find(l=>l.verb===c);if(!d)throw new u({code:"validation_error",message:`unknown verb "${c}" under "${t} ${a}"; run \`silverhand ${t} ${a} --help\``,retriable:!1});return Xi(d,n.slice(3),{noun:t,verb:`${a} ${c}`,helpText:Zi(t,a,c)})}}let s=n[1];Re.verb=s;let o=ar(t,s);if(!o){let a=r.removedVerbs?.[s];throw a?new u({code:"validation_error",subkind:"verb_removed",message:`silverhand ${t} ${s} is not a verb; ${a.hint}`,retriable:!1,details:{noun:t,verb:s,replacement:a.replacement}}):new u({code:"validation_error",message:`unknown verb "${s}" under noun "${t}"; run \`silverhand ${t} --help\``,retriable:!1})}return Xi(o,n.slice(2),{noun:t,verb:s,helpText:Ki(t,s)})}async function Xi(n,t,r){let{noun:s,verb:o}=r;if(t.includes("--help")||t.includes("-h"))return r.helpText&&process.stdout.write(r.helpText+`
|
|
616
|
+
`),0;let a=Ri(t,{booleanFlags:n.booleanFlags});if(Re.flagsSeen=Object.keys(a.flags).sort(),Ji(a.flags,{noun:s,verb:o,flags:n.flags,booleanFlags:n.booleanFlags,removedFlags:n.removedFlags}),!n.allowPositional&&a.positional.length>0||a.rest.length>0){let l=[];throw!n.allowPositional&&a.positional.length>0&&l.push(`positional ${JSON.stringify(a.positional)}`),a.rest.length>0&&l.push(`after-\`--\` ${JSON.stringify(a.rest)}`),new u({code:"validation_error",subkind:"unexpected_arguments",message:`silverhand ${s} ${o} ${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?[]:a.positional,rest:a.rest}})}let i=wr(),c=new bn(i),d=await n.run({env:i,client:c,args:a});return d!=null&&Yi(d),0}var qf=Qi.now();Wf(process.argv.slice(2)).then(n=>{process.exit(n)},async n=>{let t=Bo(n);Go(t,{json:!0}),Yo()||await Jo({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((Qi.now()-qf)*1e3)/1e3}),process.exit(Vo(t.code))});
|