@ours.network/mcp 0.1.3 → 0.3.0
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
CHANGED
|
@@ -1,91 +1,92 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`,{mode:384})
|
|
5
|
-
`),n}import Ba from"node:process";var xr=Object.freeze({status:"aborted"});function u(e,t,r){function o(c,l){var p;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(p=c._zod).traits??(p.traits=new Set),c._zod.traits.add(e),t(c,l);for(let f in s.prototype)f in c||Object.defineProperty(c,f,{value:s.prototype[f].bind(c)});c._zod.constr=s,c._zod.def=l}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(c){var l;let p=r?.Parent?new i:this;o(p,c),(l=p._zod).deferred??(l.deferred=[]);for(let f of p._zod.deferred)f();return p}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Lc=Symbol("zod_brand"),ye=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Lt={};function ce(e){return e&&Object.assign(Lt,e),Lt}var O={};gr(O,{BIGINT_FORMAT_RANGES:()=>Ho,Class:()=>yr,NUMBER_FORMAT_RANGES:()=>Zr,aborted:()=>Ze,allowsEval:()=>kr,assert:()=>Bc,assertEqual:()=>Dc,assertIs:()=>Fc,assertNever:()=>qc,assertNotEqual:()=>Mc,assignProp:()=>$r,cached:()=>it,captureStackTrace:()=>Mt,cleanEnum:()=>ou,cleanRegex:()=>at,clone:()=>ge,createTransparentProxy:()=>Kc,defineLazy:()=>N,esc:()=>Pe,escapeRegex:()=>$e,extend:()=>Qc,finalizeIssue:()=>_e,floatSafeRemainder:()=>Sr,getElementAtPath:()=>Vc,getEnumValues:()=>wr,getLengthableOrigin:()=>ct,getParsedType:()=>Hc,getSizableOrigin:()=>Ko,isObject:()=>Me,isPlainObject:()=>Fe,issue:()=>Ir,joinValues:()=>Dt,jsonStringifyReplacer:()=>br,merge:()=>eu,normalizeParams:()=>b,nullish:()=>st,numKeys:()=>Gc,omit:()=>Xc,optionalKeys:()=>Pr,partial:()=>tu,pick:()=>Yc,prefixIssues:()=>xe,primitiveTypes:()=>Go,promiseAllObject:()=>Wc,propertyKeyTypes:()=>Rr,randomString:()=>Jc,required:()=>ru,stringifyPrimitive:()=>Ft,unwrapMessage:()=>nt});function Dc(e){return e}function Mc(e){return e}function Fc(e){}function qc(e){throw new Error}function Bc(e){}function wr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Dt(e,t="|"){return e.map(r=>Ft(r)).join(t)}function br(e,t){return typeof t=="bigint"?t.toString():t}function it(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function st(e){return e==null}function at(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Sr(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}function N(e,t,r){Object.defineProperty(e,t,{get(){{let n=r();return e[t]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function $r(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Vc(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function Wc(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function Jc(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Pe(e){return JSON.stringify(e)}var Mt=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var kr=it(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Fe(e){if(Me(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Me(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Gc(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Hc=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Rr=new Set(["string","number","symbol"]),Go=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function b(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Kc(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Ft(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Pr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ho={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Yc(e,t){let r={},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(r[n]=o.shape[n])}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Xc(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete r[n]}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Qc(e,t){if(!Fe(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let o={...e._zod.def.shape,...t};return $r(this,"shape",o),o},checks:[]};return ge(e,r)}function eu(e,t){return ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return $r(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function tu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=e?new e({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=e?new e({type:"optional",innerType:o[i]}):o[i];return ge(t,{...t._zod.def,shape:n,checks:[]})}function ru(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new e({type:"nonoptional",innerType:o[i]});return ge(t,{...t._zod.def,shape:n,checks:[]})}function Ze(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function xe(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function nt(e){return typeof e=="string"?e:e?.message}function _e(e,t,r){let o={...e,path:e.path??[]};if(!e.message){let n=nt(e.inst?._zod.def?.error?.(e))??nt(t?.error?.(e))??nt(r.customError?.(e))??nt(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Ko(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ct(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ir(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function ou(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var yr=class{constructor(...t){}};var Yo=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,br,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qt=u("$ZodError",Yo),Tr=u("$ZodError",Yo,{Parent:Error});function Or(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Cr(e,t){let r=t||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>n({issues:c}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(r(s));else{let c=o,l=0;for(;l<s.path.length;){let p=s.path[l];l===s.path.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(r(s))):c[p]=c[p]||{_errors:[]},c=c[p],l++}}};return n(e),o}var Xo=e=>(t,r,o,n)=>{let i=o?Object.assign(o,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ye;if(s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Mt(c,n?.callee),c}return s.value};var Qo=e=>async(t,r,o,n)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Mt(c,n?.callee),c}return s.value};var Er=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ye;return i.issues.length?{success:!1,error:new(e??qt)(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},en=Er(Tr),Ar=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},tn=Ar(Tr);var rn=/^[cC][^\s-]{8,}$/,on=/^[0-9a-z]+$/,nn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,sn=/^[0-9a-vA-V]{20}$/,an=/^[A-Za-z0-9]{27}$/,cn=/^[a-zA-Z0-9_-]{21}$/,un=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ln=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ur=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var pn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var iu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function dn(){return new RegExp(iu,"u")}var mn=/^(?:(?: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])$/,fn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,hn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,gn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_n=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nr=/^[A-Za-z0-9_-]*$/,zn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var xn=/^\+(?:[0-9]){6,14}[0-9]$/,vn="(?:(?:\\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])))",yn=new RegExp(`^${vn}$`);function wn(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function bn(e){return new RegExp(`^${wn(e)}$`)}function Sn(e){let t=wn({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${vn}T(?:${o})$`)}var $n=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kn=/^\d+n?$/,Rn=/^\d+$/,Pn=/^-?\d+(?:\.\d+)?/i,Zn=/true|false/i,In=/null/i;var Tn=/^[^A-Z]*$/,On=/^[^a-z]*$/;var ie=u("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Cn={number:"number",bigint:"bigint",object:"date"},jr=u("$ZodCheckLessThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lr=u("$ZodCheckGreaterThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),En=u("$ZodCheckMultipleOf",(e,t)=>{ie.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Sr(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),An=u("$ZodCheckNumberFormat",(e,t)=>{ie.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Zr[t.format];e._zod.onattach.push(s=>{let c=s._zod.bag;c.format=t.format,c.minimum=n,c.maximum=i,r&&(c.pattern=Rn)}),e._zod.check=s=>{let c=s.value;if(r){if(!Number.isInteger(c)){s.issues.push({expected:o,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort});return}}c<n&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}});var Un=u("$ZodCheckMaxLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=ct(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Nn=u("$ZodCheckMinLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=ct(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),jn=u("$ZodCheckLengthEquals",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let s=ct(n),c=i>t.length;o.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ut=u("$ZodCheckStringFormat",(e,t)=>{var r,o;ie.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Ln=u("$ZodCheckRegex",(e,t)=>{ut.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dn=u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tn),ut.init(e,t)}),Mn=u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=On),ut.init(e,t)}),Fn=u("$ZodCheckIncludes",(e,t)=>{ie.init(e,t);let r=$e(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qn=u("$ZodCheckStartsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`^${$e(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Bn=u("$ZodCheckEndsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`.*${$e(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Vn=u("$ZodCheckOverwrite",(e,t)=>{ie.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Vt=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
3
|
+
var Vc=Object.defineProperty;var zr=(e,t)=>{for(var r in t)Vc(e,r,{get:t[r],enumerable:!0})};import{spawn as Zc,spawnSync as fr}from"node:child_process";import{connect as Yd}from"node:net";import{homedir as Oc,userInfo as kc}from"node:os";import{resolve as Ec,join as $e,dirname as Vo}from"node:path";import{fileURLToPath as Xd,pathToFileURL as Qd}from"node:url";import{createInterface as dr}from"node:readline/promises";import*as R from"node:fs";import*as ie from"node:fs";import{randomBytes as qc}from"node:crypto";import{homedir as Yo}from"node:os";import{resolve as jt,join as yr,dirname as vr,basename as Bc}from"node:path";var st=["owner","shared","open"],Fe={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:jt(Yo(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function Lt(){return process.env.OURS_CONFIG??yr(Yo(),".ours","config.json")}function Wc(){let e;try{e=ie.readFileSync(Lt(),"utf8")}catch{return{}}let t;try{t=JSON.parse(e)}catch{return{}}let r={};return typeof t.brokerUrl=="string"&&(r.brokerUrl=t.brokerUrl),typeof t.port=="number"&&Number.isFinite(t.port)&&(r.port=t.port),typeof t.stateDir=="string"&&(r.stateDir=jt(t.stateDir)),typeof t.gcIntervalMs=="number"&&Number.isFinite(t.gcIntervalMs)&&(r.gcIntervalMs=t.gcIntervalMs),typeof t.autoStart=="boolean"&&(r.autoStart=t.autoStart),typeof t.apiVisibility=="string"&&st.includes(t.apiVisibility)&&(r.apiVisibility=t.apiVisibility),typeof t.apiToken=="string"&&t.apiToken.trim()&&(r.apiToken=t.apiToken.trim()),r}function Jc(){let e=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return e&&st.includes(e)?e:void 0}function Hc(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function Ko(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function br(){let e=Wc();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??Fe.brokerUrl,port:Ko("OURS_PORT")??e.port??Fe.port,stateDir:jt(process.env.OURS_STATE_DIR??e.stateDir??Fe.stateDir),gcIntervalMs:Ko("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??Fe.gcIntervalMs,autoStart:Hc("OURS_AUTOSTART")??e.autoStart??Fe.autoStart,apiVisibility:Jc()??e.apiVisibility??Fe.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||e.apiToken}}var Gc="daemon-token";function Kc(e){return yr(e.stateDir,Gc)}function Xo(e,t={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let o=e.apiToken?.trim();if(o)return{token:o,source:"config"};let n=Kc(e);try{let s=ie.readFileSync(n,"utf8").trim();if(s)return{token:s,source:"file"}}catch{}if(!t.generate)return null;let i=qc(32).toString("hex");try{ie.mkdirSync(vr(n),{recursive:!0}),ie.writeFileSync(n,i+`
|
|
4
|
+
`,{mode:384}),ie.chmodSync(n,384)}catch{}return{token:i,source:"generated"}}function Qo(e){let t=Lt();ie.mkdirSync(vr(t),{recursive:!0}),ie.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384});try{ie.chmodSync(t,384)}catch{}return t}var Nt=".ours-identity";function Dt(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function wr(e){let t=jt(e);return Bc(t)===Nt?t:yr(t,Nt)}function en(e,t,r=!1){let o=Dt(t),n=wr(e);if(!r&&ie.existsSync(n))throw new Error(`${n} already exists \u2014 pass overwrite to replace it`);return ie.mkdirSync(vr(n),{recursive:!0}),ie.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
6
|
+
`),n}import Ya from"node:process";var Sr=Object.freeze({status:"aborted"});function u(e,t,r){function o(c,l){var p;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(p=c._zod).traits??(p.traits=new Set),c._zod.traits.add(e),t(c,l);for(let h in s.prototype)h in c||Object.defineProperty(c,h,{value:s.prototype[h].bind(c)});c._zod.constr=s,c._zod.def=l}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(c){var l;let p=r?.Parent?new i:this;o(p,c),(l=p._zod).deferred??(l.deferred=[]);for(let h of p._zod.deferred)h();return p}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Yc=Symbol("zod_brand"),ve=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Mt={};function le(e){return e&&Object.assign(Mt,e),Mt}var Z={};zr(Z,{BIGINT_FORMAT_RANGES:()=>rn,Class:()=>kr,NUMBER_FORMAT_RANGES:()=>Cr,aborted:()=>Ze,allowsEval:()=>Zr,assert:()=>ru,assertEqual:()=>Xc,assertIs:()=>eu,assertNever:()=>tu,assertNotEqual:()=>Qc,assignProp:()=>Tr,cached:()=>ct,captureStackTrace:()=>Vt,cleanEnum:()=>hu,cleanRegex:()=>lt,clone:()=>ge,createTransparentProxy:()=>cu,defineLazy:()=>N,esc:()=>Te,escapeRegex:()=>ke,extend:()=>pu,finalizeIssue:()=>_e,floatSafeRemainder:()=>Ir,getElementAtPath:()=>ou,getEnumValues:()=>Rr,getLengthableOrigin:()=>pt,getParsedType:()=>au,getSizableOrigin:()=>on,isObject:()=>Ve,isPlainObject:()=>qe,issue:()=>Ar,joinValues:()=>Ft,jsonStringifyReplacer:()=>Pr,merge:()=>du,normalizeParams:()=>w,nullish:()=>ut,numKeys:()=>su,omit:()=>lu,optionalKeys:()=>Er,partial:()=>mu,pick:()=>uu,prefixIssues:()=>ze,primitiveTypes:()=>tn,promiseAllObject:()=>nu,propertyKeyTypes:()=>Or,randomString:()=>iu,required:()=>fu,stringifyPrimitive:()=>qt,unwrapMessage:()=>at});function Xc(e){return e}function Qc(e){return e}function eu(e){}function tu(e){throw new Error}function ru(e){}function Rr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Ft(e,t="|"){return e.map(r=>qt(r)).join(t)}function Pr(e,t){return typeof t=="bigint"?t.toString():t}function ct(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ut(e){return e==null}function lt(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ir(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}function N(e,t,r){Object.defineProperty(e,t,{get(){{let n=r();return e[t]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Tr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ou(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function nu(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function iu(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Te(e){return JSON.stringify(e)}var Vt=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Zr=ct(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function qe(e){if(Ve(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Ve(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function su(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var au=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Or=new Set(["string","number","symbol"]),tn=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function w(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cu(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function qt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Er(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Cr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function uu(e,t){let r={},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(r[n]=o.shape[n])}return ge(e,{...e._zod.def,shape:r,checks:[]})}function lu(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete r[n]}return ge(e,{...e._zod.def,shape:r,checks:[]})}function pu(e,t){if(!qe(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let o={...e._zod.def.shape,...t};return Tr(this,"shape",o),o},checks:[]};return ge(e,r)}function du(e,t){return ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Tr(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function mu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=e?new e({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=e?new e({type:"optional",innerType:o[i]}):o[i];return ge(t,{...t._zod.def,shape:n,checks:[]})}function fu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new e({type:"nonoptional",innerType:o[i]});return ge(t,{...t._zod.def,shape:n,checks:[]})}function Ze(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ze(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function at(e){return typeof e=="string"?e:e?.message}function _e(e,t,r){let o={...e,path:e.path??[]};if(!e.message){let n=at(e.inst?._zod.def?.error?.(e))??at(t?.error?.(e))??at(r.customError?.(e))??at(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function on(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function pt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function hu(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var kr=class{constructor(...t){}};var nn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Pr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Bt=u("$ZodError",nn),Ur=u("$ZodError",nn,{Parent:Error});function Nr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function jr(e,t){let r=t||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>n({issues:c}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(r(s));else{let c=o,l=0;for(;l<s.path.length;){let p=s.path[l];l===s.path.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(r(s))):c[p]=c[p]||{_errors:[]},c=c[p],l++}}};return n(e),o}var sn=e=>(t,r,o,n)=>{let i=o?Object.assign(o,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ve;if(s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,le())));throw Vt(c,n?.callee),c}return s.value};var an=e=>async(t,r,o,n)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,le())));throw Vt(c,n?.callee),c}return s.value};var Lr=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ve;return i.issues.length?{success:!1,error:new(e??Bt)(i.issues.map(s=>_e(s,n,le())))}:{success:!0,data:i.value}},cn=Lr(Ur),Dr=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>_e(s,n,le())))}:{success:!0,data:i.value}},un=Dr(Ur);var ln=/^[cC][^\s-]{8,}$/,pn=/^[0-9a-z]+$/,dn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mn=/^[0-9a-vA-V]{20}$/,fn=/^[A-Za-z0-9]{27}$/,hn=/^[a-zA-Z0-9_-]{21}$/,gn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _n=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Mr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var xn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var _u="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function zn(){return new RegExp(_u,"u")}var yn=/^(?:(?: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])$/,vn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,bn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,wn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fr=/^[A-Za-z0-9_-]*$/,$n=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var kn=/^\+(?:[0-9]){6,14}[0-9]$/,Rn="(?:(?:\\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])))",Pn=new RegExp(`^${Rn}$`);function In(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Tn(e){return new RegExp(`^${In(e)}$`)}function Zn(e){let t=In({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Rn}T(?:${o})$`)}var On=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},En=/^\d+n?$/,Cn=/^\d+$/,An=/^-?\d+(?:\.\d+)?/i,Un=/true|false/i,Nn=/null/i;var jn=/^[^A-Z]*$/,Ln=/^[^a-z]*$/;var se=u("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Dn={number:"number",bigint:"bigint",object:"date"},Vr=u("$ZodCheckLessThan",(e,t)=>{se.init(e,t);let r=Dn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),qr=u("$ZodCheckGreaterThan",(e,t)=>{se.init(e,t);let r=Dn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mn=u("$ZodCheckMultipleOf",(e,t)=>{se.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Ir(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Fn=u("$ZodCheckNumberFormat",(e,t)=>{se.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Cr[t.format];e._zod.onattach.push(s=>{let c=s._zod.bag;c.format=t.format,c.minimum=n,c.maximum=i,r&&(c.pattern=Cn)}),e._zod.check=s=>{let c=s.value;if(r){if(!Number.isInteger(c)){s.issues.push({expected:o,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort});return}}c<n&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}});var Vn=u("$ZodCheckMaxLength",(e,t)=>{var r;se.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!ut(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=pt(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),qn=u("$ZodCheckMinLength",(e,t)=>{var r;se.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!ut(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=pt(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Bn=u("$ZodCheckLengthEquals",(e,t)=>{var r;se.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!ut(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let s=pt(n),c=i>t.length;o.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),dt=u("$ZodCheckStringFormat",(e,t)=>{var r,o;se.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Wn=u("$ZodCheckRegex",(e,t)=>{dt.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Jn=u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=jn),dt.init(e,t)}),Hn=u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ln),dt.init(e,t)}),Gn=u("$ZodCheckIncludes",(e,t)=>{se.init(e,t);let r=ke(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Kn=u("$ZodCheckStartsWith",(e,t)=>{se.init(e,t);let r=new RegExp(`^${ke(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Yn=u("$ZodCheckEndsWith",(e,t)=>{se.init(e,t);let r=new RegExp(`.*${ke(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Xn=u("$ZodCheckOverwrite",(e,t)=>{se.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Jt=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
6
7
|
`).filter(s=>s),n=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,n.join(`
|
|
7
|
-
`))}};var
|
|
8
|
-
if (${
|
|
9
|
-
if (input[${
|
|
10
|
-
if (${
|
|
11
|
-
newResult[${
|
|
8
|
+
`))}};var ei={major:4,minor:0,patch:0};var C=u("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ei;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,s,c)=>{let l=Ze(i),p;for(let h of s){if(h._zod.def.when){if(!h._zod.def.when(i))continue}else if(l)continue;let _=i.issues.length,z=h._zod.check(i);if(z instanceof Promise&&c?.async===!1)throw new ve;if(p||z instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await z,i.issues.length!==_&&(l||(l=Ze(i,_)))});else{if(i.issues.length===_)continue;l||(l=Ze(i,_))}}return p?p.then(()=>i):i};e._zod.run=(i,s)=>{let c=e._zod.parse(i,s);if(c instanceof Promise){if(s.async===!1)throw new ve;return c.then(l=>n(l,o,s))}return n(c,o,s)}}e["~standard"]={validate:n=>{try{let i=cn(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return un(e,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Gt=u("$ZodString",(e,t)=>{C.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??On(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),M=u("$ZodStringFormat",(e,t)=>{dt.init(e,t),Gt.init(e,t)}),li=u("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_n),M.init(e,t)}),pi=u("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Mr(o))}else t.pattern??(t.pattern=Mr());M.init(e,t)}),di=u("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=xn),M.init(e,t)}),mi=u("$ZodURL",(e,t)=>{M.init(e,t),e._zod.check=r=>{try{let o=r.value,n=new URL(o),i=n.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$n.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!o.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),fi=u("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=zn()),M.init(e,t)}),hi=u("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=hn),M.init(e,t)}),gi=u("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ln),M.init(e,t)}),_i=u("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=pn),M.init(e,t)}),xi=u("$ZodULID",(e,t)=>{t.pattern??(t.pattern=dn),M.init(e,t)}),zi=u("$ZodXID",(e,t)=>{t.pattern??(t.pattern=mn),M.init(e,t)}),yi=u("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=fn),M.init(e,t)}),vi=u("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Zn(t)),M.init(e,t)}),bi=u("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Pn),M.init(e,t)}),wi=u("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Tn(t)),M.init(e,t)}),Si=u("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=gn),M.init(e,t)}),$i=u("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yn),M.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv4"})}),ki=u("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vn),M.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ri=u("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bn),M.init(e,t)}),Pi=u("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=wn),M.init(e,t),e._zod.check=r=>{let[o,n]=r.value.split("/");try{if(!n)throw new Error;let i=Number(n);if(`${i}`!==n)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Ii(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ti=u("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Sn),M.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Ii(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function xu(e){if(!Fr.test(e))return!1;let t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ii(r)}var Zi=u("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fr),M.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{xu(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Oi=u("$ZodE164",(e,t)=>{t.pattern??(t.pattern=kn),M.init(e,t)});function zu(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}var Ei=u("$ZodJWT",(e,t)=>{M.init(e,t),e._zod.check=r=>{zu(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Wr=u("$ZodNumber",(e,t)=>{C.init(e,t),e._zod.pattern=e._zod.bag.pattern??An,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Ci=u("$ZodNumber",(e,t)=>{Fn.init(e,t),Wr.init(e,t)}),Ai=u("$ZodBoolean",(e,t)=>{C.init(e,t),e._zod.pattern=Un,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Ui=u("$ZodBigInt",(e,t)=>{C.init(e,t),e._zod.pattern=En,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var Ni=u("$ZodNull",(e,t)=>{C.init(e,t),e._zod.pattern=Nn,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),ji=u("$ZodAny",(e,t)=>{C.init(e,t),e._zod.parse=r=>r}),Li=u("$ZodUnknown",(e,t)=>{C.init(e,t),e._zod.parse=r=>r}),Di=u("$ZodNever",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});var Mi=u("$ZodDate",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function ti(e,t,r){e.issues.length&&t.issues.push(...ze(r,e.issues)),t.value[r]=e.value}var Fi=u("$ZodArray",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let c=n[s],l=t.element._zod.run({value:c,issues:[]},o);l instanceof Promise?i.push(l.then(p=>ti(p,r,s))):ti(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Ht(e,t,r){e.issues.length&&t.issues.push(...ze(r,e.issues)),t.value[r]=e.value}function ri(e,t,r,o){e.issues.length?o[r]===void 0?r in o?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...ze(r,e.issues)):e.value===void 0?r in o&&(t.value[r]=void 0):t.value[r]=e.value}var Vi=u("$ZodObject",(e,t)=>{C.init(e,t);let r=ct(()=>{let _=Object.keys(t.shape);for(let m of _)if(!(t.shape[m]instanceof C))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let z=Er(t.shape);return{shape:t.shape,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(z)}});N(e._zod,"propValues",()=>{let _=t.shape,z={};for(let m in _){let k=_[m]._zod;if(k.values){z[m]??(z[m]=new Set);for(let P of k.values)z[m].add(P)}}return z});let o=_=>{let z=new Jt(["shape","payload","ctx"]),m=r.value,k=A=>{let $=Te(A);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};z.write("const input = payload.value;");let P=Object.create(null),ee=0;for(let A of m.keys)P[A]=`key_${ee++}`;z.write("const newResult = {}");for(let A of m.keys)if(m.optionalKeys.has(A)){let $=P[A];z.write(`const ${$} = ${k(A)};`);let O=Te(A);z.write(`
|
|
9
|
+
if (${$}.issues.length) {
|
|
10
|
+
if (input[${O}] === undefined) {
|
|
11
|
+
if (${O} in input) {
|
|
12
|
+
newResult[${O}] = undefined;
|
|
12
13
|
}
|
|
13
14
|
} else {
|
|
14
15
|
payload.issues = payload.issues.concat(
|
|
15
|
-
${
|
|
16
|
+
${$}.issues.map((iss) => ({
|
|
16
17
|
...iss,
|
|
17
|
-
path: iss.path ? [${
|
|
18
|
+
path: iss.path ? [${O}, ...iss.path] : [${O}],
|
|
18
19
|
}))
|
|
19
20
|
);
|
|
20
21
|
}
|
|
21
|
-
} else if (${
|
|
22
|
-
if (${
|
|
22
|
+
} else if (${$}.value === undefined) {
|
|
23
|
+
if (${O} in input) newResult[${O}] = undefined;
|
|
23
24
|
} else {
|
|
24
|
-
newResult[${
|
|
25
|
+
newResult[${O}] = ${$}.value;
|
|
25
26
|
}
|
|
26
|
-
`)}else{let
|
|
27
|
-
if (${
|
|
27
|
+
`)}else{let $=P[A];z.write(`const ${$} = ${k(A)};`),z.write(`
|
|
28
|
+
if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
|
|
28
29
|
...iss,
|
|
29
|
-
path: iss.path ? [${
|
|
30
|
-
})));`),x.write(`newResult[${Pe(A)}] = ${k}.value`)}x.write("payload.value = newResult;"),x.write("return payload;");let H=x.compile();return(A,k)=>H(g,A,k)},n,i=Me,s=!Lt.jitless,l=s&&kr.value,p=t.catchall,f;e._zod.parse=(g,x)=>{f??(f=r.value);let _=g.value;if(!i(_))return g.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),g;let S=[];if(s&&l&&x?.async===!1&&x.jitless!==!0)n||(n=o(t.shape)),g=n(g,x);else{g.value={};let k=f.shape;for(let T of f.keys){let v=k[T],z=v._zod.run({value:_[T],issues:[]},x),$=v._zod.optin==="optional"&&v._zod.optout==="optional";z instanceof Promise?S.push(z.then(D=>$?Hn(D,g,T,_):Wt(D,g,T))):$?Hn(z,g,T,_):Wt(z,g,T)}}if(!p)return S.length?Promise.all(S).then(()=>g):g;let R=[],ee=f.keySet,H=p._zod,A=H.def.type;for(let k of Object.keys(_)){if(ee.has(k))continue;if(A==="never"){R.push(k);continue}let T=H.run({value:_[k],issues:[]},x);T instanceof Promise?S.push(T.then(v=>Wt(v,g,k))):Wt(T,g,k)}return R.length&&g.issues.push({code:"unrecognized_keys",keys:R,input:_,inst:e}),S.length?Promise.all(S).then(()=>g):g}});function Kn(e,t,r,o){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(n=>n.issues.map(i=>_e(i,o,ce())))}),t}var Fr=u("$ZodUnion",(e,t)=>{E.init(e,t),N(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),N(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),N(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),N(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>at(o.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1,i=[];for(let s of t.options){let c=s._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),n=!0;else{if(c.issues.length===0)return c;i.push(c)}}return n?Promise.all(i).then(s=>Kn(s,r,e,o)):Kn(i,r,e,o)}}),Ni=u("$ZodDiscriminatedUnion",(e,t)=>{Fr.init(e,t);let r=e._zod.parse;N(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,l]of Object.entries(s)){n[c]||(n[c]=new Set);for(let p of l)n[c].add(p)}}return n});let o=it(()=>{let n=t.options,i=new Map;for(let s of n){let c=s._zod.propValues[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of c){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!Me(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let c=o.value.get(s?.[t.discriminator]);return c?c._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),n)}}),ji=u("$ZodIntersection",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,p])=>Yn(r,l,p)):Yn(r,i,s)}});function Dr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Fe(e)&&Fe(t)){let r=Object.keys(t),o=Object.keys(e).filter(i=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=Dr(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=Dr(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Yn(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ze(e))return e;let o=Dr(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Li=u("$ZodRecord",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Fe(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let p=t.valueType._zod.run({value:n[l],issues:[]},o);p instanceof Promise?i.push(p.then(f=>{f.issues.length&&r.issues.push(...xe(l,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...xe(l,p.issues)),r.value[l]=p.value)}let c;for(let l in n)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:c})}else{r.value={};for(let s of Reflect.ownKeys(n)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(p=>_e(p,o,ce())),input:s,path:[s],inst:e}),r.value[c.value]=c.value;continue}let l=t.valueType._zod.run({value:n[s],issues:[]},o);l instanceof Promise?i.push(l.then(p=>{p.issues.length&&r.issues.push(...xe(s,p.issues)),r.value[c.value]=p.value})):(l.issues.length&&r.issues.push(...xe(s,l.issues)),r.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Di=u("$ZodEnum",(e,t)=>{E.init(e,t);let r=wr(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(o=>Rr.has(typeof o)).map(o=>typeof o=="string"?$e(o):o.toString()).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;return e._zod.values.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Mi=u("$ZodLiteral",(e,t)=>{E.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?$e(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}});var Fi=u("$ZodTransform",(e,t)=>{E.init(e,t),e._zod.parse=(r,o)=>{let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(s=>(r.value=s,r));if(n instanceof Promise)throw new ye;return r.value=n,r}}),qi=u("$ZodOptional",(e,t)=>{E.init(e,t),e._zod.optin="optional",e._zod.optout="optional",N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${at(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,o):r.value===void 0?r:t.innerType._zod.run(r,o)}),Bi=u("$ZodNullable",(e,t)=>{E.init(e,t),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${at(r.source)}|null)$`):void 0}),N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),Vi=u("$ZodDefault",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Xn(i,t)):Xn(n,t)}});function Xn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Wi=u("$ZodPrefault",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),Ji=u("$ZodNonOptional",(e,t)=>{E.init(e,t),N(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Qn(i,e)):Qn(n,e)}});function Qn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Gi=u("$ZodCatch",(e,t)=>{E.init(e,t),e._zod.optin="optional",N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>_e(s,o,ce()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(i=>_e(i,o,ce()))},input:r.value}),r.issues=[]),r)}});var Hi=u("$ZodPipe",(e,t)=>{E.init(e,t),N(e._zod,"values",()=>t.in._zod.values),N(e._zod,"optin",()=>t.in._zod.optin),N(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,o)=>{let n=t.in._zod.run(r,o);return n instanceof Promise?n.then(i=>ei(i,t,o)):ei(n,t,o)}});function ei(e,t,r){return Ze(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Ki=u("$ZodReadonly",(e,t)=>{E.init(e,t),N(e._zod,"propValues",()=>t.innerType._zod.propValues),N(e._zod,"values",()=>t.innerType._zod.values),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(ti):ti(n)}});function ti(e){return e.value=Object.freeze(e.value),e}var Yi=u("$ZodCustom",(e,t)=>{ie.init(e,t),E.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(i=>ri(i,r,o,e));ri(n,r,o,e)}});function ri(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),t.issues.push(Ir(n))}}var cu=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},uu=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${cu(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${Ft(o.values[0])}`:`Invalid option: expected one of ${Dt(o.values,"|")}`;case"too_big":{let n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{let n=o.inclusive?">=":">",i=t(o.origin);return i?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{let n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Dt(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Xi(){return{localeError:uu()}}var lu=Symbol("ZodOutput"),pu=Symbol("ZodInput"),qr=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let o=r[0];if(this._map.set(t,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let o={...this.get(r)??{}};return delete o.id,{...o,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Qi(){return new qr}var qe=Qi();function es(e,t){return new e({type:"string",...b(t)})}function ts(e,t){return new e({type:"string",coerce:!0,...b(t)})}function rs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...b(t)})}function Br(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...b(t)})}function os(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...b(t)})}function ns(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(t)})}function is(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(t)})}function ss(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(t)})}function Vr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...b(t)})}function as(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...b(t)})}function cs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(t)})}function us(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...b(t)})}function ls(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(t)})}function ps(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...b(t)})}function ds(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...b(t)})}function ms(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(t)})}function fs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(t)})}function hs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(t)})}function gs(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(t)})}function _s(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(t)})}function zs(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...b(t)})}function xs(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...b(t)})}function vs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...b(t)})}function ys(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...b(t)})}function ws(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(t)})}function bs(e,t){return new e({type:"string",format:"date",check:"string_format",...b(t)})}function Ss(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...b(t)})}function $s(e,t){return new e({type:"string",format:"duration",check:"string_format",...b(t)})}function ks(e,t){return new e({type:"number",checks:[],...b(t)})}function Rs(e,t){return new e({type:"number",coerce:!0,checks:[],...b(t)})}function Ps(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...b(t)})}function Zs(e,t){return new e({type:"boolean",...b(t)})}function Is(e,t){return new e({type:"boolean",coerce:!0,...b(t)})}function Ts(e,t){return new e({type:"bigint",coerce:!0,...b(t)})}function Os(e,t){return new e({type:"null",...b(t)})}function Cs(e){return new e({type:"any"})}function Es(e){return new e({type:"unknown"})}function As(e,t){return new e({type:"never",...b(t)})}function Us(e,t){return new e({type:"date",coerce:!0,...b(t)})}function Be(e,t){return new jr({check:"less_than",...b(t),value:e,inclusive:!1})}function we(e,t){return new jr({check:"less_than",...b(t),value:e,inclusive:!0})}function Ve(e,t){return new Lr({check:"greater_than",...b(t),value:e,inclusive:!1})}function ze(e,t){return new Lr({check:"greater_than",...b(t),value:e,inclusive:!0})}function lt(e,t){return new En({check:"multiple_of",...b(t),value:e})}function Gt(e,t){return new Un({check:"max_length",...b(t),maximum:e})}function We(e,t){return new Nn({check:"min_length",...b(t),minimum:e})}function Ht(e,t){return new jn({check:"length_equals",...b(t),length:e})}function Wr(e,t){return new Ln({check:"string_format",format:"regex",...b(t),pattern:e})}function Jr(e){return new Dn({check:"string_format",format:"lowercase",...b(e)})}function Gr(e){return new Mn({check:"string_format",format:"uppercase",...b(e)})}function Hr(e,t){return new Fn({check:"string_format",format:"includes",...b(t),includes:e})}function Kr(e,t){return new qn({check:"string_format",format:"starts_with",...b(t),prefix:e})}function Yr(e,t){return new Bn({check:"string_format",format:"ends_with",...b(t),suffix:e})}function Ie(e){return new Vn({check:"overwrite",tx:e})}function Xr(e){return Ie(t=>t.normalize(e))}function Qr(){return Ie(e=>e.trim())}function eo(){return Ie(e=>e.toLowerCase())}function to(){return Ie(e=>e.toUpperCase())}function Ns(e,t,r){return new e({type:"array",element:t,...b(r)})}function js(e,t,r){let o=b(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ls(e,t,r){return new e({type:"custom",check:"custom",fn:t,...b(r)})}var pt={};gr(pt,{ZodISODate:()=>Ms,ZodISODateTime:()=>Ds,ZodISODuration:()=>qs,ZodISOTime:()=>Fs,date:()=>oo,datetime:()=>ro,duration:()=>io,time:()=>no});var Ds=u("ZodISODateTime",(e,t)=>{fi.init(e,t),q.init(e,t)});function ro(e){return ws(Ds,e)}var Ms=u("ZodISODate",(e,t)=>{hi.init(e,t),q.init(e,t)});function oo(e){return bs(Ms,e)}var Fs=u("ZodISOTime",(e,t)=>{gi.init(e,t),q.init(e,t)});function no(e){return Ss(Fs,e)}var qs=u("ZodISODuration",(e,t)=>{_i.init(e,t),q.init(e,t)});function io(e){return $s(qs,e)}var Vs=(e,t)=>{qt.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Cr(e,r)},flatten:{value:r=>Or(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},Wm=u("ZodError",Vs),dt=u("ZodError",Vs,{Parent:Error});var Ws=Xo(dt),Js=Qo(dt),Gs=Er(dt),Hs=Ar(dt);var j=u("ZodType",(e,t)=>(E.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),e.clone=(r,o)=>ge(e,r,o),e.brand=()=>e,e.register=(r,o)=>(r.add(e,o),e),e.parse=(r,o)=>Ws(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Gs(e,r,o),e.parseAsync=async(r,o)=>Js(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Hs(e,r,o),e.spa=e.safeParseAsync,e.refine=(r,o)=>e.check(il(r,o)),e.superRefine=r=>e.check(sl(r)),e.overwrite=r=>e.check(Ie(r)),e.optional=()=>V(e),e.nullable=()=>Xs(e),e.nullish=()=>V(Xs(e)),e.nonoptional=r=>Xu(e,r),e.array=()=>m(e),e.or=r=>F([e,r]),e.and=r=>Xt(e,r),e.transform=r=>ao(e,ca(r)),e.default=r=>Hu(e,r),e.prefault=r=>Yu(e,r),e.catch=r=>el(e,r),e.pipe=r=>ao(e,r),e.readonly=()=>ol(e),e.describe=r=>{let o=e.clone();return qe.add(o,{description:r}),o},Object.defineProperty(e,"description",{get(){return qe.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return qe.get(e);let o=e.clone();return qe.add(o,r[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Qs=u("_ZodString",(e,t)=>{Jt.init(e,t),j.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...o)=>e.check(Wr(...o)),e.includes=(...o)=>e.check(Hr(...o)),e.startsWith=(...o)=>e.check(Kr(...o)),e.endsWith=(...o)=>e.check(Yr(...o)),e.min=(...o)=>e.check(We(...o)),e.max=(...o)=>e.check(Gt(...o)),e.length=(...o)=>e.check(Ht(...o)),e.nonempty=(...o)=>e.check(We(1,...o)),e.lowercase=o=>e.check(Jr(o)),e.uppercase=o=>e.check(Gr(o)),e.trim=()=>e.check(Qr()),e.normalize=(...o)=>e.check(Xr(...o)),e.toLowerCase=()=>e.check(eo()),e.toUpperCase=()=>e.check(to())}),co=u("ZodString",(e,t)=>{Jt.init(e,t),Qs.init(e,t),e.email=r=>e.check(rs(xu,r)),e.url=r=>e.check(Vr(ea,r)),e.jwt=r=>e.check(ys(Eu,r)),e.emoji=r=>e.check(as(vu,r)),e.guid=r=>e.check(Br(Ks,r)),e.uuid=r=>e.check(os(Kt,r)),e.uuidv4=r=>e.check(ns(Kt,r)),e.uuidv6=r=>e.check(is(Kt,r)),e.uuidv7=r=>e.check(ss(Kt,r)),e.nanoid=r=>e.check(cs(yu,r)),e.guid=r=>e.check(Br(Ks,r)),e.cuid=r=>e.check(us(wu,r)),e.cuid2=r=>e.check(ls(bu,r)),e.ulid=r=>e.check(ps(Su,r)),e.base64=r=>e.check(zs(Tu,r)),e.base64url=r=>e.check(xs(Ou,r)),e.xid=r=>e.check(ds($u,r)),e.ksuid=r=>e.check(ms(ku,r)),e.ipv4=r=>e.check(fs(Ru,r)),e.ipv6=r=>e.check(hs(Pu,r)),e.cidrv4=r=>e.check(gs(Zu,r)),e.cidrv6=r=>e.check(_s(Iu,r)),e.e164=r=>e.check(vs(Cu,r)),e.datetime=r=>e.check(ro(r)),e.date=r=>e.check(oo(r)),e.time=r=>e.check(no(r)),e.duration=r=>e.check(io(r))});function a(e){return es(co,e)}var q=u("ZodStringFormat",(e,t)=>{M.init(e,t),Qs.init(e,t)}),xu=u("ZodEmail",(e,t)=>{ii.init(e,t),q.init(e,t)});var Ks=u("ZodGUID",(e,t)=>{oi.init(e,t),q.init(e,t)});var Kt=u("ZodUUID",(e,t)=>{ni.init(e,t),q.init(e,t)});var ea=u("ZodURL",(e,t)=>{si.init(e,t),q.init(e,t)});function ta(e){return Vr(ea,e)}var vu=u("ZodEmoji",(e,t)=>{ai.init(e,t),q.init(e,t)});var yu=u("ZodNanoID",(e,t)=>{ci.init(e,t),q.init(e,t)});var wu=u("ZodCUID",(e,t)=>{ui.init(e,t),q.init(e,t)});var bu=u("ZodCUID2",(e,t)=>{li.init(e,t),q.init(e,t)});var Su=u("ZodULID",(e,t)=>{pi.init(e,t),q.init(e,t)});var $u=u("ZodXID",(e,t)=>{di.init(e,t),q.init(e,t)});var ku=u("ZodKSUID",(e,t)=>{mi.init(e,t),q.init(e,t)});var Ru=u("ZodIPv4",(e,t)=>{zi.init(e,t),q.init(e,t)});var Pu=u("ZodIPv6",(e,t)=>{xi.init(e,t),q.init(e,t)});var Zu=u("ZodCIDRv4",(e,t)=>{vi.init(e,t),q.init(e,t)});var Iu=u("ZodCIDRv6",(e,t)=>{yi.init(e,t),q.init(e,t)});var Tu=u("ZodBase64",(e,t)=>{bi.init(e,t),q.init(e,t)});var Ou=u("ZodBase64URL",(e,t)=>{Si.init(e,t),q.init(e,t)});var Cu=u("ZodE164",(e,t)=>{$i.init(e,t),q.init(e,t)});var Eu=u("ZodJWT",(e,t)=>{ki.init(e,t),q.init(e,t)});var Yt=u("ZodNumber",(e,t)=>{Mr.init(e,t),j.init(e,t),e.gt=(o,n)=>e.check(Ve(o,n)),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.lt=(o,n)=>e.check(Be(o,n)),e.lte=(o,n)=>e.check(we(o,n)),e.max=(o,n)=>e.check(we(o,n)),e.int=o=>e.check(Ys(o)),e.safe=o=>e.check(Ys(o)),e.positive=o=>e.check(Ve(0,o)),e.nonnegative=o=>e.check(ze(0,o)),e.negative=o=>e.check(Be(0,o)),e.nonpositive=o=>e.check(we(0,o)),e.multipleOf=(o,n)=>e.check(lt(o,n)),e.step=(o,n)=>e.check(lt(o,n)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function I(e){return ks(Yt,e)}var Au=u("ZodNumberFormat",(e,t)=>{Ri.init(e,t),Yt.init(e,t)});function Ys(e){return Ps(Au,e)}var uo=u("ZodBoolean",(e,t)=>{Pi.init(e,t),j.init(e,t)});function U(e){return Zs(uo,e)}var ra=u("ZodBigInt",(e,t)=>{Zi.init(e,t),j.init(e,t),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.gt=(o,n)=>e.check(Ve(o,n)),e.gte=(o,n)=>e.check(ze(o,n)),e.min=(o,n)=>e.check(ze(o,n)),e.lt=(o,n)=>e.check(Be(o,n)),e.lte=(o,n)=>e.check(we(o,n)),e.max=(o,n)=>e.check(we(o,n)),e.positive=o=>e.check(Ve(BigInt(0),o)),e.negative=o=>e.check(Be(BigInt(0),o)),e.nonpositive=o=>e.check(we(BigInt(0),o)),e.nonnegative=o=>e.check(ze(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(lt(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Uu=u("ZodNull",(e,t)=>{Ii.init(e,t),j.init(e,t)});function oa(e){return Os(Uu,e)}var Nu=u("ZodAny",(e,t)=>{Ti.init(e,t),j.init(e,t)});function na(){return Cs(Nu)}var ju=u("ZodUnknown",(e,t)=>{Oi.init(e,t),j.init(e,t)});function B(){return Es(ju)}var Lu=u("ZodNever",(e,t)=>{Ci.init(e,t),j.init(e,t)});function Du(e){return As(Lu,e)}var ia=u("ZodDate",(e,t)=>{Ei.init(e,t),j.init(e,t),e.min=(o,n)=>e.check(ze(o,n)),e.max=(o,n)=>e.check(we(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var Mu=u("ZodArray",(e,t)=>{Ai.init(e,t),j.init(e,t),e.element=t.element,e.min=(r,o)=>e.check(We(r,o)),e.nonempty=r=>e.check(We(1,r)),e.max=(r,o)=>e.check(Gt(r,o)),e.length=(r,o)=>e.check(Ht(r,o)),e.unwrap=()=>e.element});function m(e,t){return Ns(Mu,e,t)}var sa=u("ZodObject",(e,t)=>{Ui.init(e,t),j.init(e,t),O.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ae(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:B()}),e.loose=()=>e.clone({...e._zod.def,catchall:B()}),e.strict=()=>e.clone({...e._zod.def,catchall:Du()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>O.extend(e,r),e.merge=r=>O.merge(e,r),e.pick=r=>O.pick(e,r),e.omit=r=>O.omit(e,r),e.partial=(...r)=>O.partial(ua,e,r[0]),e.required=(...r)=>O.required(la,e,r[0])});function h(e,t){let r={type:"object",get shape(){return O.assignProp(this,"shape",{...e}),this.shape},...O.normalizeParams(t)};return new sa(r)}function X(e,t){return new sa({type:"object",get shape(){return O.assignProp(this,"shape",{...e}),this.shape},catchall:B(),...O.normalizeParams(t)})}var aa=u("ZodUnion",(e,t)=>{Fr.init(e,t),j.init(e,t),e.options=t.options});function F(e,t){return new aa({type:"union",options:e,...O.normalizeParams(t)})}var Fu=u("ZodDiscriminatedUnion",(e,t)=>{aa.init(e,t),Ni.init(e,t)});function lo(e,t,r){return new Fu({type:"union",options:t,discriminator:e,...O.normalizeParams(r)})}var qu=u("ZodIntersection",(e,t)=>{ji.init(e,t),j.init(e,t)});function Xt(e,t){return new qu({type:"intersection",left:e,right:t})}var Bu=u("ZodRecord",(e,t)=>{Li.init(e,t),j.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,r){return new Bu({type:"record",keyType:e,valueType:t,...O.normalizeParams(r)})}var so=u("ZodEnum",(e,t)=>{Di.init(e,t),j.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new so({...t,checks:[],...O.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new so({...t,checks:[],...O.normalizeParams(n),entries:i})}});function ae(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new so({type:"enum",entries:r,...O.normalizeParams(t)})}var Vu=u("ZodLiteral",(e,t)=>{Mi.init(e,t),j.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function y(e,t){return new Vu({type:"literal",values:Array.isArray(e)?e:[e],...O.normalizeParams(t)})}var Wu=u("ZodTransform",(e,t)=>{Fi.init(e,t),j.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(O.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(O.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ca(e){return new Wu({type:"transform",transform:e})}var ua=u("ZodOptional",(e,t)=>{qi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V(e){return new ua({type:"optional",innerType:e})}var Ju=u("ZodNullable",(e,t)=>{Bi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xs(e){return new Ju({type:"nullable",innerType:e})}var Gu=u("ZodDefault",(e,t)=>{Vi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hu(e,t){return new Gu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var Ku=u("ZodPrefault",(e,t)=>{Wi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yu(e,t){return new Ku({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var la=u("ZodNonOptional",(e,t)=>{Ji.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xu(e,t){return new la({type:"nonoptional",innerType:e,...O.normalizeParams(t)})}var Qu=u("ZodCatch",(e,t)=>{Gi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function el(e,t){return new Qu({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var tl=u("ZodPipe",(e,t)=>{Hi.init(e,t),j.init(e,t),e.in=t.in,e.out=t.out});function ao(e,t){return new tl({type:"pipe",in:e,out:t})}var rl=u("ZodReadonly",(e,t)=>{Ki.init(e,t),j.init(e,t)});function ol(e){return new rl({type:"readonly",innerType:e})}var pa=u("ZodCustom",(e,t)=>{Yi.init(e,t),j.init(e,t)});function nl(e){let t=new ie({check:"custom"});return t._zod.check=e,t}function da(e,t){return js(pa,e??(()=>!0),t)}function il(e,t={}){return Ls(pa,e,t)}function sl(e){let t=nl(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(O.issue(o,r.value,t._zod.def));else{let n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(O.issue(n))}},e(r.value,r)));return t}function po(e,t){return ao(ca(e),t)}var ma={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Qt={};gr(Qt,{bigint:()=>ll,boolean:()=>ul,date:()=>pl,number:()=>cl,string:()=>al});function al(e){return ts(co,e)}function cl(e){return Rs(Yt,e)}function ul(e){return Is(uo,e)}function ll(e){return Ts(ra,e)}function pl(e){return Us(ia,e)}ce(Xi());var mo="2025-11-25";var ml="io.modelcontextprotocol/related-task",tr="2.0",Q=da(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ha=F([a(),I().int()]),ga=a(),Mf=X({ttl:I().optional(),pollInterval:I().optional()}),fl=h({ttl:I().optional()}),hl=h({taskId:a()}),fo=X({progressToken:ha.optional(),[ml]:hl.optional()}),ue=h({_meta:fo.optional()}),rr=ue.extend({task:fl.optional()});var re=h({method:a(),params:ue.loose().optional()}),me=h({_meta:fo.optional()}),fe=h({method:a(),params:me.loose().optional()}),oe=X({_meta:fo.optional()}),or=F([a(),I().int()]),_a=h({jsonrpc:y(tr),id:or,...re.shape}).strict(),za=e=>_a.safeParse(e).success,gl=h({jsonrpc:y(tr),...fe.shape}).strict();var ho=h({jsonrpc:y(tr),id:or,result:oe}).strict(),xa=e=>ho.safeParse(e).success;var fa;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(fa||(fa={}));var va=h({jsonrpc:y(tr),id:or.optional(),error:h({code:I().int(),message:a(),data:B().optional()})}).strict();var He=F([_a,gl,ho,va]),Ff=F([ho,va]),ya=oe.strict(),_l=me.extend({requestId:or.optional(),reason:a().optional()}),wa=fe.extend({method:y("notifications/cancelled"),params:_l}),zl=h({src:a(),mimeType:a().optional(),sizes:m(a()).optional(),theme:ae(["light","dark"]).optional()}),mt=h({icons:m(zl).optional()}),Ge=h({name:a(),title:a().optional()}),ba=Ge.extend({...Ge.shape,...mt.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),xl=Xt(h({applyDefaults:U().optional()}),L(a(),B())),vl=po(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Xt(h({form:xl.optional(),url:Q.optional()}),L(a(),B()).optional())),yl=X({list:Q.optional(),cancel:Q.optional(),requests:X({sampling:X({createMessage:Q.optional()}).optional(),elicitation:X({create:Q.optional()}).optional()}).optional()}),wl=X({list:Q.optional(),cancel:Q.optional(),requests:X({tools:X({call:Q.optional()}).optional()}).optional()}),bl=h({experimental:L(a(),Q).optional(),sampling:h({context:Q.optional(),tools:Q.optional()}).optional(),elicitation:vl.optional(),roots:h({listChanged:U().optional()}).optional(),tasks:yl.optional(),extensions:L(a(),Q).optional()}),Sl=ue.extend({protocolVersion:a(),capabilities:bl,clientInfo:ba}),$l=re.extend({method:y("initialize"),params:Sl});var kl=h({experimental:L(a(),Q).optional(),logging:Q.optional(),completions:Q.optional(),prompts:h({listChanged:U().optional()}).optional(),resources:h({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:h({listChanged:U().optional()}).optional(),tasks:wl.optional(),extensions:L(a(),Q).optional()}),Rl=oe.extend({protocolVersion:a(),capabilities:kl,serverInfo:ba,instructions:a().optional()}),Sa=fe.extend({method:y("notifications/initialized"),params:me.optional()}),$a=e=>Sa.safeParse(e).success,ka=re.extend({method:y("ping"),params:ue.optional()}),Pl=h({progress:I(),total:V(I()),message:V(a())}),Zl=h({...me.shape,...Pl.shape,progressToken:ha}),Ra=fe.extend({method:y("notifications/progress"),params:Zl}),Il=ue.extend({cursor:ga.optional()}),ft=re.extend({params:Il.optional()}),ht=oe.extend({nextCursor:ga.optional()}),Tl=ae(["working","input_required","completed","failed","cancelled"]),gt=h({taskId:a(),status:Tl,ttl:F([I(),oa()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:V(I()),statusMessage:V(a())}),Pa=oe.extend({task:gt}),Ol=me.merge(gt),Za=fe.extend({method:y("notifications/tasks/status"),params:Ol}),Ia=re.extend({method:y("tasks/get"),params:ue.extend({taskId:a()})}),Ta=oe.merge(gt),Oa=re.extend({method:y("tasks/result"),params:ue.extend({taskId:a()})}),qf=oe.loose(),Ca=ft.extend({method:y("tasks/list")}),Ea=ht.extend({tasks:m(gt)}),Aa=re.extend({method:y("tasks/cancel"),params:ue.extend({taskId:a()})}),Bf=oe.merge(gt),Ua=h({uri:a(),mimeType:V(a()),_meta:L(a(),B()).optional()}),Na=Ua.extend({text:a()}),go=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ja=Ua.extend({blob:go}),_t=ae(["user","assistant"]),Ke=h({audience:m(_t).optional(),priority:I().min(0).max(1).optional(),lastModified:pt.datetime({offset:!0}).optional()}),La=h({...Ge.shape,...mt.shape,uri:a(),description:V(a()),mimeType:V(a()),size:V(I()),annotations:Ke.optional(),_meta:V(X({}))}),Cl=h({...Ge.shape,...mt.shape,uriTemplate:a(),description:V(a()),mimeType:V(a()),annotations:Ke.optional(),_meta:V(X({}))}),El=ft.extend({method:y("resources/list")}),Al=ht.extend({resources:m(La)}),Ul=ft.extend({method:y("resources/templates/list")}),Nl=ht.extend({resourceTemplates:m(Cl)}),_o=ue.extend({uri:a()}),jl=_o,Ll=re.extend({method:y("resources/read"),params:jl}),Dl=oe.extend({contents:m(F([Na,ja]))}),Ml=fe.extend({method:y("notifications/resources/list_changed"),params:me.optional()}),Fl=_o,ql=re.extend({method:y("resources/subscribe"),params:Fl}),Bl=_o,Vl=re.extend({method:y("resources/unsubscribe"),params:Bl}),Wl=me.extend({uri:a()}),Jl=fe.extend({method:y("notifications/resources/updated"),params:Wl}),Gl=h({name:a(),description:V(a()),required:V(U())}),Hl=h({...Ge.shape,...mt.shape,description:V(a()),arguments:V(m(Gl)),_meta:V(X({}))}),Kl=ft.extend({method:y("prompts/list")}),Yl=ht.extend({prompts:m(Hl)}),Xl=ue.extend({name:a(),arguments:L(a(),a()).optional()}),Ql=re.extend({method:y("prompts/get"),params:Xl}),zo=h({type:y("text"),text:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),xo=h({type:y("image"),data:go,mimeType:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),vo=h({type:y("audio"),data:go,mimeType:a(),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),ep=h({type:y("tool_use"),name:a(),id:a(),input:L(a(),B()),_meta:L(a(),B()).optional()}),tp=h({type:y("resource"),resource:F([Na,ja]),annotations:Ke.optional(),_meta:L(a(),B()).optional()}),rp=La.extend({type:y("resource_link")}),yo=F([zo,xo,vo,rp,tp]),op=h({role:_t,content:yo}),np=oe.extend({description:a().optional(),messages:m(op)}),ip=fe.extend({method:y("notifications/prompts/list_changed"),params:me.optional()}),sp=h({title:a().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),ap=h({taskSupport:ae(["required","optional","forbidden"]).optional()}),Da=h({...Ge.shape,...mt.shape,description:a().optional(),inputSchema:h({type:y("object"),properties:L(a(),Q).optional(),required:m(a()).optional()}).catchall(B()),outputSchema:h({type:y("object"),properties:L(a(),Q).optional(),required:m(a()).optional()}).catchall(B()).optional(),annotations:sp.optional(),execution:ap.optional(),_meta:L(a(),B()).optional()}),cp=ft.extend({method:y("tools/list")}),up=ht.extend({tools:m(Da)}),Ma=oe.extend({content:m(yo).default([]),structuredContent:L(a(),B()).optional(),isError:U().optional()}),Vf=Ma.or(oe.extend({toolResult:B()})),lp=rr.extend({name:a(),arguments:L(a(),B()).optional()}),pp=re.extend({method:y("tools/call"),params:lp}),dp=fe.extend({method:y("notifications/tools/list_changed"),params:me.optional()}),Wf=h({autoRefresh:U().default(!0),debounceMs:I().int().nonnegative().default(300)}),Fa=ae(["debug","info","notice","warning","error","critical","alert","emergency"]),mp=ue.extend({level:Fa}),fp=re.extend({method:y("logging/setLevel"),params:mp}),hp=me.extend({level:Fa,logger:a().optional(),data:B()}),gp=fe.extend({method:y("notifications/message"),params:hp}),_p=h({name:a().optional()}),zp=h({hints:m(_p).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),xp=h({mode:ae(["auto","required","none"]).optional()}),vp=h({type:y("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:m(yo).default([]),structuredContent:h({}).loose().optional(),isError:U().optional(),_meta:L(a(),B()).optional()}),yp=lo("type",[zo,xo,vo]),er=lo("type",[zo,xo,vo,ep,vp]),wp=h({role:_t,content:F([er,m(er)]),_meta:L(a(),B()).optional()}),bp=rr.extend({messages:m(wp),modelPreferences:zp.optional(),systemPrompt:a().optional(),includeContext:ae(["none","thisServer","allServers"]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:m(a()).optional(),metadata:Q.optional(),tools:m(Da).optional(),toolChoice:xp.optional()}),Sp=re.extend({method:y("sampling/createMessage"),params:bp}),$p=oe.extend({model:a(),stopReason:V(ae(["endTurn","stopSequence","maxTokens"]).or(a())),role:_t,content:yp}),kp=oe.extend({model:a(),stopReason:V(ae(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:_t,content:F([er,m(er)])}),Rp=h({type:y("boolean"),title:a().optional(),description:a().optional(),default:U().optional()}),Pp=h({type:y("string"),title:a().optional(),description:a().optional(),minLength:I().optional(),maxLength:I().optional(),format:ae(["email","uri","date","date-time"]).optional(),default:a().optional()}),Zp=h({type:ae(["number","integer"]),title:a().optional(),description:a().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),Ip=h({type:y("string"),title:a().optional(),description:a().optional(),enum:m(a()),default:a().optional()}),Tp=h({type:y("string"),title:a().optional(),description:a().optional(),oneOf:m(h({const:a(),title:a()})),default:a().optional()}),Op=h({type:y("string"),title:a().optional(),description:a().optional(),enum:m(a()),enumNames:m(a()).optional(),default:a().optional()}),Cp=F([Ip,Tp]),Ep=h({type:y("array"),title:a().optional(),description:a().optional(),minItems:I().optional(),maxItems:I().optional(),items:h({type:y("string"),enum:m(a())}),default:m(a()).optional()}),Ap=h({type:y("array"),title:a().optional(),description:a().optional(),minItems:I().optional(),maxItems:I().optional(),items:h({anyOf:m(h({const:a(),title:a()}))}),default:m(a()).optional()}),Up=F([Ep,Ap]),Np=F([Op,Cp,Up]),jp=F([Np,Rp,Pp,Zp]),Lp=rr.extend({mode:y("form").optional(),message:a(),requestedSchema:h({type:y("object"),properties:L(a(),jp),required:m(a()).optional()})}),Dp=rr.extend({mode:y("url"),message:a(),elicitationId:a(),url:a().url()}),Mp=F([Lp,Dp]),Fp=re.extend({method:y("elicitation/create"),params:Mp}),qp=me.extend({elicitationId:a()}),Bp=fe.extend({method:y("notifications/elicitation/complete"),params:qp}),Vp=oe.extend({action:ae(["accept","decline","cancel"]),content:po(e=>e===null?void 0:e,L(a(),F([a(),I(),U(),m(a())])).optional())}),Wp=h({type:y("ref/resource"),uri:a()});var Jp=h({type:y("ref/prompt"),name:a()}),Gp=ue.extend({ref:F([Jp,Wp]),argument:h({name:a(),value:a()}),context:h({arguments:L(a(),a()).optional()}).optional()}),Hp=re.extend({method:y("completion/complete"),params:Gp});var Kp=oe.extend({completion:X({values:m(a()).max(100),total:V(I().int()),hasMore:V(U())})}),Yp=h({uri:a().startsWith("file://"),name:a().optional(),_meta:L(a(),B()).optional()}),Xp=re.extend({method:y("roots/list"),params:ue.optional()}),Qp=oe.extend({roots:m(Yp)}),ed=fe.extend({method:y("notifications/roots/list_changed"),params:me.optional()}),Jf=F([ka,$l,Hp,fp,Ql,Kl,El,Ul,Ll,ql,Vl,pp,cp,Ia,Oa,Ca,Aa]),Gf=F([wa,Ra,Sa,ed,Za]),Hf=F([ya,$p,kp,Vp,Qp,Ta,Ea,Pa]),Kf=F([ka,Sp,Fp,Xp,Ia,Oa,Ca,Aa]),Yf=F([wa,Ra,gp,Jl,Ml,dp,ip,Za,Bp]),Xf=F([ya,Rl,Kp,np,Yl,Al,Nl,Dl,Ma,up,Ta,Ea,Pa]);var nr=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
31
|
-
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),
|
|
32
|
-
`}var ir=class{constructor(t=Ba.stdin,r=Ba.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new nr,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let o=qa(t);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};function sr(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Va(e=fetch,t){return t?async(r,o)=>{let n={...t,...o,headers:o?.headers?{...sr(t.headers),...sr(o.headers)}:t.headers};return e(r,n)}:e}var wo;wo=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function rd(e){return(await wo).getRandomValues(new Uint8Array(e))}async function od(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let n=await rd(e-o.length);for(let i of n)i<r&&(o+=t[i%t.length])}return o}async function nd(e){return await od(e)}async function id(e){let t=await(await wo).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function bo(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await nd(e),r=await id(t);return{code_verifier:t,code_challenge:r}}var ne=ta().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ma.custom,message:"URL must be parseable",fatal:!0}),xr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ja=X({resource:a().url(),authorization_servers:m(ne).optional(),jwks_uri:a().url().optional(),scopes_supported:m(a()).optional(),bearer_methods_supported:m(a()).optional(),resource_signing_alg_values_supported:m(a()).optional(),resource_name:a().optional(),resource_documentation:a().optional(),resource_policy_uri:a().url().optional(),resource_tos_uri:a().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:m(a()).optional(),dpop_signing_alg_values_supported:m(a()).optional(),dpop_bound_access_tokens_required:U().optional()}),So=X({issuer:a(),authorization_endpoint:ne,token_endpoint:ne,registration_endpoint:ne.optional(),scopes_supported:m(a()).optional(),response_types_supported:m(a()),response_modes_supported:m(a()).optional(),grant_types_supported:m(a()).optional(),token_endpoint_auth_methods_supported:m(a()).optional(),token_endpoint_auth_signing_alg_values_supported:m(a()).optional(),service_documentation:ne.optional(),revocation_endpoint:ne.optional(),revocation_endpoint_auth_methods_supported:m(a()).optional(),revocation_endpoint_auth_signing_alg_values_supported:m(a()).optional(),introspection_endpoint:a().optional(),introspection_endpoint_auth_methods_supported:m(a()).optional(),introspection_endpoint_auth_signing_alg_values_supported:m(a()).optional(),code_challenge_methods_supported:m(a()).optional(),client_id_metadata_document_supported:U().optional()}),sd=X({issuer:a(),authorization_endpoint:ne,token_endpoint:ne,userinfo_endpoint:ne.optional(),jwks_uri:ne,registration_endpoint:ne.optional(),scopes_supported:m(a()).optional(),response_types_supported:m(a()),response_modes_supported:m(a()).optional(),grant_types_supported:m(a()).optional(),acr_values_supported:m(a()).optional(),subject_types_supported:m(a()),id_token_signing_alg_values_supported:m(a()),id_token_encryption_alg_values_supported:m(a()).optional(),id_token_encryption_enc_values_supported:m(a()).optional(),userinfo_signing_alg_values_supported:m(a()).optional(),userinfo_encryption_alg_values_supported:m(a()).optional(),userinfo_encryption_enc_values_supported:m(a()).optional(),request_object_signing_alg_values_supported:m(a()).optional(),request_object_encryption_alg_values_supported:m(a()).optional(),request_object_encryption_enc_values_supported:m(a()).optional(),token_endpoint_auth_methods_supported:m(a()).optional(),token_endpoint_auth_signing_alg_values_supported:m(a()).optional(),display_values_supported:m(a()).optional(),claim_types_supported:m(a()).optional(),claims_supported:m(a()).optional(),service_documentation:a().optional(),claims_locales_supported:m(a()).optional(),ui_locales_supported:m(a()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:ne.optional(),op_tos_uri:ne.optional(),client_id_metadata_document_supported:U().optional()}),Ga=h({...sd.shape,...So.pick({code_challenge_methods_supported:!0}).shape}),Ha=h({access_token:a(),id_token:a().optional(),token_type:a(),expires_in:Qt.number().optional(),scope:a().optional(),refresh_token:a().optional()}).strip(),Ka=h({error:a(),error_description:a().optional(),error_uri:a().optional()}),Wa=ne.optional().or(y("").transform(()=>{})),ad=h({redirect_uris:m(ne),token_endpoint_auth_method:a().optional(),grant_types:m(a()).optional(),response_types:m(a()).optional(),client_name:a().optional(),client_uri:ne.optional(),logo_uri:Wa,scope:a().optional(),contacts:m(a()).optional(),tos_uri:Wa,policy_uri:a().optional(),jwks_uri:ne.optional(),jwks:na().optional(),software_id:a().optional(),software_version:a().optional(),software_statement:a().optional()}).strip(),cd=h({client_id:a(),client_secret:a().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional()}).strip(),Ya=ad.merge(cd),ah=h({error:a(),error_description:a().optional()}).strip(),ch=h({token:a(),token_type_hint:a().optional()}).strip();function Xa(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Qa({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var J=class extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},zt=class extends J{};zt.errorCode="invalid_request";var Te=class extends J{};Te.errorCode="invalid_client";var Oe=class extends J{};Oe.errorCode="invalid_grant";var Ce=class extends J{};Ce.errorCode="unauthorized_client";var xt=class extends J{};xt.errorCode="unsupported_grant_type";var vt=class extends J{};vt.errorCode="invalid_scope";var yt=class extends J{};yt.errorCode="access_denied";var be=class extends J{};be.errorCode="server_error";var wt=class extends J{};wt.errorCode="temporarily_unavailable";var bt=class extends J{};bt.errorCode="unsupported_response_type";var St=class extends J{};St.errorCode="unsupported_token_type";var $t=class extends J{};$t.errorCode="invalid_token";var kt=class extends J{};kt.errorCode="method_not_allowed";var Rt=class extends J{};Rt.errorCode="too_many_requests";var Ee=class extends J{};Ee.errorCode="invalid_client_metadata";var Pt=class extends J{};Pt.errorCode="insufficient_scope";var Zt=class extends J{};Zt.errorCode="invalid_target";var ec={[zt.errorCode]:zt,[Te.errorCode]:Te,[Oe.errorCode]:Oe,[Ce.errorCode]:Ce,[xt.errorCode]:xt,[vt.errorCode]:vt,[yt.errorCode]:yt,[be.errorCode]:be,[wt.errorCode]:wt,[bt.errorCode]:bt,[St.errorCode]:St,[$t.errorCode]:$t,[kt.errorCode]:kt,[Rt.errorCode]:Rt,[Ee.errorCode]:Ee,[Pt.errorCode]:Pt,[Zt.errorCode]:Zt};var Se=class extends Error{constructor(t){super(t??"Unauthorized")}};function ud(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var $o="code",ko="S256";function ld(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&ud(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function pd(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":dd(n,i,r);return;case"client_secret_post":md(n,i,o);return;case"none":fd(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function dd(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function md(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function fd(e,t){t.set("client_id",e)}async function rc(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ka.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:s}=o,c=ec[n]||be;return new c(i||"",s)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new be(n)}}async function It(e,t){try{return await Ro(e,t)}catch(r){if(r instanceof Te||r instanceof Ce)return await e.invalidateCredentials?.("all"),await Ro(e,t);if(r instanceof Oe)return await e.invalidateCredentials?.("tokens"),await Ro(e,t);throw r}}async function Ro(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let s=await e.discoveryState?.(),c,l,p,f=n;if(!f&&s?.resourceMetadataUrl&&(f=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await nc(l,{fetchFn:i}),!c)try{c=await oc(t,{resourceMetadataUrl:f},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let k=await yd(t,{resourceMetadataUrl:f,fetchFn:i});l=k.authorizationServerUrl,p=k.authorizationServerMetadata,c=k.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let g=await gd(t,e,c),x=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,_=await Promise.resolve(e.clientInformation());if(!_){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let k=p?.client_id_metadata_document_supported===!0,T=e.clientMetadataUrl;if(T&&!hd(T))throw new Ee(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${T}`);if(k&&T)_={client_id:T},await e.saveClientInformation?.(_);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let z=await kd(l,{metadata:p,clientMetadata:e.clientMetadata,scope:x,fetchFn:i});await e.saveClientInformation(z),_=z}}let S=!e.redirectUrl;if(r!==void 0||S){let k=await $d(e,l,{metadata:p,resource:g,authorizationCode:r,fetchFn:i});return await e.saveTokens(k),"AUTHORIZED"}let R=await e.tokens();if(R?.refresh_token)try{let k=await Sd(l,{metadata:p,clientInformation:_,refreshToken:R.refresh_token,resource:g,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(k),"AUTHORIZED"}catch(k){if(!(!(k instanceof J)||k instanceof be))throw k}let ee=e.state?await e.state():void 0,{authorizationUrl:H,codeVerifier:A}=await wd(l,{metadata:p,clientInformation:_,state:ee,redirectUrl:e.redirectUrl,scope:x,resource:g});return await e.saveCodeVerifier(A),await e.redirectToAuthorization(H),"REDIRECT"}function hd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function gd(e,t,r){let o=Xa(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Qa({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function Zo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Po(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=Po(e,"scope")||void 0,c=Po(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}function Po(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function oc(e,t,r=fetch){let o=await xd(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Ja.parse(await o.json())}async function Io(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Io(e,void 0,r):void 0;throw o}}function _d(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tc(e,t,r=fetch){return await Io(e,{"MCP-Protocol-Version":t},r)}function zd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function xd(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??mo,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=_d(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let c=await tc(s,i,r);if(!o?.metadataUrl&&zd(c,n.pathname)){let l=new URL(`/.well-known/${t}`,n);c=await tc(l,i,r)}return c}function vd(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function nc(e,{fetchFn:t=fetch,protocolVersion:r=mo}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=vd(e);for(let{url:i,type:s}of n){let c=await Io(i,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?So.parse(await c.json()):Ga.parse(await c.json())}}}async function yd(e,t){let r,o;try{r=await oc(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let n=await nc(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}async function wd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes($o))throw new Error(`Incompatible auth server: does not support response type ${$o}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ko))throw new Error(`Incompatible auth server: does not support code challenge method ${ko}`)}else c=new URL("/authorize",e);let l=await bo(),p=l.code_verifier,f=l.code_challenge;return c.searchParams.set("response_type",$o),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",ko),c.searchParams.set("redirect_uri",String(o)),i&&c.searchParams.set("state",i),n&&c.searchParams.set("scope",n),n?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}function bd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function ic(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),n)await n(l,r,c,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],g=ld(o,f);pd(g,o,l,r)}let p=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!p.ok)throw await rc(p);return Ha.parse(await p.json())}async function Sd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await ic(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:n,fetchFn:s});return{refresh_token:o,...l}}async function $d(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=bd(n,p,e.redirectUrl)}let l=await e.clientInformation();return ic(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function kd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await rc(s);return Ya.parse(await s.json())}var Tt=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},sc=10,Rd=13,Ae=32;function To(e){}function uc(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=To,onError:r=To,onRetry:o=To,onComment:n,maxBufferSize:i}=e,s=[],c=0,l=!0,p,f="",g=0,x,_=!1;function S(v){if(_)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),s.length===0){let D=ee(v);D!==""&&(s.push(D),c=D.length),R();return}if(v.indexOf(`
|
|
33
|
-
`)===-1&&
|
|
34
|
-
`,
|
|
35
|
-
`,
|
|
36
|
-
`,
|
|
37
|
-
${
|
|
38
|
-
`,
|
|
39
|
-
`,
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
`),o=
|
|
30
|
+
path: iss.path ? [${Te(A)}, ...iss.path] : [${Te(A)}]
|
|
31
|
+
})));`),z.write(`newResult[${Te(A)}] = ${$}.value`)}z.write("payload.value = newResult;"),z.write("return payload;");let G=z.compile();return(A,$)=>G(_,A,$)},n,i=Ve,s=!Mt.jitless,l=s&&Zr.value,p=t.catchall,h;e._zod.parse=(_,z)=>{h??(h=r.value);let m=_.value;if(!i(m))return _.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),_;let k=[];if(s&&l&&z?.async===!1&&z.jitless!==!0)n||(n=o(t.shape)),_=n(_,z);else{_.value={};let $=h.shape;for(let O of h.keys){let y=$[O],x=y._zod.run({value:m[O],issues:[]},z),S=y._zod.optin==="optional"&&y._zod.optout==="optional";x instanceof Promise?k.push(x.then(D=>S?ri(D,_,O,m):Ht(D,_,O))):S?ri(x,_,O,m):Ht(x,_,O)}}if(!p)return k.length?Promise.all(k).then(()=>_):_;let P=[],ee=h.keySet,G=p._zod,A=G.def.type;for(let $ of Object.keys(m)){if(ee.has($))continue;if(A==="never"){P.push($);continue}let O=G.run({value:m[$],issues:[]},z);O instanceof Promise?k.push(O.then(y=>Ht(y,_,$))):Ht(O,_,$)}return P.length&&_.issues.push({code:"unrecognized_keys",keys:P,input:m,inst:e}),k.length?Promise.all(k).then(()=>_):_}});function oi(e,t,r,o){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(n=>n.issues.map(i=>_e(i,o,le())))}),t}var Jr=u("$ZodUnion",(e,t)=>{C.init(e,t),N(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),N(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),N(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),N(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>lt(o.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1,i=[];for(let s of t.options){let c=s._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),n=!0;else{if(c.issues.length===0)return c;i.push(c)}}return n?Promise.all(i).then(s=>oi(s,r,e,o)):oi(i,r,e,o)}}),qi=u("$ZodDiscriminatedUnion",(e,t)=>{Jr.init(e,t);let r=e._zod.parse;N(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,l]of Object.entries(s)){n[c]||(n[c]=new Set);for(let p of l)n[c].add(p)}}return n});let o=ct(()=>{let n=t.options,i=new Map;for(let s of n){let c=s._zod.propValues[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of c){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!Ve(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let c=o.value.get(s?.[t.discriminator]);return c?c._zod.run(n,i):t.unionFallback?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),n)}}),Bi=u("$ZodIntersection",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,p])=>ni(r,l,p)):ni(r,i,s)}});function Br(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(qe(e)&&qe(t)){let r=Object.keys(t),o=Object.keys(e).filter(i=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=Br(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=Br(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ni(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ze(e))return e;let o=Br(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Wi=u("$ZodRecord",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!qe(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let p=t.valueType._zod.run({value:n[l],issues:[]},o);p instanceof Promise?i.push(p.then(h=>{h.issues.length&&r.issues.push(...ze(l,h.issues)),r.value[l]=h.value})):(p.issues.length&&r.issues.push(...ze(l,p.issues)),r.value[l]=p.value)}let c;for(let l in n)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:c})}else{r.value={};for(let s of Reflect.ownKeys(n)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(p=>_e(p,o,le())),input:s,path:[s],inst:e}),r.value[c.value]=c.value;continue}let l=t.valueType._zod.run({value:n[s],issues:[]},o);l instanceof Promise?i.push(l.then(p=>{p.issues.length&&r.issues.push(...ze(s,p.issues)),r.value[c.value]=p.value})):(l.issues.length&&r.issues.push(...ze(s,l.issues)),r.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Ji=u("$ZodEnum",(e,t)=>{C.init(e,t);let r=Rr(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(o=>Or.has(typeof o)).map(o=>typeof o=="string"?ke(o):o.toString()).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;return e._zod.values.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Hi=u("$ZodLiteral",(e,t)=>{C.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ke(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}});var Gi=u("$ZodTransform",(e,t)=>{C.init(e,t),e._zod.parse=(r,o)=>{let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(s=>(r.value=s,r));if(n instanceof Promise)throw new ve;return r.value=n,r}}),Ki=u("$ZodOptional",(e,t)=>{C.init(e,t),e._zod.optin="optional",e._zod.optout="optional",N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${lt(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,o):r.value===void 0?r:t.innerType._zod.run(r,o)}),Yi=u("$ZodNullable",(e,t)=>{C.init(e,t),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${lt(r.source)}|null)$`):void 0}),N(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)}),Xi=u("$ZodDefault",(e,t)=>{C.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>ii(i,t)):ii(n,t)}});function ii(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Qi=u("$ZodPrefault",(e,t)=>{C.init(e,t),e._zod.optin="optional",N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,o))}),es=u("$ZodNonOptional",(e,t)=>{C.init(e,t),N(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>si(i,e)):si(n,e)}});function si(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var ts=u("$ZodCatch",(e,t)=>{C.init(e,t),e._zod.optin="optional",N(e._zod,"optout",()=>t.innerType._zod.optout),N(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>_e(s,o,le()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(i=>_e(i,o,le()))},input:r.value}),r.issues=[]),r)}});var rs=u("$ZodPipe",(e,t)=>{C.init(e,t),N(e._zod,"values",()=>t.in._zod.values),N(e._zod,"optin",()=>t.in._zod.optin),N(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,o)=>{let n=t.in._zod.run(r,o);return n instanceof Promise?n.then(i=>ai(i,t,o)):ai(n,t,o)}});function ai(e,t,r){return Ze(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var os=u("$ZodReadonly",(e,t)=>{C.init(e,t),N(e._zod,"propValues",()=>t.innerType._zod.propValues),N(e._zod,"values",()=>t.innerType._zod.values),N(e._zod,"optin",()=>t.innerType._zod.optin),N(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(ci):ci(n)}});function ci(e){return e.value=Object.freeze(e.value),e}var ns=u("$ZodCustom",(e,t)=>{se.init(e,t),C.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=r=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(i=>ui(i,r,o,e));ui(n,r,o,e)}});function ui(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),t.issues.push(Ar(n))}}var yu=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},vu=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${yu(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${qt(o.values[0])}`:`Invalid option: expected one of ${Ft(o.values,"|")}`;case"too_big":{let n=o.inclusive?"<=":"<",i=t(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{let n=o.inclusive?">=":">",i=t(o.origin);return i?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{let n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Ft(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function is(){return{localeError:vu()}}var bu=Symbol("ZodOutput"),wu=Symbol("ZodInput"),Hr=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let o=r[0];if(this._map.set(t,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let o={...this.get(r)??{}};return delete o.id,{...o,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function ss(){return new Hr}var Be=ss();function as(e,t){return new e({type:"string",...w(t)})}function cs(e,t){return new e({type:"string",coerce:!0,...w(t)})}function us(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function Gr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function ls(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function ps(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function ds(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function ms(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function Kr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function fs(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function hs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function gs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function _s(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function xs(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function zs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function ys(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function vs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function bs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function ws(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function Ss(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function $s(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function ks(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function Rs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function Ps(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}function Is(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function Ts(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function Zs(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function Os(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function Es(e,t){return new e({type:"number",checks:[],...w(t)})}function Cs(e,t){return new e({type:"number",coerce:!0,checks:[],...w(t)})}function As(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function Us(e,t){return new e({type:"boolean",...w(t)})}function Ns(e,t){return new e({type:"boolean",coerce:!0,...w(t)})}function js(e,t){return new e({type:"bigint",coerce:!0,...w(t)})}function Ls(e,t){return new e({type:"null",...w(t)})}function Ds(e){return new e({type:"any"})}function Ms(e){return new e({type:"unknown"})}function Fs(e,t){return new e({type:"never",...w(t)})}function Vs(e,t){return new e({type:"date",coerce:!0,...w(t)})}function We(e,t){return new Vr({check:"less_than",...w(t),value:e,inclusive:!1})}function be(e,t){return new Vr({check:"less_than",...w(t),value:e,inclusive:!0})}function Je(e,t){return new qr({check:"greater_than",...w(t),value:e,inclusive:!1})}function xe(e,t){return new qr({check:"greater_than",...w(t),value:e,inclusive:!0})}function mt(e,t){return new Mn({check:"multiple_of",...w(t),value:e})}function Kt(e,t){return new Vn({check:"max_length",...w(t),maximum:e})}function He(e,t){return new qn({check:"min_length",...w(t),minimum:e})}function Yt(e,t){return new Bn({check:"length_equals",...w(t),length:e})}function Yr(e,t){return new Wn({check:"string_format",format:"regex",...w(t),pattern:e})}function Xr(e){return new Jn({check:"string_format",format:"lowercase",...w(e)})}function Qr(e){return new Hn({check:"string_format",format:"uppercase",...w(e)})}function eo(e,t){return new Gn({check:"string_format",format:"includes",...w(t),includes:e})}function to(e,t){return new Kn({check:"string_format",format:"starts_with",...w(t),prefix:e})}function ro(e,t){return new Yn({check:"string_format",format:"ends_with",...w(t),suffix:e})}function Oe(e){return new Xn({check:"overwrite",tx:e})}function oo(e){return Oe(t=>t.normalize(e))}function no(){return Oe(e=>e.trim())}function io(){return Oe(e=>e.toLowerCase())}function so(){return Oe(e=>e.toUpperCase())}function qs(e,t,r){return new e({type:"array",element:t,...w(r)})}function Bs(e,t,r){let o=w(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ws(e,t,r){return new e({type:"custom",check:"custom",fn:t,...w(r)})}var ft={};zr(ft,{ZodISODate:()=>Hs,ZodISODateTime:()=>Js,ZodISODuration:()=>Ks,ZodISOTime:()=>Gs,date:()=>co,datetime:()=>ao,duration:()=>lo,time:()=>uo});var Js=u("ZodISODateTime",(e,t)=>{vi.init(e,t),q.init(e,t)});function ao(e){return Is(Js,e)}var Hs=u("ZodISODate",(e,t)=>{bi.init(e,t),q.init(e,t)});function co(e){return Ts(Hs,e)}var Gs=u("ZodISOTime",(e,t)=>{wi.init(e,t),q.init(e,t)});function uo(e){return Zs(Gs,e)}var Ks=u("ZodISODuration",(e,t)=>{Si.init(e,t),q.init(e,t)});function lo(e){return Os(Ks,e)}var Xs=(e,t)=>{Bt.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>jr(e,r)},flatten:{value:r=>Nr(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},lf=u("ZodError",Xs),ht=u("ZodError",Xs,{Parent:Error});var Qs=sn(ht),ea=an(ht),ta=Lr(ht),ra=Dr(ht);var j=u("ZodType",(e,t)=>(C.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),e.clone=(r,o)=>ge(e,r,o),e.brand=()=>e,e.register=(r,o)=>(r.add(e,o),e),e.parse=(r,o)=>Qs(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>ta(e,r,o),e.parseAsync=async(r,o)=>ea(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>ra(e,r,o),e.spa=e.safeParseAsync,e.refine=(r,o)=>e.check(_l(r,o)),e.superRefine=r=>e.check(xl(r)),e.overwrite=r=>e.check(Oe(r)),e.optional=()=>W(e),e.nullable=()=>ia(e),e.nullish=()=>W(ia(e)),e.nonoptional=r=>ll(e,r),e.array=()=>f(e),e.or=r=>F([e,r]),e.and=r=>er(e,r),e.transform=r=>mo(e,ha(r)),e.default=r=>al(e,r),e.prefault=r=>ul(e,r),e.catch=r=>dl(e,r),e.pipe=r=>mo(e,r),e.readonly=()=>hl(e),e.describe=r=>{let o=e.clone();return Be.add(o,{description:r}),o},Object.defineProperty(e,"description",{get(){return Be.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Be.get(e);let o=e.clone();return Be.add(o,r[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),sa=u("_ZodString",(e,t)=>{Gt.init(e,t),j.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...o)=>e.check(Yr(...o)),e.includes=(...o)=>e.check(eo(...o)),e.startsWith=(...o)=>e.check(to(...o)),e.endsWith=(...o)=>e.check(ro(...o)),e.min=(...o)=>e.check(He(...o)),e.max=(...o)=>e.check(Kt(...o)),e.length=(...o)=>e.check(Yt(...o)),e.nonempty=(...o)=>e.check(He(1,...o)),e.lowercase=o=>e.check(Xr(o)),e.uppercase=o=>e.check(Qr(o)),e.trim=()=>e.check(no()),e.normalize=(...o)=>e.check(oo(...o)),e.toLowerCase=()=>e.check(io()),e.toUpperCase=()=>e.check(so())}),fo=u("ZodString",(e,t)=>{Gt.init(e,t),sa.init(e,t),e.email=r=>e.check(us(Zu,r)),e.url=r=>e.check(Kr(aa,r)),e.jwt=r=>e.check(Ps(Wu,r)),e.emoji=r=>e.check(fs(Ou,r)),e.guid=r=>e.check(Gr(oa,r)),e.uuid=r=>e.check(ls(Xt,r)),e.uuidv4=r=>e.check(ps(Xt,r)),e.uuidv6=r=>e.check(ds(Xt,r)),e.uuidv7=r=>e.check(ms(Xt,r)),e.nanoid=r=>e.check(hs(Eu,r)),e.guid=r=>e.check(Gr(oa,r)),e.cuid=r=>e.check(gs(Cu,r)),e.cuid2=r=>e.check(_s(Au,r)),e.ulid=r=>e.check(xs(Uu,r)),e.base64=r=>e.check($s(Vu,r)),e.base64url=r=>e.check(ks(qu,r)),e.xid=r=>e.check(zs(Nu,r)),e.ksuid=r=>e.check(ys(ju,r)),e.ipv4=r=>e.check(vs(Lu,r)),e.ipv6=r=>e.check(bs(Du,r)),e.cidrv4=r=>e.check(ws(Mu,r)),e.cidrv6=r=>e.check(Ss(Fu,r)),e.e164=r=>e.check(Rs(Bu,r)),e.datetime=r=>e.check(ao(r)),e.date=r=>e.check(co(r)),e.time=r=>e.check(uo(r)),e.duration=r=>e.check(lo(r))});function a(e){return as(fo,e)}var q=u("ZodStringFormat",(e,t)=>{M.init(e,t),sa.init(e,t)}),Zu=u("ZodEmail",(e,t)=>{di.init(e,t),q.init(e,t)});var oa=u("ZodGUID",(e,t)=>{li.init(e,t),q.init(e,t)});var Xt=u("ZodUUID",(e,t)=>{pi.init(e,t),q.init(e,t)});var aa=u("ZodURL",(e,t)=>{mi.init(e,t),q.init(e,t)});function ca(e){return Kr(aa,e)}var Ou=u("ZodEmoji",(e,t)=>{fi.init(e,t),q.init(e,t)});var Eu=u("ZodNanoID",(e,t)=>{hi.init(e,t),q.init(e,t)});var Cu=u("ZodCUID",(e,t)=>{gi.init(e,t),q.init(e,t)});var Au=u("ZodCUID2",(e,t)=>{_i.init(e,t),q.init(e,t)});var Uu=u("ZodULID",(e,t)=>{xi.init(e,t),q.init(e,t)});var Nu=u("ZodXID",(e,t)=>{zi.init(e,t),q.init(e,t)});var ju=u("ZodKSUID",(e,t)=>{yi.init(e,t),q.init(e,t)});var Lu=u("ZodIPv4",(e,t)=>{$i.init(e,t),q.init(e,t)});var Du=u("ZodIPv6",(e,t)=>{ki.init(e,t),q.init(e,t)});var Mu=u("ZodCIDRv4",(e,t)=>{Ri.init(e,t),q.init(e,t)});var Fu=u("ZodCIDRv6",(e,t)=>{Pi.init(e,t),q.init(e,t)});var Vu=u("ZodBase64",(e,t)=>{Ti.init(e,t),q.init(e,t)});var qu=u("ZodBase64URL",(e,t)=>{Zi.init(e,t),q.init(e,t)});var Bu=u("ZodE164",(e,t)=>{Oi.init(e,t),q.init(e,t)});var Wu=u("ZodJWT",(e,t)=>{Ei.init(e,t),q.init(e,t)});var Qt=u("ZodNumber",(e,t)=>{Wr.init(e,t),j.init(e,t),e.gt=(o,n)=>e.check(Je(o,n)),e.gte=(o,n)=>e.check(xe(o,n)),e.min=(o,n)=>e.check(xe(o,n)),e.lt=(o,n)=>e.check(We(o,n)),e.lte=(o,n)=>e.check(be(o,n)),e.max=(o,n)=>e.check(be(o,n)),e.int=o=>e.check(na(o)),e.safe=o=>e.check(na(o)),e.positive=o=>e.check(Je(0,o)),e.nonnegative=o=>e.check(xe(0,o)),e.negative=o=>e.check(We(0,o)),e.nonpositive=o=>e.check(be(0,o)),e.multipleOf=(o,n)=>e.check(mt(o,n)),e.step=(o,n)=>e.check(mt(o,n)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function T(e){return Es(Qt,e)}var Ju=u("ZodNumberFormat",(e,t)=>{Ci.init(e,t),Qt.init(e,t)});function na(e){return As(Ju,e)}var ho=u("ZodBoolean",(e,t)=>{Ai.init(e,t),j.init(e,t)});function U(e){return Us(ho,e)}var ua=u("ZodBigInt",(e,t)=>{Ui.init(e,t),j.init(e,t),e.gte=(o,n)=>e.check(xe(o,n)),e.min=(o,n)=>e.check(xe(o,n)),e.gt=(o,n)=>e.check(Je(o,n)),e.gte=(o,n)=>e.check(xe(o,n)),e.min=(o,n)=>e.check(xe(o,n)),e.lt=(o,n)=>e.check(We(o,n)),e.lte=(o,n)=>e.check(be(o,n)),e.max=(o,n)=>e.check(be(o,n)),e.positive=o=>e.check(Je(BigInt(0),o)),e.negative=o=>e.check(We(BigInt(0),o)),e.nonpositive=o=>e.check(be(BigInt(0),o)),e.nonnegative=o=>e.check(xe(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(mt(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});var Hu=u("ZodNull",(e,t)=>{Ni.init(e,t),j.init(e,t)});function la(e){return Ls(Hu,e)}var Gu=u("ZodAny",(e,t)=>{ji.init(e,t),j.init(e,t)});function pa(){return Ds(Gu)}var Ku=u("ZodUnknown",(e,t)=>{Li.init(e,t),j.init(e,t)});function B(){return Ms(Ku)}var Yu=u("ZodNever",(e,t)=>{Di.init(e,t),j.init(e,t)});function Xu(e){return Fs(Yu,e)}var da=u("ZodDate",(e,t)=>{Mi.init(e,t),j.init(e,t),e.min=(o,n)=>e.check(xe(o,n)),e.max=(o,n)=>e.check(be(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});var Qu=u("ZodArray",(e,t)=>{Fi.init(e,t),j.init(e,t),e.element=t.element,e.min=(r,o)=>e.check(He(r,o)),e.nonempty=r=>e.check(He(1,r)),e.max=(r,o)=>e.check(Kt(r,o)),e.length=(r,o)=>e.check(Yt(r,o)),e.unwrap=()=>e.element});function f(e,t){return qs(Qu,e,t)}var ma=u("ZodObject",(e,t)=>{Vi.init(e,t),j.init(e,t),Z.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ce(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:B()}),e.loose=()=>e.clone({...e._zod.def,catchall:B()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Z.extend(e,r),e.merge=r=>Z.merge(e,r),e.pick=r=>Z.pick(e,r),e.omit=r=>Z.omit(e,r),e.partial=(...r)=>Z.partial(ga,e,r[0]),e.required=(...r)=>Z.required(_a,e,r[0])});function g(e,t){let r={type:"object",get shape(){return Z.assignProp(this,"shape",{...e}),this.shape},...Z.normalizeParams(t)};return new ma(r)}function X(e,t){return new ma({type:"object",get shape(){return Z.assignProp(this,"shape",{...e}),this.shape},catchall:B(),...Z.normalizeParams(t)})}var fa=u("ZodUnion",(e,t)=>{Jr.init(e,t),j.init(e,t),e.options=t.options});function F(e,t){return new fa({type:"union",options:e,...Z.normalizeParams(t)})}var el=u("ZodDiscriminatedUnion",(e,t)=>{fa.init(e,t),qi.init(e,t)});function go(e,t,r){return new el({type:"union",options:t,discriminator:e,...Z.normalizeParams(r)})}var tl=u("ZodIntersection",(e,t)=>{Bi.init(e,t),j.init(e,t)});function er(e,t){return new tl({type:"intersection",left:e,right:t})}var rl=u("ZodRecord",(e,t)=>{Wi.init(e,t),j.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,r){return new rl({type:"record",keyType:e,valueType:t,...Z.normalizeParams(r)})}var po=u("ZodEnum",(e,t)=>{Ji.init(e,t),j.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new po({...t,checks:[],...Z.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new po({...t,checks:[],...Z.normalizeParams(n),entries:i})}});function ce(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new po({type:"enum",entries:r,...Z.normalizeParams(t)})}var ol=u("ZodLiteral",(e,t)=>{Hi.init(e,t),j.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function v(e,t){return new ol({type:"literal",values:Array.isArray(e)?e:[e],...Z.normalizeParams(t)})}var nl=u("ZodTransform",(e,t)=>{Gi.init(e,t),j.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(Z.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(Z.issue(s))}};let n=t.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function ha(e){return new nl({type:"transform",transform:e})}var ga=u("ZodOptional",(e,t)=>{Ki.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W(e){return new ga({type:"optional",innerType:e})}var il=u("ZodNullable",(e,t)=>{Yi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ia(e){return new il({type:"nullable",innerType:e})}var sl=u("ZodDefault",(e,t)=>{Xi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function al(e,t){return new sl({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var cl=u("ZodPrefault",(e,t)=>{Qi.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ul(e,t){return new cl({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var _a=u("ZodNonOptional",(e,t)=>{es.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ll(e,t){return new _a({type:"nonoptional",innerType:e,...Z.normalizeParams(t)})}var pl=u("ZodCatch",(e,t)=>{ts.init(e,t),j.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dl(e,t){return new pl({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var ml=u("ZodPipe",(e,t)=>{rs.init(e,t),j.init(e,t),e.in=t.in,e.out=t.out});function mo(e,t){return new ml({type:"pipe",in:e,out:t})}var fl=u("ZodReadonly",(e,t)=>{os.init(e,t),j.init(e,t)});function hl(e){return new fl({type:"readonly",innerType:e})}var xa=u("ZodCustom",(e,t)=>{ns.init(e,t),j.init(e,t)});function gl(e){let t=new se({check:"custom"});return t._zod.check=e,t}function za(e,t){return Bs(xa,e??(()=>!0),t)}function _l(e,t={}){return Ws(xa,e,t)}function xl(e){let t=gl(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Z.issue(o,r.value,t._zod.def));else{let n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(Z.issue(n))}},e(r.value,r)));return t}function _o(e,t){return mo(ha(e),t)}var ya={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var tr={};zr(tr,{bigint:()=>bl,boolean:()=>vl,date:()=>wl,number:()=>yl,string:()=>zl});function zl(e){return cs(fo,e)}function yl(e){return Cs(Qt,e)}function vl(e){return Ns(ho,e)}function bl(e){return js(ua,e)}function wl(e){return Vs(da,e)}le(is());var xo="2025-11-25";var $l="io.modelcontextprotocol/related-task",or="2.0",Q=za(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ba=F([a(),T().int()]),wa=a(),nh=X({ttl:T().optional(),pollInterval:T().optional()}),kl=g({ttl:T().optional()}),Rl=g({taskId:a()}),zo=X({progressToken:ba.optional(),[$l]:Rl.optional()}),pe=g({_meta:zo.optional()}),nr=pe.extend({task:kl.optional()});var re=g({method:a(),params:pe.loose().optional()}),me=g({_meta:zo.optional()}),fe=g({method:a(),params:me.loose().optional()}),oe=X({_meta:zo.optional()}),ir=F([a(),T().int()]),Sa=g({jsonrpc:v(or),id:ir,...re.shape}).strict(),$a=e=>Sa.safeParse(e).success,Pl=g({jsonrpc:v(or),...fe.shape}).strict();var yo=g({jsonrpc:v(or),id:ir,result:oe}).strict(),ka=e=>yo.safeParse(e).success;var va;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(va||(va={}));var Ra=g({jsonrpc:v(or),id:ir.optional(),error:g({code:T().int(),message:a(),data:B().optional()})}).strict();var Ye=F([Sa,Pl,yo,Ra]),ih=F([yo,Ra]),Pa=oe.strict(),Il=me.extend({requestId:ir.optional(),reason:a().optional()}),Ia=fe.extend({method:v("notifications/cancelled"),params:Il}),Tl=g({src:a(),mimeType:a().optional(),sizes:f(a()).optional(),theme:ce(["light","dark"]).optional()}),gt=g({icons:f(Tl).optional()}),Ke=g({name:a(),title:a().optional()}),Ta=Ke.extend({...Ke.shape,...gt.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),Zl=er(g({applyDefaults:U().optional()}),L(a(),B())),Ol=_o(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,er(g({form:Zl.optional(),url:Q.optional()}),L(a(),B()).optional())),El=X({list:Q.optional(),cancel:Q.optional(),requests:X({sampling:X({createMessage:Q.optional()}).optional(),elicitation:X({create:Q.optional()}).optional()}).optional()}),Cl=X({list:Q.optional(),cancel:Q.optional(),requests:X({tools:X({call:Q.optional()}).optional()}).optional()}),Al=g({experimental:L(a(),Q).optional(),sampling:g({context:Q.optional(),tools:Q.optional()}).optional(),elicitation:Ol.optional(),roots:g({listChanged:U().optional()}).optional(),tasks:El.optional(),extensions:L(a(),Q).optional()}),Ul=pe.extend({protocolVersion:a(),capabilities:Al,clientInfo:Ta}),Nl=re.extend({method:v("initialize"),params:Ul});var jl=g({experimental:L(a(),Q).optional(),logging:Q.optional(),completions:Q.optional(),prompts:g({listChanged:U().optional()}).optional(),resources:g({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:g({listChanged:U().optional()}).optional(),tasks:Cl.optional(),extensions:L(a(),Q).optional()}),Ll=oe.extend({protocolVersion:a(),capabilities:jl,serverInfo:Ta,instructions:a().optional()}),Za=fe.extend({method:v("notifications/initialized"),params:me.optional()}),Oa=e=>Za.safeParse(e).success,Ea=re.extend({method:v("ping"),params:pe.optional()}),Dl=g({progress:T(),total:W(T()),message:W(a())}),Ml=g({...me.shape,...Dl.shape,progressToken:ba}),Ca=fe.extend({method:v("notifications/progress"),params:Ml}),Fl=pe.extend({cursor:wa.optional()}),_t=re.extend({params:Fl.optional()}),xt=oe.extend({nextCursor:wa.optional()}),Vl=ce(["working","input_required","completed","failed","cancelled"]),zt=g({taskId:a(),status:Vl,ttl:F([T(),la()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:W(T()),statusMessage:W(a())}),Aa=oe.extend({task:zt}),ql=me.merge(zt),Ua=fe.extend({method:v("notifications/tasks/status"),params:ql}),Na=re.extend({method:v("tasks/get"),params:pe.extend({taskId:a()})}),ja=oe.merge(zt),La=re.extend({method:v("tasks/result"),params:pe.extend({taskId:a()})}),sh=oe.loose(),Da=_t.extend({method:v("tasks/list")}),Ma=xt.extend({tasks:f(zt)}),Fa=re.extend({method:v("tasks/cancel"),params:pe.extend({taskId:a()})}),ah=oe.merge(zt),Va=g({uri:a(),mimeType:W(a()),_meta:L(a(),B()).optional()}),qa=Va.extend({text:a()}),vo=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ba=Va.extend({blob:vo}),yt=ce(["user","assistant"]),Xe=g({audience:f(yt).optional(),priority:T().min(0).max(1).optional(),lastModified:ft.datetime({offset:!0}).optional()}),Wa=g({...Ke.shape,...gt.shape,uri:a(),description:W(a()),mimeType:W(a()),size:W(T()),annotations:Xe.optional(),_meta:W(X({}))}),Bl=g({...Ke.shape,...gt.shape,uriTemplate:a(),description:W(a()),mimeType:W(a()),annotations:Xe.optional(),_meta:W(X({}))}),Wl=_t.extend({method:v("resources/list")}),Jl=xt.extend({resources:f(Wa)}),Hl=_t.extend({method:v("resources/templates/list")}),Gl=xt.extend({resourceTemplates:f(Bl)}),bo=pe.extend({uri:a()}),Kl=bo,Yl=re.extend({method:v("resources/read"),params:Kl}),Xl=oe.extend({contents:f(F([qa,Ba]))}),Ql=fe.extend({method:v("notifications/resources/list_changed"),params:me.optional()}),ep=bo,tp=re.extend({method:v("resources/subscribe"),params:ep}),rp=bo,op=re.extend({method:v("resources/unsubscribe"),params:rp}),np=me.extend({uri:a()}),ip=fe.extend({method:v("notifications/resources/updated"),params:np}),sp=g({name:a(),description:W(a()),required:W(U())}),ap=g({...Ke.shape,...gt.shape,description:W(a()),arguments:W(f(sp)),_meta:W(X({}))}),cp=_t.extend({method:v("prompts/list")}),up=xt.extend({prompts:f(ap)}),lp=pe.extend({name:a(),arguments:L(a(),a()).optional()}),pp=re.extend({method:v("prompts/get"),params:lp}),wo=g({type:v("text"),text:a(),annotations:Xe.optional(),_meta:L(a(),B()).optional()}),So=g({type:v("image"),data:vo,mimeType:a(),annotations:Xe.optional(),_meta:L(a(),B()).optional()}),$o=g({type:v("audio"),data:vo,mimeType:a(),annotations:Xe.optional(),_meta:L(a(),B()).optional()}),dp=g({type:v("tool_use"),name:a(),id:a(),input:L(a(),B()),_meta:L(a(),B()).optional()}),mp=g({type:v("resource"),resource:F([qa,Ba]),annotations:Xe.optional(),_meta:L(a(),B()).optional()}),fp=Wa.extend({type:v("resource_link")}),ko=F([wo,So,$o,fp,mp]),hp=g({role:yt,content:ko}),gp=oe.extend({description:a().optional(),messages:f(hp)}),_p=fe.extend({method:v("notifications/prompts/list_changed"),params:me.optional()}),xp=g({title:a().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),zp=g({taskSupport:ce(["required","optional","forbidden"]).optional()}),Ja=g({...Ke.shape,...gt.shape,description:a().optional(),inputSchema:g({type:v("object"),properties:L(a(),Q).optional(),required:f(a()).optional()}).catchall(B()),outputSchema:g({type:v("object"),properties:L(a(),Q).optional(),required:f(a()).optional()}).catchall(B()).optional(),annotations:xp.optional(),execution:zp.optional(),_meta:L(a(),B()).optional()}),yp=_t.extend({method:v("tools/list")}),vp=xt.extend({tools:f(Ja)}),Ha=oe.extend({content:f(ko).default([]),structuredContent:L(a(),B()).optional(),isError:U().optional()}),ch=Ha.or(oe.extend({toolResult:B()})),bp=nr.extend({name:a(),arguments:L(a(),B()).optional()}),wp=re.extend({method:v("tools/call"),params:bp}),Sp=fe.extend({method:v("notifications/tools/list_changed"),params:me.optional()}),uh=g({autoRefresh:U().default(!0),debounceMs:T().int().nonnegative().default(300)}),Ga=ce(["debug","info","notice","warning","error","critical","alert","emergency"]),$p=pe.extend({level:Ga}),kp=re.extend({method:v("logging/setLevel"),params:$p}),Rp=me.extend({level:Ga,logger:a().optional(),data:B()}),Pp=fe.extend({method:v("notifications/message"),params:Rp}),Ip=g({name:a().optional()}),Tp=g({hints:f(Ip).optional(),costPriority:T().min(0).max(1).optional(),speedPriority:T().min(0).max(1).optional(),intelligencePriority:T().min(0).max(1).optional()}),Zp=g({mode:ce(["auto","required","none"]).optional()}),Op=g({type:v("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:f(ko).default([]),structuredContent:g({}).loose().optional(),isError:U().optional(),_meta:L(a(),B()).optional()}),Ep=go("type",[wo,So,$o]),rr=go("type",[wo,So,$o,dp,Op]),Cp=g({role:yt,content:F([rr,f(rr)]),_meta:L(a(),B()).optional()}),Ap=nr.extend({messages:f(Cp),modelPreferences:Tp.optional(),systemPrompt:a().optional(),includeContext:ce(["none","thisServer","allServers"]).optional(),temperature:T().optional(),maxTokens:T().int(),stopSequences:f(a()).optional(),metadata:Q.optional(),tools:f(Ja).optional(),toolChoice:Zp.optional()}),Up=re.extend({method:v("sampling/createMessage"),params:Ap}),Np=oe.extend({model:a(),stopReason:W(ce(["endTurn","stopSequence","maxTokens"]).or(a())),role:yt,content:Ep}),jp=oe.extend({model:a(),stopReason:W(ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:yt,content:F([rr,f(rr)])}),Lp=g({type:v("boolean"),title:a().optional(),description:a().optional(),default:U().optional()}),Dp=g({type:v("string"),title:a().optional(),description:a().optional(),minLength:T().optional(),maxLength:T().optional(),format:ce(["email","uri","date","date-time"]).optional(),default:a().optional()}),Mp=g({type:ce(["number","integer"]),title:a().optional(),description:a().optional(),minimum:T().optional(),maximum:T().optional(),default:T().optional()}),Fp=g({type:v("string"),title:a().optional(),description:a().optional(),enum:f(a()),default:a().optional()}),Vp=g({type:v("string"),title:a().optional(),description:a().optional(),oneOf:f(g({const:a(),title:a()})),default:a().optional()}),qp=g({type:v("string"),title:a().optional(),description:a().optional(),enum:f(a()),enumNames:f(a()).optional(),default:a().optional()}),Bp=F([Fp,Vp]),Wp=g({type:v("array"),title:a().optional(),description:a().optional(),minItems:T().optional(),maxItems:T().optional(),items:g({type:v("string"),enum:f(a())}),default:f(a()).optional()}),Jp=g({type:v("array"),title:a().optional(),description:a().optional(),minItems:T().optional(),maxItems:T().optional(),items:g({anyOf:f(g({const:a(),title:a()}))}),default:f(a()).optional()}),Hp=F([Wp,Jp]),Gp=F([qp,Bp,Hp]),Kp=F([Gp,Lp,Dp,Mp]),Yp=nr.extend({mode:v("form").optional(),message:a(),requestedSchema:g({type:v("object"),properties:L(a(),Kp),required:f(a()).optional()})}),Xp=nr.extend({mode:v("url"),message:a(),elicitationId:a(),url:a().url()}),Qp=F([Yp,Xp]),ed=re.extend({method:v("elicitation/create"),params:Qp}),td=me.extend({elicitationId:a()}),rd=fe.extend({method:v("notifications/elicitation/complete"),params:td}),od=oe.extend({action:ce(["accept","decline","cancel"]),content:_o(e=>e===null?void 0:e,L(a(),F([a(),T(),U(),f(a())])).optional())}),nd=g({type:v("ref/resource"),uri:a()});var id=g({type:v("ref/prompt"),name:a()}),sd=pe.extend({ref:F([id,nd]),argument:g({name:a(),value:a()}),context:g({arguments:L(a(),a()).optional()}).optional()}),ad=re.extend({method:v("completion/complete"),params:sd});var cd=oe.extend({completion:X({values:f(a()).max(100),total:W(T().int()),hasMore:W(U())})}),ud=g({uri:a().startsWith("file://"),name:a().optional(),_meta:L(a(),B()).optional()}),ld=re.extend({method:v("roots/list"),params:pe.optional()}),pd=oe.extend({roots:f(ud)}),dd=fe.extend({method:v("notifications/roots/list_changed"),params:me.optional()}),lh=F([Ea,Nl,ad,kp,pp,cp,Wl,Hl,Yl,tp,op,wp,yp,Na,La,Da,Fa]),ph=F([Ia,Ca,Za,dd,Ua]),dh=F([Pa,Np,jp,od,pd,ja,Ma,Aa]),mh=F([Ea,Up,ed,ld,Na,La,Da,Fa]),fh=F([Ia,Ca,Pp,ip,Ql,Sp,_p,Ua,rd]),hh=F([Pa,Ll,cd,gp,up,Jl,Gl,Xl,Ha,vp,ja,Ma,Aa]);var sr=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
32
|
+
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),md(r)}clear(){this._buffer=void 0}};function md(e){return Ye.parse(JSON.parse(e))}function Ka(e){return JSON.stringify(e)+`
|
|
33
|
+
`}var ar=class{constructor(t=Ya.stdin,r=Ya.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new sr,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let o=Ka(t);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};function cr(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Xa(e=fetch,t){return t?async(r,o)=>{let n={...t,...o,headers:o?.headers?{...cr(t.headers),...cr(o.headers)}:t.headers};return e(r,n)}:e}var Ro;Ro=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto);async function fd(e){return(await Ro).getRandomValues(new Uint8Array(e))}async function hd(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let n=await fd(e-o.length);for(let i of n)i<r&&(o+=t[i%t.length])}return o}async function gd(e){return await hd(e)}async function _d(e){let t=await(await Ro).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Po(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gd(e),r=await _d(t);return{code_verifier:t,code_challenge:r}}var ne=ca().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ya.custom,message:"URL must be parseable",fatal:!0}),Sr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ec=X({resource:a().url(),authorization_servers:f(ne).optional(),jwks_uri:a().url().optional(),scopes_supported:f(a()).optional(),bearer_methods_supported:f(a()).optional(),resource_signing_alg_values_supported:f(a()).optional(),resource_name:a().optional(),resource_documentation:a().optional(),resource_policy_uri:a().url().optional(),resource_tos_uri:a().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:f(a()).optional(),dpop_signing_alg_values_supported:f(a()).optional(),dpop_bound_access_tokens_required:U().optional()}),Io=X({issuer:a(),authorization_endpoint:ne,token_endpoint:ne,registration_endpoint:ne.optional(),scopes_supported:f(a()).optional(),response_types_supported:f(a()),response_modes_supported:f(a()).optional(),grant_types_supported:f(a()).optional(),token_endpoint_auth_methods_supported:f(a()).optional(),token_endpoint_auth_signing_alg_values_supported:f(a()).optional(),service_documentation:ne.optional(),revocation_endpoint:ne.optional(),revocation_endpoint_auth_methods_supported:f(a()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(a()).optional(),introspection_endpoint:a().optional(),introspection_endpoint_auth_methods_supported:f(a()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(a()).optional(),code_challenge_methods_supported:f(a()).optional(),client_id_metadata_document_supported:U().optional()}),xd=X({issuer:a(),authorization_endpoint:ne,token_endpoint:ne,userinfo_endpoint:ne.optional(),jwks_uri:ne,registration_endpoint:ne.optional(),scopes_supported:f(a()).optional(),response_types_supported:f(a()),response_modes_supported:f(a()).optional(),grant_types_supported:f(a()).optional(),acr_values_supported:f(a()).optional(),subject_types_supported:f(a()),id_token_signing_alg_values_supported:f(a()),id_token_encryption_alg_values_supported:f(a()).optional(),id_token_encryption_enc_values_supported:f(a()).optional(),userinfo_signing_alg_values_supported:f(a()).optional(),userinfo_encryption_alg_values_supported:f(a()).optional(),userinfo_encryption_enc_values_supported:f(a()).optional(),request_object_signing_alg_values_supported:f(a()).optional(),request_object_encryption_alg_values_supported:f(a()).optional(),request_object_encryption_enc_values_supported:f(a()).optional(),token_endpoint_auth_methods_supported:f(a()).optional(),token_endpoint_auth_signing_alg_values_supported:f(a()).optional(),display_values_supported:f(a()).optional(),claim_types_supported:f(a()).optional(),claims_supported:f(a()).optional(),service_documentation:a().optional(),claims_locales_supported:f(a()).optional(),ui_locales_supported:f(a()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:ne.optional(),op_tos_uri:ne.optional(),client_id_metadata_document_supported:U().optional()}),tc=g({...xd.shape,...Io.pick({code_challenge_methods_supported:!0}).shape}),rc=g({access_token:a(),id_token:a().optional(),token_type:a(),expires_in:tr.number().optional(),scope:a().optional(),refresh_token:a().optional()}).strip(),oc=g({error:a(),error_description:a().optional(),error_uri:a().optional()}),Qa=ne.optional().or(v("").transform(()=>{})),zd=g({redirect_uris:f(ne),token_endpoint_auth_method:a().optional(),grant_types:f(a()).optional(),response_types:f(a()).optional(),client_name:a().optional(),client_uri:ne.optional(),logo_uri:Qa,scope:a().optional(),contacts:f(a()).optional(),tos_uri:Qa,policy_uri:a().optional(),jwks_uri:ne.optional(),jwks:pa().optional(),software_id:a().optional(),software_version:a().optional(),software_statement:a().optional()}).strip(),yd=g({client_id:a(),client_secret:a().optional(),client_id_issued_at:T().optional(),client_secret_expires_at:T().optional()}).strip(),nc=zd.merge(yd),Sh=g({error:a(),error_description:a().optional()}).strip(),$h=g({token:a(),token_type_hint:a().optional()}).strip();function ic(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function sc({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var K=class extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},vt=class extends K{};vt.errorCode="invalid_request";var Ee=class extends K{};Ee.errorCode="invalid_client";var Ce=class extends K{};Ce.errorCode="invalid_grant";var Ae=class extends K{};Ae.errorCode="unauthorized_client";var bt=class extends K{};bt.errorCode="unsupported_grant_type";var wt=class extends K{};wt.errorCode="invalid_scope";var St=class extends K{};St.errorCode="access_denied";var we=class extends K{};we.errorCode="server_error";var $t=class extends K{};$t.errorCode="temporarily_unavailable";var kt=class extends K{};kt.errorCode="unsupported_response_type";var Rt=class extends K{};Rt.errorCode="unsupported_token_type";var Pt=class extends K{};Pt.errorCode="invalid_token";var It=class extends K{};It.errorCode="method_not_allowed";var Tt=class extends K{};Tt.errorCode="too_many_requests";var Ue=class extends K{};Ue.errorCode="invalid_client_metadata";var Zt=class extends K{};Zt.errorCode="insufficient_scope";var Ot=class extends K{};Ot.errorCode="invalid_target";var ac={[vt.errorCode]:vt,[Ee.errorCode]:Ee,[Ce.errorCode]:Ce,[Ae.errorCode]:Ae,[bt.errorCode]:bt,[wt.errorCode]:wt,[St.errorCode]:St,[we.errorCode]:we,[$t.errorCode]:$t,[kt.errorCode]:kt,[Rt.errorCode]:Rt,[Pt.errorCode]:Pt,[It.errorCode]:It,[Tt.errorCode]:Tt,[Ue.errorCode]:Ue,[Zt.errorCode]:Zt,[Ot.errorCode]:Ot};var Se=class extends Error{constructor(t){super(t??"Unauthorized")}};function vd(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var To="code",Zo="S256";function bd(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&vd(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function wd(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":Sd(n,i,r);return;case"client_secret_post":$d(n,i,o);return;case"none":kd(n,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function Sd(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function $d(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function kd(e,t){t.set("client_id",e)}async function uc(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=oc.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:s}=o,c=ac[n]||we;return new c(i||"",s)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new we(n)}}async function Et(e,t){try{return await Oo(e,t)}catch(r){if(r instanceof Ee||r instanceof Ae)return await e.invalidateCredentials?.("all"),await Oo(e,t);if(r instanceof Ce)return await e.invalidateCredentials?.("tokens"),await Oo(e,t);throw r}}async function Oo(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let s=await e.discoveryState?.(),c,l,p,h=n;if(!h&&s?.resourceMetadataUrl&&(h=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await pc(l,{fetchFn:i}),!c)try{c=await lc(t,{resourceMetadataUrl:h},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let $=await Ed(t,{resourceMetadataUrl:h,fetchFn:i});l=$.authorizationServerUrl,p=$.authorizationServerMetadata,c=$.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let _=await Pd(t,e,c),z=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,m=await Promise.resolve(e.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let $=p?.client_id_metadata_document_supported===!0,O=e.clientMetadataUrl;if(O&&!Rd(O))throw new Ue(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if($&&O)m={client_id:O},await e.saveClientInformation?.(m);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let x=await jd(l,{metadata:p,clientMetadata:e.clientMetadata,scope:z,fetchFn:i});await e.saveClientInformation(x),m=x}}let k=!e.redirectUrl;if(r!==void 0||k){let $=await Nd(e,l,{metadata:p,resource:_,authorizationCode:r,fetchFn:i});return await e.saveTokens($),"AUTHORIZED"}let P=await e.tokens();if(P?.refresh_token)try{let $=await Ud(l,{metadata:p,clientInformation:m,refreshToken:P.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens($),"AUTHORIZED"}catch($){if(!(!($ instanceof K)||$ instanceof we))throw $}let ee=e.state?await e.state():void 0,{authorizationUrl:G,codeVerifier:A}=await Cd(l,{metadata:p,clientInformation:m,state:ee,redirectUrl:e.redirectUrl,scope:z,resource:_});return await e.saveCodeVerifier(A),await e.redirectToAuthorization(G),"REDIRECT"}function Rd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Pd(e,t,r){let o=ic(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!sc({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function Co(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Eo(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=Eo(e,"scope")||void 0,c=Eo(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}function Eo(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function lc(e,t,r=fetch){let o=await Zd(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ec.parse(await o.json())}async function Ao(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Ao(e,void 0,r):void 0;throw o}}function Id(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function cc(e,t,r=fetch){return await Ao(e,{"MCP-Protocol-Version":t},r)}function Td(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Zd(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??xo,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=Id(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let c=await cc(s,i,r);if(!o?.metadataUrl&&Td(c,n.pathname)){let l=new URL(`/.well-known/${t}`,n);c=await cc(l,i,r)}return c}function Od(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function pc(e,{fetchFn:t=fetch,protocolVersion:r=xo}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=Od(e);for(let{url:i,type:s}of n){let c=await Ao(i,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?Io.parse(await c.json()):tc.parse(await c.json())}}}async function Ed(e,t){let r,o;try{r=await lc(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let n=await pc(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}async function Cd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(To))throw new Error(`Incompatible auth server: does not support response type ${To}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Zo))throw new Error(`Incompatible auth server: does not support code challenge method ${Zo}`)}else c=new URL("/authorize",e);let l=await Po(),p=l.code_verifier,h=l.code_challenge;return c.searchParams.set("response_type",To),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",Zo),c.searchParams.set("redirect_uri",String(o)),i&&c.searchParams.set("state",i),n&&c.searchParams.set("scope",n),n?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}function Ad(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function dc(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),n)await n(l,r,c,t);else if(o){let h=t?.token_endpoint_auth_methods_supported??[],_=bd(o,h);wd(_,o,l,r)}let p=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!p.ok)throw await uc(p);return rc.parse(await p.json())}async function Ud(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await dc(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:n,fetchFn:s});return{refresh_token:o,...l}}async function Nd(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=Ad(n,p,e.redirectUrl)}let l=await e.clientInformation();return dc(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function jd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await uc(s);return nc.parse(await s.json())}var Ct=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},mc=10,Ld=13,Ne=32;function Uo(e){}function gc(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Uo,onError:r=Uo,onRetry:o=Uo,onComment:n,maxBufferSize:i}=e,s=[],c=0,l=!0,p,h="",_=0,z,m=!1;function k(y){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,y.charCodeAt(0)===239&&y.charCodeAt(1)===187&&y.charCodeAt(2)===191&&(y=y.slice(3))),s.length===0){let D=ee(y);D!==""&&(s.push(D),c=D.length),P();return}if(y.indexOf(`
|
|
34
|
+
`)===-1&&y.indexOf("\r")===-1){s.push(y),c+=y.length,P();return}s.push(y);let x=s.join("");s.length=0,c=0;let S=ee(x);S!==""&&(s.push(S),c=S.length),P()}function P(){i!==void 0&&(c+h.length<=i||(m=!0,s.length=0,c=0,p=void 0,h="",_=0,z=void 0,r(new Ct(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function ee(y){let x=0;if(y.indexOf("\r")===-1){let S=y.indexOf(`
|
|
35
|
+
`,x);for(;S!==-1;){if(x===S){_>0&&t({id:p,event:z,data:h}),p=void 0,h="",_=0,z=void 0,x=S+1,S=y.indexOf(`
|
|
36
|
+
`,x);continue}let D=y.charCodeAt(x);if(fc(y,x,D)){let H=y.charCodeAt(x+5)===Ne?x+6:x+5,ae=y.slice(H,S);if(_===0&&y.charCodeAt(S+1)===mc){t({id:p,event:z,data:ae}),p=void 0,h="",z=void 0,x=S+2,S=y.indexOf(`
|
|
37
|
+
`,x);continue}h=_===0?ae:`${h}
|
|
38
|
+
${ae}`,_++}else hc(y,x,D)?z=y.slice(y.charCodeAt(x+6)===Ne?x+7:x+6,S)||void 0:G(y,x,S);x=S+1,S=y.indexOf(`
|
|
39
|
+
`,x)}return y.slice(x)}for(;x<y.length;){let S=y.indexOf("\r",x),D=y.indexOf(`
|
|
40
|
+
`,x),H=-1;if(S!==-1&&D!==-1?H=S<D?S:D:S!==-1?S===y.length-1?H=-1:H=S:D!==-1&&(H=D),H===-1)break;G(y,x,H),x=H+1,y.charCodeAt(x-1)===Ld&&y.charCodeAt(x)===mc&&x++}return y.slice(x)}function G(y,x,S){if(x===S){$();return}let D=y.charCodeAt(x);if(fc(y,x,D)){let de=y.charCodeAt(x+5)===Ne?x+6:x+5,Me=y.slice(de,S);h=_===0?Me:`${h}
|
|
41
|
+
${Me}`,_++;return}if(hc(y,x,D)){z=y.slice(y.charCodeAt(x+6)===Ne?x+7:x+6,S)||void 0;return}if(D===105&&y.charCodeAt(x+1)===100&&y.charCodeAt(x+2)===58){let de=y.slice(y.charCodeAt(x+3)===Ne?x+4:x+3,S);p=de.includes("\0")?void 0:de;return}if(D===58){if(n){let de=y.slice(x,S);n(de.slice(y.charCodeAt(x+1)===Ne?2:1))}return}let H=y.slice(x,S),ae=H.indexOf(":");if(ae===-1){A(H,"",H);return}let De=H.slice(0,ae),gr=H.charCodeAt(ae+1)===Ne?2:1,it=H.slice(ae+gr);A(De,it,H)}function A(y,x,S){switch(y){case"event":z=x||void 0;break;case"data":h=_===0?x:`${h}
|
|
42
|
+
${x}`,_++;break;case"id":p=x.includes("\0")?void 0:x;break;case"retry":/^\d+$/.test(x)?o(parseInt(x,10)):r(new Ct(`Invalid \`retry\` value: "${x}"`,{type:"invalid-retry",value:x,line:S}));break;default:r(new Ct(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:x,line:S}));break}}function $(){_>0&&t({id:p,event:z,data:h}),p=void 0,h="",_=0,z=void 0}function O(y={}){if(y.consume&&s.length>0){let x=s.join("");G(x,0,x.length)}l=!0,p=void 0,h="",_=0,z=void 0,s.length=0,c=0,m=!1}return{feed:k,reset:O}}function fc(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function hc(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var ur=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(s){i=gc({onEvent:c=>{s.enqueue(c)},onError(c){typeof t=="function"&&t(c),(t==="terminate"||c.type==="max-buffer-size-exceeded")&&s.error(c)},onRetry:r,onComment:o,maxBufferSize:n})},transform(s){i.feed(s)}})}};var Dd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Re=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},lr=class{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Xa(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Dd}async _authThenStart(){if(!this._authProvider)throw new Se("No auth provider");let t;try{t=await Et(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Se;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(t.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=cr(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new Re(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,t,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,t),n)}_scheduleReconnection(t,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},n)}_handleSseStream(t,r,o){if(!t)return;let{onresumptiontoken:n,replayMessageId:i}=r,s,c=!1,l=!1;(async()=>{try{let h=t.pipeThrough(new TextDecoderStream).pipeThrough(new ur({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:k}=await h.read();if(k)break;if(m.id&&(s=m.id,c=!0,n?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let P=Ye.parse(JSON.parse(m.data));ka(P)&&(l=!0,i!==void 0&&(P.id=i)),this.onmessage?.(P)}catch(P){this.onerror?.(P)}}(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(h){if(this.onerror?.(new Error(`SSE stream disconnected: ${h}`)),(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Se("No auth provider");if(await Et(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:$a(t)?t.id:void 0}).catch(z=>this.onerror?.(z));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),l=c.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!c.ok){let z=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Re(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:m,scope:k}=Co(c);if(this._resourceMetadataUrl=m,this._scope=k,await Et(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:m,scope:k,error:P}=Co(c);if(P==="insufficient_scope"){let ee=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===ee)throw new Re(403,"Server returned 403 after trying upscoping");if(k&&(this._scope=k),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=ee??void 0,await Et(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Se;return this.send(t)}}throw new Re(c.status,`Error POSTing to endpoint: ${z}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Oa(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(z=>this.onerror?.(z));return}let h=(Array.isArray(t)?t:[t]).filter(z=>"method"in z&&"id"in z&&z.id!==void 0).length>0,_=c.headers.get("content-type");if(h)if(_?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:n},!1);else if(_?.includes("application/json")){let z=await c.json(),m=Array.isArray(z)?z.map(k=>Ye.parse(k)):[Ye.parse(z)];for(let k of m)this.onmessage?.(k)}else throw await c.body?.cancel(),new Re(-1,`Unexpected content type: ${_}`);else await c.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new Re(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function _c(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as Md,writeFileSync as Fd,readFileSync as Vd,readdirSync as qd,statSync as xc,unlinkSync as Bd,chmodSync as zc}from"node:fs";import{join as pr}from"node:path";import{homedir as Wd}from"node:os";var Jd="0.3.0",Hd=new Set(["choose_identity","create_identity","create_root_identity"]),yc=e=>new Promise(t=>setTimeout(t,e)),Gd=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,Kd=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,vc=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},bc=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,wc=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function $c(e){let t=new URL(e.url),r=(...b)=>process.stderr.write(`[ours-proxy] ${b.join(" ")}
|
|
43
|
+
`),o=b=>Number.isInteger(b)&&b>1,n=Number(process.env.OURS_CLIENT_PID),i=o(n)?n:o(process.ppid)?process.ppid:process.pid,s=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${i}`,c=null,l=null,p,h=null,_=new Map,z=null,m=wc?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,k=e.stateDir??process.env.OURS_STATE_DIR??pr(Wd(),".ours"),P=pr(k,"session-restore"),ee=m&&/^[A-Za-z0-9._-]{1,200}$/.test(m)?m:null,G=ee?pr(P,`${ee}.json`):null,A=!1,$=null;function O(b){if(G)try{Md(P,{recursive:!0,mode:448}),Fd(G,JSON.stringify({claudeSessionId:m,identity:b,boundAt:new Date().toISOString()}),{mode:384}),zc(P,448),zc(G,384)}catch(I){r("restore persist failed (non-fatal):",String(I))}}function y(){if(!G)return null;try{if(Date.now()-xc(G).mtimeMs>bc)return null;let b=JSON.parse(Vd(G,"utf8"));return(typeof b.identity=="string"?b.identity.trim():"")||null}catch{return null}}function x(){try{let b=Date.now();for(let I of qd(P)){if(!I.endsWith(".json"))continue;let E=pr(P,I);try{b-xc(E).mtimeMs>bc&&(Bd(E),r("session-restore: pruned expired record",I))}catch{}}}catch{}}let S=null,D=!1,H=!1,ae=!1,De=[],gr="__ours_proxy_init__",it=0,de=new Set,Me=new Set,Ie=new ar;Ie.onmessage=b=>{let I=[],E=!1;for(let he of Sc(b)){let Y=he;if(Y.method==="notifications/initialized"&&(E=!0),Gd(Y)){if(Y.method==="initialize"&&(c=Y,l)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Ie.send({jsonrpc:"2.0",id:Y.id,result:l}).catch(te=>r("local initialize reply failed:",String(te)));continue}if(Y.method==="tools/call"){let te=Y.params;te&&Hd.has(te.name??"")&&typeof te.arguments?.name=="string"&&_.set(Y.id,te.arguments.name)}}I.push(Y)}if(I.length){let he=Array.isArray(b)?I:I[0];Bo(he)}E&&Lc()},Ie.onclose=()=>void _r(0),Ie.onerror=b=>r("downstream error:",String(b));function Lc(){if(A||!h)return;A=!0;let b=`__ours_proxy_restore_${++it}__`;de.add(b),$=b,r("session-restore: self-recovering bound identity",`"${h}"`),Bo({jsonrpc:"2.0",id:b,method:"tools/call",params:{name:"choose_identity",arguments:{name:h}}})}function Bo(b){if(D&&S){let I=S;S.send(b).catch(E=>{r("upstream send failed:",String(E)),De.push(b),Wo(I,"send failed")})}else De.push(b)}function Wo(b,I){if(H||ae||S!==null&&b!==S)return;r(`upstream dropped (${I}) \u2014 reconnecting`),D=!1;let E=S;S=null;try{E?.close?.()}catch{}Mc()}function Dc(b){b.onmessage=I=>{let E=[];for(let he of Sc(I)){let Y=he;if(Kd(Y)){let te=Y.id,xr=Y.result?.protocolVersion;if(xr&&(Me.has(te)||Jo(te))){p=xr;try{S?.setProtocolVersion?.(xr)}catch{}if(l==null&&Jo(te)&&!de.has(te)){let ye=Y.result??null;ye&&z&&(ye.instructions=`${ye.instructions?ye.instructions+`
|
|
43
44
|
|
|
44
|
-
`:""}${
|
|
45
|
-
`),
|
|
46
|
-
`),
|
|
47
|
-
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=p==="y"||p==="yes"}finally{s.close()}if(!c){d("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await
|
|
48
|
-
${
|
|
49
|
-
`))
|
|
45
|
+
`:""}${z}`),l=ye}Me.delete(te)}if(de.has(te)){de.delete(te),te===$&&($=null,vc(Y)&&(h=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(_.has(te)){let ye=_.get(te);_.delete(te),vc(Y)||(h=ye,r("bound identity tracked:",ye),O(ye))}}E.push(Y)}if(E.length){let he=Array.isArray(I)?E:E[0];Ie.send(he).catch(Y=>r("downstream send failed:",String(Y)))}},b.onerror=I=>r("upstream error:",String(I)),b.onclose=()=>Wo(b,"closed")}let Jo=b=>c!=null&&c.id===b;async function Ho(){e.ensureDaemon&&await e.ensureDaemon().catch(I=>r("ensureDaemon:",String(I)));let b=new lr(t,{requestInit:{headers:{"x-ours-lease-token":s,"x-ours-client-pid":String(i),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(Dc(b),await b.start(),p)try{b.setProtocolVersion?.(p)}catch{}S=b}async function Go(b,I){I&&b.id!==void 0&&de.add(b.id),await S.send(b)}async function Mc(){if(ae||H)return;ae=!0;let b=500;for(;;){if(H){ae=!1;return}try{if(await Ho(),c){let E=`${gr}${it}`;Me.add(E),await Go({...c,id:E},!0),await S.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(h){let E=`__ours_proxy_rebind_${++it}__`;await Go({jsonrpc:"2.0",id:E,method:"tools/call",params:{name:"choose_identity",arguments:{name:h}}},!0)}D=!0;let I=De.splice(0);for(let E of I)await S.send(E).catch(he=>r("flush failed:",String(he)));r("upstream reconnected",h?`(re-bound "${h}")`:""),ae=!1;return}catch(I){r("reconnect attempt failed:",String(I)),await yc(b),b=Math.min(Math.floor(b*1.5),1e4)}}}async function _r(b){if(!H){H=!0;try{await S?.close()}catch{}try{await Ie.close()}catch{}process.exit(b)}}process.on("SIGINT",()=>void _r(0)),process.on("SIGTERM",()=>void _r(0));async function Fc(){let b=new URL(t.href);b.pathname="/state-dir";let I;try{I=await(await fetch(b,{signal:AbortSignal.timeout(3e3)})).json()}catch(E){r("compat handshake: could not read daemon /state-dir, proceeding:",String(E));return}z=_c({selfVersion:Jd,daemonVersion:typeof I?.version=="string"?I.version:null}),z&&r(z)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(E=>r("ensureDaemon:",String(E))),await Fc();let b=500;for(;;)try{await Ho();break}catch(E){r("initial upstream connect failed, retrying:",String(E)),await yc(b),b=Math.min(Math.floor(b*1.5),1e4)}D=!0;let I=De.splice(0);for(let E of I)await S.send(E).catch(he=>r("flush failed:",String(he)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),m){x();let b=y();b&&(h=b,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${b}"`))}else wc&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Ie.start(),r("proxy started (stdio transport up)")}function Sc(e){return Array.isArray(e)?e:[e]}var tt=br(),ue=tt.stateDir,J=tt.port,Do=Xo(tt,{generate:!1})?.token??null,qo=()=>Do?{"x-ours-api-token":Do}:{},rt=tt.brokerUrl,Le=$e(ue,"daemon.pid"),je=$e(ue,"daemon.log"),nt=Xd(import.meta.url),d=(...e)=>process.stdout.write(`${e.join(" ")}
|
|
46
|
+
`),V=(...e)=>process.stderr.write(`${e.join(" ")}
|
|
47
|
+
`),Qe="0.3.0";async function Mo(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),o=await fetch(`http://127.0.0.1:${J}${e}`,{signal:t.signal});if(clearTimeout(r),o.ok){let n=await o.json();if(n&&typeof n.version=="string")return n}}catch{}return null}function Rc(e){if(d(` cli: v${Qe}`),e?.version){let t=e.version!==Qe;d(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${Qe}`:""))}else d(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var hr=e=>new Promise(t=>setTimeout(t,e));function em(){try{let e=parseInt(R.readFileSync(Le,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Fo(e){try{return process.kill(e,0),!0}catch{return!1}}function Ut(){let e=em();if(e&&Fo(e))return e;if(e)try{R.rmSync(Le,{force:!0})}catch{}return null}function ot(e,t=1e3){return new Promise(r=>{let o=Yd({host:"127.0.0.1",port:e}),n=i=>{o.destroy(),r(i)};o.setTimeout(t),o.once("connect",()=>n(!0)),o.once("timeout",()=>n(!1)),o.once("error",()=>n(!1))})}async function Cc(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await ot(e))return!0;await hr(400)}return!1}async function Pc(){let e=Ut();if(e){d(`ours-mcp is already running (pid ${e}, port ${J}).`);return}R.mkdirSync(ue,{recursive:!0});let t=R.openSync(je,"a"),r=Zc(process.execPath,[nt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(J),OURS_BROKER_URL:rt,OURS_STATE_DIR:ue}});r.unref(),r.pid||(V("failed to spawn the daemon."),process.exit(1)),R.writeFileSync(Le,String(r.pid)),d(`starting ours-mcp (pid ${r.pid})\u2026`),await Cc(J)?(d(`ours-mcp is up on http://localhost:${J}/mcp`),d(` broker: ${rt}`),d(` state: ${ue}`),d(` logs: ${je}`)):(V(`daemon started (pid ${r.pid}) but port ${J} did not open within 30s \u2014 check ${je}.`),process.exit(1))}async function tm(){if(!await ot(J)){if(!Ut()){R.mkdirSync(ue,{recursive:!0});let e=R.openSync(je,"a"),t=Zc(process.execPath,[nt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(J),OURS_BROKER_URL:rt,OURS_STATE_DIR:ue}});if(t.unref(),t.pid)try{R.writeFileSync(Le,String(t.pid))}catch{}}await Cc(J)}}async function mr(){let e=Ut();if(!e){d("ours-mcp is not running.");return}d(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){V(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Fo(e);t++)await hr(200);if(Fo(e)){V(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{R.rmSync(Le,{force:!0})}catch{}d("stopped.")}async function rm(){let e=Ut();if(!e){if(await ot(J)){let o=await Mo();d("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),d(` url: http://localhost:${J}/mcp (reachable)`),Rc(o);return}d("ours-mcp: stopped"),d(` cli: v${Qe}`),process.exitCode=1;return}let t=await ot(J),r=t?await Mo():null;d("ours-mcp: running"),d(` pid: ${e}`),d(` url: http://localhost:${J}/mcp ${t?"(reachable)":"(port not answering!)"}`),d(` broker: ${rt}`),d(` state: ${ue}`),d(` logs: ${je}`),Rc(r)}async function om(){if(d(`ours-mcp v${Qe}`),await ot(J)){let e=await Mo();e?.version?d(`running daemon: v${e.version}`+(e.version!==Qe?" (differs \u2014 restart to update)":"")):d("running daemon: version unknown (predates /version)")}else d("daemon: not running")}async function nm(){let e=br(),t=Lt();d(`ours-mcp setup \u2014 ${t}`),d("Enter a value, or press Enter to keep the current [bracketed] one."),d("");let r=dr({input:process.stdin,output:process.stdout}),o;try{let p=async(O,y)=>{let x=(await r.question(` ${O} [${y}]: `)).trim();return x===""?y:x},h=await p("broker URL",e.brokerUrl),_=await p("HTTP port",String(e.port)),z=await p("state dir",e.stateDir),m=await p("GC interval (ms)",String(e.gcIntervalMs)),k=await p("proxy auto-starts daemon (true/false)",String(e.autoStart)),P=await p("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility),ee=parseInt(_,10);(!Number.isFinite(ee)||ee<=0)&&(V(`invalid port: ${_}`),process.exit(1));let G=parseInt(m,10);(!Number.isFinite(G)||G<=0)&&(V(`invalid GC interval: ${m}`),process.exit(1));let A=k.toLowerCase()==="true"||k==="1",$=P.trim().toLowerCase();st.includes($)||(V(`invalid visibility: ${P} (expected one of ${st.join(", ")})`),process.exit(1)),o={brokerUrl:h,port:ee,stateDir:Ec(z),gcIntervalMs:G,autoStart:A,apiVisibility:$,...e.apiToken?{apiToken:e.apiToken}:{}}}finally{r.close()}Qo(o),d(""),d(`wrote ${t} (mode 0600):`),d(JSON.stringify(o,null,2));let n=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART","OURS_API_VISIBILITY","OURS_API_TOKEN"].filter(p=>process.env[p]!==void 0);n.length&&(d(""),d(`note: these env vars are set and OVERRIDE the file at runtime: ${n.join(", ")}`));let i=Ut();if(!i)return;let s=dr({input:process.stdin,output:process.stdout}),c=!1;try{let p=(await s.question(`
|
|
48
|
+
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=p==="y"||p==="yes"}finally{s.close()}if(!c){d("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await mr();let l=fr(process.execPath,[nt,"start"],{stdio:"inherit"});l.status!==0&&process.exit(l.status??1)}function No(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function jo(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function im(e){let t=jo(e,"--name"),r=No(e,"--force-bind","--no-force-bind"),o=No(e,"--local-book","--no-local-book"),n=No(e,"--auto-accept-local","--no-auto-accept-local"),i=e.includes("--overwrite"),s=e.includes("--print"),c=jo(e,"--path")??jo(e,"--dir")??process.cwd(),l=t!==void 0||r.set||o.set||n.set||s,p;if(l?((!t||!t.trim())&&(V("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),p={name:t.trim(),force:r.value??!1,exposeLocal:o.value??!0,localAutoAccept:n.value??!0}):p=await sm(),s){d(JSON.stringify(Dt(p),null,2));return}let h=wr(c);if(!i&&R.existsSync(h)){l&&(V(`define-local-identity-file: ${h} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let z=dr({input:process.stdin,output:process.stdout}),m=!1;try{let k=(await z.question(`
|
|
49
|
+
${h} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();m=k==="y"||k==="yes"}finally{z.close()}if(!m){d("aborted \u2014 nothing written.");return}}let _=en(c,p,!0);d(""),d(`wrote ${_}:`),d(JSON.stringify(Dt(p),null,2))}async function sm(){d("ours-mcp define-local-identity-file \u2014 interactive"),d(`Answer the prompts; the result is written to ${$e(process.cwd(),Nt)}.`),d("");let e=dr({input:process.stdin,output:process.stdout});try{let t=async(s,c)=>{let l=c?"Y/n":"y/N",p=(await e.question(` ${s} [${l}]: `)).trim().toLowerCase();return p===""?c:p==="y"||p==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||d(" (name is required)");let o=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),n=await t("Add to the host-local contact book?",!0),i=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:o,exposeLocal:n,localAutoAccept:i}}finally{e.close()}}function Ac(e,t){t.event==="local_contact_request"?d(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"?d(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`):d(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:""))}function Pe(e){V(`ours-mcp watch: ${e}`),process.exit(1)}async function am(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${J}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let o=await r.json();return typeof o.stateDir=="string"&&o.stateDir?Ec(o.stateDir):ue}}catch{}return null}var cm=e=>`http://127.0.0.1:${J}/identities/${encodeURIComponent(e)}/notifications`;async function Ic(e){let t=async n=>{let i=new AbortController,s=setTimeout(()=>i.abort(),35e3),c;try{c=await fetch(`${cm(e)}?since=${n}`,{headers:qo(),signal:i.signal})}finally{clearTimeout(s)}if(c.status===401&&Pe(`daemon rejected the API token (401) for identity "${e}". Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode).`),!c.ok)throw new Error(`daemon returned HTTP ${c.status}`);return await c.json()},r=(await t("tip")).cursor??0,o=0;for(;;)try{let n=await t(String(r));if(o=0,Array.isArray(n.events))for(let i of n.events)Ac(e,i);typeof n.cursor=="number"&&(r=n.cursor)}catch(n){o=Math.min(o+1e3,5e3),V(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(n?.message??n)}), retrying\u2026`),await hr(o)}}async function um(e){if(e){await Ic(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${J}/identities`,{headers:qo()});if(r.status===401&&Pe("daemon rejected the API token (401). Set OURS_API_TOKEN or run watch as the daemon owner."),r.ok){let o=await r.json();for(let n of o.identities??[]){let i=typeof n?.name=="string"?n.name:void 0;i&&!t.has(i)&&(t.add(i),Ic(i))}}}catch{}await hr(3e3)}}var Lo=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function lm(e,t){try{R.readdirSync(e)}catch(s){Pe(`cannot watch \u2014 the daemon API is unreachable AND ${e} is not readable (${s?.code??s}). On a multi-user host, run watch as the daemon owner, or enable the daemon API (start the daemon) so watch can stream over HTTP.`)}if(t)try{R.readdirSync($e(e,t))}catch(s){Pe(`cannot watch identity "${t}" \u2014 ${$e(e,t)} is not readable (${s?.code??s}). Is the daemon running and the name correct?`)}let r=new Map,o=s=>{let c;try{c=R.readdirSync(e,{withFileTypes:!0}).filter(l=>l.isDirectory()).map(l=>l.name)}catch(l){Lo(l)&&Pe(`lost read access to ${e} (${l.code}) \u2014 cannot watch.`);return}for(let l of c){if(t&&l!==t)continue;let p=$e(e,l,"notifications.log"),h;try{h=R.statSync(p).size}catch(m){Lo(m)&&Pe(`cannot read ${p} (${m.code}) \u2014 cannot watch identity "${l}".`);continue}let _=r.get(p);if(_===void 0&&(_=s?h:0,r.set(p,_),s))continue;if(h<=_){h<_&&r.set(p,h);continue}let z;try{let m=R.openSync(p,"r"),k=Buffer.alloc(h-_);R.readSync(m,k,0,k.length,_),R.closeSync(m),z=k.toString("utf8")}catch(m){Lo(m)&&Pe(`cannot read ${p} (${m.code}) \u2014 cannot watch identity "${l}".`);continue}r.set(p,h);for(let m of z.split(`
|
|
50
|
+
`))if(m.trim())try{Ac(l,JSON.parse(m))}catch{}}};V(`ours-mcp watch: daemon API unreachable \u2014 falling back to file poll of ${e} (Ctrl-C to stop)`),o(!0);let n=setInterval(()=>o(!1),1e3),i=()=>{clearInterval(n),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}async function pm(){try{let e=await fetch(`http://127.0.0.1:${J}/identities`,{headers:qo()});return e.status===401&&Pe("daemon rejected the API token (401). Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode)."),e.status===404?"file":e.ok?"api":"file"}catch{return"file"}}async function dm(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await am()!==null&&await pm()==="api"){V(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${J} (Ctrl-C to stop)`),await um(e);return}lm(ue,e)}var At="ours.service",Uc="solutions.adaptframework.ours";function Nc(){return $e(Oc(),".config","systemd","user",At)}function jc(){return $e(Oc(),"Library","LaunchAgents",`${Uc}.plist`)}function et(e,t){return fr(e,t,{stdio:"inherit"}).status===0}function mm(){let e=Nc();R.mkdirSync(Vo(e),{recursive:!0});let t=`[Unit]
|
|
50
51
|
Description=ours MCP daemon (secure agent-to-agent messaging over ADAPT)
|
|
51
52
|
After=network-online.target
|
|
52
53
|
Wants=network-online.target
|
|
53
54
|
|
|
54
55
|
[Service]
|
|
55
56
|
Type=simple
|
|
56
|
-
ExecStart=${process.execPath} ${
|
|
57
|
+
ExecStart=${process.execPath} ${nt} serve
|
|
57
58
|
Environment=OURS_TRANSPORT=http
|
|
58
|
-
Environment=OURS_PORT=${
|
|
59
|
-
Environment=OURS_BROKER_URL=${
|
|
60
|
-
Environment=OURS_STATE_DIR=${
|
|
59
|
+
Environment=OURS_PORT=${J}
|
|
60
|
+
Environment=OURS_BROKER_URL=${rt}
|
|
61
|
+
Environment=OURS_STATE_DIR=${ue}
|
|
61
62
|
Restart=on-failure
|
|
62
63
|
RestartSec=2
|
|
63
64
|
|
|
64
65
|
[Install]
|
|
65
66
|
WantedBy=default.target
|
|
66
|
-
`;
|
|
67
|
+
`;R.writeFileSync(e,t),d(`wrote ${e}`),et("systemctl",["--user","daemon-reload"]),et("systemctl",["--user","enable","--now",At])||(V("failed to enable/start the service via systemctl --user."),process.exit(1)),et("loginctl",["enable-linger",kc().username])||(V("warning: could not enable linger \u2014 the daemon may not start until you log in."),V(` run manually: loginctl enable-linger ${kc().username}`)),d(""),d("ours-mcp installed as a systemd user service and started."),d(` status: systemctl --user status ${At}`),d(` logs: journalctl --user -u ${At} -f`),d(" remove: ours-mcp uninstall-service")}function fm(){et("systemctl",["--user","disable","--now",At]);let e=Nc();try{R.rmSync(e,{force:!0}),d(`removed ${e}`)}catch(t){V(`failed to remove ${e}: ${String(t)}`)}et("systemctl",["--user","daemon-reload"]),d("ours-mcp service uninstalled.")}function hm(){let e=jc();R.mkdirSync(Vo(e),{recursive:!0});let t=`<?xml version="1.0" encoding="UTF-8"?>
|
|
67
68
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
68
69
|
<plist version="1.0">
|
|
69
70
|
<dict>
|
|
70
|
-
<key>Label</key><string>${
|
|
71
|
+
<key>Label</key><string>${Uc}</string>
|
|
71
72
|
<key>ProgramArguments</key>
|
|
72
73
|
<array>
|
|
73
74
|
<string>${process.execPath}</string>
|
|
74
|
-
<string>${
|
|
75
|
+
<string>${nt}</string>
|
|
75
76
|
<string>serve</string>
|
|
76
77
|
</array>
|
|
77
78
|
<key>EnvironmentVariables</key>
|
|
78
79
|
<dict>
|
|
79
80
|
<key>OURS_TRANSPORT</key><string>http</string>
|
|
80
|
-
<key>OURS_PORT</key><string>${
|
|
81
|
-
<key>OURS_BROKER_URL</key><string>${
|
|
82
|
-
<key>OURS_STATE_DIR</key><string>${
|
|
81
|
+
<key>OURS_PORT</key><string>${J}</string>
|
|
82
|
+
<key>OURS_BROKER_URL</key><string>${rt}</string>
|
|
83
|
+
<key>OURS_STATE_DIR</key><string>${ue}</string>
|
|
83
84
|
</dict>
|
|
84
85
|
<key>RunAtLoad</key><true/>
|
|
85
86
|
<key>KeepAlive</key><true/>
|
|
86
|
-
<key>StandardOutPath</key><string>${
|
|
87
|
-
<key>StandardErrorPath</key><string>${
|
|
87
|
+
<key>StandardOutPath</key><string>${je}</string>
|
|
88
|
+
<key>StandardErrorPath</key><string>${je}</string>
|
|
88
89
|
</dict>
|
|
89
90
|
</plist>
|
|
90
|
-
`;
|
|
91
|
-
`),
|
|
91
|
+
`;R.writeFileSync(e,t),d(`wrote ${e}`);let r=`gui/${process.getuid()}`;fr("launchctl",["bootout",r,e],{stdio:"ignore"}),et("launchctl",["bootstrap",r,e])||(V("failed to load the launchd agent."),process.exit(1)),d(""),d("ours-mcp installed as a launchd agent and started."),d(" remove: ours-mcp uninstall-service")}function gm(){let e=jc(),t=`gui/${process.getuid()}`;fr("launchctl",["bootout",t,e],{stdio:"ignore"});try{R.rmSync(e,{force:!0}),d(`removed ${e}`)}catch(r){V(`failed to remove ${e}: ${String(r)}`)}d("ours-mcp service uninstalled.")}async function _m(){if(await mr(),process.platform==="linux")return mm();if(process.platform==="darwin")return hm();V(`install-service: unsupported platform "${process.platform}" (only linux/systemd and macOS/launchd).`),process.exit(1)}function xm(){if(process.platform==="linux")return fm();if(process.platform==="darwin")return gm();V(`uninstall-service: unsupported platform "${process.platform}".`),process.exit(1)}function Tc(){d("ours-mcp \u2014 daemon for the ours MCP server"),d(""),d("Usage: ours-mcp <command>"),d(" start start the daemon in the background"),d(" stop stop the running daemon"),d(" restart stop then start"),d(" status show whether the daemon is running (incl. CLI + running-daemon version)"),d(" version print the CLI version and the running daemon version (GET /version)"),d(" setup interactively edit the config file (broker / port / state dir / gc)"),d(" serve run in the foreground (used by start; handy for debugging)"),d(" watch [identity] stream one line per new inbound message (wake source for a Monitor)"),d(" proxy per-session stdio shim \u2192 daemon (stable binding; for the MCP client config)"),d(""),d(" define-local-identity-file write a .ours-identity workspace pin"),d(" interactive (default): 4-question survey, writes to CWD"),d(" scripted: --name <s> [--force-bind] [--local-book] [--auto-accept-local]"),d(" negate with --no-force-bind / --no-local-book / --no-auto-accept-local"),d(" --dir <path> | --path <file> (default CWD) \xB7 --overwrite \xB7 --print"),d(""),d(" install-service install + start a boot-persistent service (systemd/launchd)"),d(" uninstall-service stop + remove that service"),d(""),d("Config precedence (per field): env var > config.json > default."),d(" config.json: OURS_CONFIG, else ~/.ours/config.json \u2014 edit with `setup`."),d(" env: OURS_BROKER_URL, OURS_PORT (3050), OURS_STATE_DIR (~/.ours), OURS_GC_INTERVAL_MS (3600000), OURS_AUTOSTART (off)"),d("(install-service bakes the resolved config values into the service definition.)")}async function zm(){let e=process.argv[2]??"help";switch(e){case"serve":case"run":process.env.OURS_TRANSPORT||(process.env.OURS_TRANSPORT="http"),R.mkdirSync(ue,{recursive:!0}),R.writeFileSync(Le,String(process.pid));{let t=()=>{try{R.rmSync(Le,{force:!0})}catch{}};process.on("exit",t);for(let r of["SIGTERM","SIGINT"])process.on(r,()=>{t(),process.exit(0)})}await import(Qd($e(Vo(nt),"index.js")).href);break;case"start":await Pc();break;case"stop":await mr();break;case"restart":await mr(),await Pc();break;case"status":await rm();break;case"version":case"--version":case"-v":await om();break;case"setup":await nm();break;case"define-local-identity-file":await im(process.argv.slice(3));break;case"watch":await dm(process.argv[3]);break;case"proxy":!tt.autoStart&&!await ot(J)&&(V(`ours-mcp daemon is not running on port ${J} \u2014 start it with \`ours-mcp start\`.`),V("(or enable auto-start: `ours-mcp setup` \u2192 autoStart, or OURS_AUTOSTART=1)"),process.exit(1)),await $c({url:`http://127.0.0.1:${J}/mcp`,ensureDaemon:tt.autoStart?tm:void 0,stateDir:ue,apiToken:Do??void 0});break;case"install-service":await _m();break;case"uninstall-service":xm();break;case"help":case"--help":case"-h":Tc();break;default:V(`unknown command: ${e}
|
|
92
|
+
`),Tc(),process.exit(1)}}zm().catch(e=>{V(`ours-mcp error: ${e?.stack??e}`),process.exit(1)});
|